diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index 791c26556a..fba3886b5d 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -43,6 +43,45 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "atlas-core" version = "0.1.0" @@ -91,6 +130,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", + "untrusted 0.7.1", "zeroize", ] @@ -125,7 +165,16 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ - "bit-vec", + "bit-vec 0.10.1", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", ] [[package]] @@ -472,6 +521,26 @@ dependencies = [ "serde", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "deranged" version = "0.5.9" @@ -645,6 +714,7 @@ dependencies = [ "ed25519-dalek", "fleet-agent", "fleet-bridge", + "fleet-cert", "fleet-config", "fleet-dispatch", "fleet-dispatch-test", @@ -684,6 +754,20 @@ dependencies = [ "ureq", ] +[[package]] +name = "fleet-cert" +version = "0.1.0" +dependencies = [ + "aws-lc-rs", + "rcgen", + "rustls-pki-types", + "serde", + "serde_json", + "sha2", + "time", + "x509-parser", +] + [[package]] name = "fleet-config" version = "0.1.0" @@ -1110,6 +1194,12 @@ dependencies = [ "libc", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" @@ -1256,6 +1346,16 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -1289,6 +1389,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1354,6 +1463,16 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -1436,7 +1555,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set", - "bit-vec", + "bit-vec 0.10.1", "bitflags", "chacha20", "core_detect", @@ -1567,6 +1686,20 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "aws-lc-rs", + "pem", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "regex" version = "1.13.1" @@ -1606,7 +1739,7 @@ dependencies = [ "cfg-if", "getrandom 0.2.17", "libc", - "untrusted", + "untrusted 0.9.0", "windows-sys 0.52.0", ] @@ -1643,6 +1776,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + [[package]] name = "rustix" version = "1.1.6" @@ -1729,7 +1871,7 @@ dependencies = [ "aws-lc-rs", "ring", "rustls-pki-types", - "untrusted", + "untrusted 0.9.0", ] [[package]] @@ -1976,6 +2118,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -2229,6 +2382,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "untrusted" version = "0.9.0" @@ -2483,6 +2642,34 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "aws-lc-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec 0.9.1", + "time", +] + [[package]] name = "yoke" version = "0.8.4" @@ -2503,7 +2690,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -2544,7 +2731,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.9", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/pkgs/fleet/Cargo.toml b/pkgs/fleet/Cargo.toml index 0485392cb2..e208e6cb82 100644 --- a/pkgs/fleet/Cargo.toml +++ b/pkgs/fleet/Cargo.toml @@ -29,6 +29,7 @@ members = [ "crates/fleet-bridge", "crates/fleet-agent", "crates/fleet-kv", + "crates/fleet-cert", "crates/fleet", ] resolver = "2" @@ -52,6 +53,7 @@ fleet-laptop-agent = { path = "crates/fleet-laptop-agent" } fleet-search = { path = "crates/fleet-search", default-features = false } fleet-bridge = { path = "crates/fleet-bridge" } fleet-agent = { path = "crates/fleet-agent" } +fleet-cert = { path = "crates/fleet-cert" } serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 9b0f8ec110..5e78444fbc 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -304,7 +304,7 @@ and every build compiles it, so no build can know a domain another build forgot. The registered domains are `fleet queue`, `fleet serve`, `fleet proxy`, `fleet dispatch`, `fleet dispatch-test`, `fleet secrets`, `fleet gh`, `fleet bridge`, `fleet agent`, -`fleet shell`, `fleet search` and `fleet laptop-agent`, plus the +`fleet shell`, `fleet search`, `fleet laptop-agent` and `fleet cert`, plus the built-ins `fleet init`, `fleet session`, `fleet version`, `fleet capabilities` and `fleet help`. diff --git a/pkgs/fleet/crates/fleet-cert/Cargo.toml b/pkgs/fleet/crates/fleet-cert/Cargo.toml new file mode 100644 index 0000000000..82440fc02d --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "fleet-cert" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "The `fleet cert` domain: PKI/X.509 roots, issuers, leaves, chains and bundles over a library-first Rust API (developing-today/code#9157, spec doc/2026-11-13T01-34-11Z_design_fleet_ca_credentials_secrets)." + +[dependencies] +# rcgen is the certificate engine: key generation, TBS construction and +# signing for every registered algorithm, ML-DSA-44 included (RFC 9881 +# identifiers, via the aws-lc-rs backend — the ring backend has no +# ML-DSA). Certificates produced here verify in OpenSSL 3.5+. +rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "pem"] } +# Direct aws-lc-rs link for chain signature verification (all five +# registered algorithms, ML-DSA-44 included) — the same backend rcgen +# signs with, so verify semantics match the signer. +aws-lc-rs = { version = "1.18", default-features = false } +# Certificate parsing for inspect/validate/chain work (DER + PEM). +x509-parser = "0.18" +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +time = { version = "0.3", features = ["parsing", "formatting"] } +# PKCS#8 key wrapper rcgen's loader takes (rustls-pki-types). +rustls-pki-types = "1" + +[dev-dependencies] +# Integration tests drive the built library API end to end and shell +# out to `openssl` (when present) as the independent validator. +serde_json = { workspace = true } diff --git a/pkgs/fleet/crates/fleet-cert/README.md b/pkgs/fleet/crates/fleet-cert/README.md new file mode 100644 index 0000000000..daf06ebd2c --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/README.md @@ -0,0 +1,81 @@ +# fleet-cert — the `fleet cert` domain (alias `pki`) + +Phase 1 foundation slice of the fleet CA program +([#9155](https://github.com/developing-today/code/issues/9155), +tracking [#9157](https://github.com/developing-today/code/issues/9157)). +Implements the fleet architecture spec v0.3 +(`doc/2026-11-13T01-34-11Z_design_fleet_ca_credentials_secrets/sources/fleet_architecture_spec_v0_3.md`) +§§3, 5.4, 6, 7.1, 24, 26 for the core surface. Library-first per +§6.4: every CLI verb is a thin shell over this crate's API. + +## Landed surface + +- `fleet cert root create|inspect|list|validate` — root sets with + the §3.2 cross-signing graph (default set: 4 keys, 13 + certificates), ceremony-named key destination (§24.3). +- `fleet cert issuer create|inspect|list` — issuer sets per the + §24.2 matrix (default set, A+B: 8 keys, 26 certificates); + requires `--root` and `--root-key-dir`. +- `fleet cert leaf issue|inspect|list` — profiles mirroring + `pkgs/idp-pki`'s idp-ca: `server`, `client`, `saml-signing`, + `oidc-signing`; requires `--issuer-key-dir`. +- `fleet cert chain build|test` — signature-verified path building + (shortest path, path-length pruned) and validation under + all/classical/PQ trust selections. +- `fleet cert bundle inspect`, `profile list|show`, + `algorithms list|describe`, `explain`, `doctor`. +- Text and `--json` output; fleet exit-code contract (0/2/1). + +Not yet built (tracked as child issues under #9157): `revoke`/`crl`, +`ocsp`, `publish`, `dns`, `trust`, `key`, `format`, profile +validate/scaffold, algorithm benchmark/doctor, `batch`, +`inventory`, renew/rotate verbs, bundle pack/unpack/diff/migrate. + +## Design decisions worth knowing + +- **Engine**: rcgen 0.14 + aws-lc-rs for all five algorithms + (ed25519, p256, rsa-4096, gated rsa-2048, ml-dsa-44). ML-DSA-44 + is real FIPS 204 with the RFC 9881 identifiers, verified + independently by OpenSSL 3.5. +- **rcgen gap, worked around**: rcgen 0.14 cannot reload ML-DSA + keys (its PKCS#8 loaders have no PQ branch; the typed loader + panics). `MlDsa44Signer` implements rcgen's public + `SigningKey`/`PublicKeyData` traits over + `aws_lc_rs::signature::PqdsaKeyPair`, so reloaded PQ roots and + issuers sign through the same machinery as classical keys. +- **Cross-signing is data**: the signer→subject edge tables live + in `graph.rs` (`GraphPolicy`), shared by root creation, issuer + creation, bundle inventory validation, and tests. The §3.2 + asymmetry (ML-DSA signs no classical subject) is a table entry, + not a loop condition. +- **Signer source (§24.3)**: signing requests carry a required + `SignerSource`; there is no ambient key discovery anywhere in + the crate. Missing keys are policy errors naming the rule. +- **Path building**: iterative-deepening DFS with per-link + signature verification and path-length pruning. A root + cross-certificate is a CA certificate in the path, so an anchor + with pathLenConstraint 1 cannot top a leaf → issuer → cross → + root path; the validator enforces anchor constraints (RFC 5280 + §6.1 reading) and prefers the shorter directly-cross-signed + issuer variant. +- **Time (§5.4)**: Gregorian calendar arithmetic on RFC 3339 + instants (Feb 29 + 1y = Feb 28); `--valid-for` and `--not-after` + are mutually exclusive; leaf/issuer validity clamps to the + signer's window with the clamp recorded as a manifest warning. +- **Bundles (§7.1)**: `manifest.json` (`fleet-cert-manifest/v1`) + with per-certificate records parsed back from the issued DER + and a SHA-256 index over every artifact; loading a bundle + verifies the index, so tampering is a hard error. Private keys + are PKCS#8, mode 0600, under `private/` (0700). + +## Evidence + +`cargo test -p fleet-cert` — 19 unit tests (registry, time +grammar, naming, graph arithmetic, profiles, bundle round-trip) +and 7 integration tests in `tests/hierarchy.rs`, each naming its +oracle: spec inventory arithmetic (§§3.2/24.2), the crate +validator, the system `openssl` as an independent implementation +(classical, PQ, and cross-signed paths), the §24.1/§24.3 policy +gates, §5.4 clamping, and §7.1 tamper rejection. A PQ-policy +negative test proves a classical leaf is rejected under PQ-only +trust while an all-ML-DSA path validates. diff --git a/pkgs/fleet/crates/fleet-cert/src/algorithm.rs b/pkgs/fleet/crates/fleet-cert/src/algorithm.rs new file mode 100644 index 0000000000..4bfcc5491a --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/algorithm.rs @@ -0,0 +1,311 @@ +//! The algorithm registry (spec §§3.1, 6.3, 24.1). +//! +//! One table is the source of truth for every algorithm `fleet cert` +//! knows: its canonical id, its X.509 identifiers (RFC 9881 for +//! ML-DSA-44), whether the engine in this build can actually generate +//! and sign with it, and the policy class that governs it. Nothing +//! else in the crate hardcodes an algorithm fact. +//! +//! Support reality (verified 2026-11-23 against rcgen 0.14.10 + +//! aws-lc-rs on OpenSSL 3.5.9 as the independent validator): all five +//! registered algorithms generate, sign, and cross-sign for real — +//! ML-DSA-44 included, with the standardized RFC 9881 identifiers. +//! There is no stubbed algorithm in this registry. + +use crate::error::{CertError, Result}; +use serde::{Deserialize, Serialize}; + +/// A registered key/signature algorithm. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum AlgorithmId { + Ed25519, + P256, + Rsa4096, + Rsa2048, + MlDsa44, +} + +/// Whether the engine in this build can generate keys and sign. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum SupportStatus { + Supported, + Unsupported, +} + +/// The policy class an algorithm sits in (spec §24.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum PolicyClass { + /// In the default algorithm set. + Default, + /// Supported, but not in any default set; name it explicitly. + Supported, + /// Legacy/compatibility only. CA use requires the explicit + /// `--allow-legacy-root-strength` opt-in (spec §24.1(1): RSA-2048 + /// supplies ~112-bit security and is questionable as a new + /// long-lived root; leaf/compatibility use stays allowed). + LegacyGated, +} + +/// One registry row. +#[derive(Debug, Clone, Copy, Serialize)] +pub struct AlgorithmInfo { + pub id: AlgorithmId, + /// Canonical algorithm id (`ed25519`, `p256`, ...). + pub name: &'static str, + pub display_name: &'static str, + /// SubjectPublicKeyInfo algorithm OID, dotted string. + pub spki_oid: &'static str, + /// Signature algorithm OID, dotted string. + pub signature_oid: &'static str, + pub support: SupportStatus, + pub policy: PolicyClass, + /// Post-quantum (FIPS 204) — drives PQ trust selection (§3.2). + pub post_quantum: bool, + pub notes: &'static str, +} + +impl AlgorithmId { + pub fn info(self) -> AlgorithmInfo { + match self { + AlgorithmId::Ed25519 => AlgorithmInfo { + id: self, + name: "ed25519", + display_name: "Ed25519", + spki_oid: "1.3.101.112", + signature_oid: "1.3.101.112", + support: SupportStatus::Supported, + policy: PolicyClass::Default, + post_quantum: false, + notes: "Preferred classical performance root (spec §3.1).", + }, + AlgorithmId::P256 => AlgorithmInfo { + id: self, + name: "p256", + display_name: "P-256", + spki_oid: "1.2.840.10045.2.1", + signature_oid: "1.2.840.10045.4.3.2", + support: SupportStatus::Supported, + policy: PolicyClass::Default, + post_quantum: false, + notes: "ECDSA P-256 with SHA-256 (RFC 5758).", + }, + AlgorithmId::Rsa4096 => AlgorithmInfo { + id: self, + name: "rsa-4096", + display_name: "RSA-4096", + spki_oid: "1.2.840.113549.1.1.1", + signature_oid: "1.2.840.113549.1.1.11", + support: SupportStatus::Supported, + policy: PolicyClass::Default, + post_quantum: false, + notes: "Classical compatibility root; RSA/SHA-256 (spec §3.1).", + }, + AlgorithmId::Rsa2048 => AlgorithmInfo { + id: self, + name: "rsa-2048", + display_name: "RSA-2048", + spki_oid: "1.2.840.113549.1.1.1", + signature_oid: "1.2.840.113549.1.1.11", + support: SupportStatus::Supported, + policy: PolicyClass::LegacyGated, + post_quantum: false, + notes: "Legacy/compatibility profile (spec §24.1(1)): ~112-bit \ + classical security. CA/root use requires \ + --allow-legacy-root-strength; leaf use is allowed policy.", + }, + AlgorithmId::MlDsa44 => AlgorithmInfo { + id: self, + name: "ml-dsa-44", + display_name: "ML-DSA-44", + spki_oid: "2.16.840.1.101.3.4.3.17", + signature_oid: "2.16.840.1.101.3.4.3.17", + support: SupportStatus::Supported, + policy: PolicyClass::Default, + post_quantum: true, + notes: "FIPS 204 ML-DSA-44 with the standardized RFC 9881 \ + identifiers — not the pre-standard Dilithium2 scheme \ + (spec §3.1). NIST security category 2.", + }, + } + } + + pub fn name(self) -> &'static str { + self.info().name + } + + pub fn display_name(self) -> &'static str { + self.info().display_name + } + + pub fn is_post_quantum(self) -> bool { + self.info().post_quantum + } + + pub fn is_classical(self) -> bool { + !self.is_post_quantum() + } + + pub fn is_supported(self) -> bool { + matches!(self.info().support, SupportStatus::Supported) + } + + /// Parse one algorithm name or documented alias (spec §6.3). + /// Returns the algorithm plus an optional warning the caller must + /// surface (the `dilithium2` deprecated alias). Ambiguous input — + /// `dsa` above all — is rejected with suggestions, never guessed. + pub fn parse(input: &str) -> Result<(AlgorithmId, Option)> { + let norm = input.trim().to_ascii_lowercase().replace('_', "-"); + let warn = |a: AlgorithmId, w: &str| Ok((a, Some(w.to_string()))); + match norm.as_str() { + "ed25519" | "ed" => Ok((AlgorithmId::Ed25519, None)), + "p256" | "p-256" | "secp256r1" | "ecc" | "ecdsa" | "ec" => { + Ok((AlgorithmId::P256, None)) + } + "rsa-4096" | "rsa4096" | "rsa" => Ok((AlgorithmId::Rsa4096, None)), + "rsa-2048" | "rsa2048" => Ok((AlgorithmId::Rsa2048, None)), + "ml-dsa-44" | "ml-dsa" | "mldsa" | "mldsa44" | "ml-dsa44" => { + Ok((AlgorithmId::MlDsa44, None)) + } + "dilithium2" => warn( + AlgorithmId::MlDsa44, + "alias 'dilithium2' is deprecated: it maps to standardized \ + ML-DSA-44 (RFC 9881); pre-standard Dilithium2 keys are NOT \ + byte-compatible and are never silently equated (spec §6.3)", + ), + "dsa" => Err(CertError::usage( + "'dsa' is ambiguous and is rejected (spec §6.3): did you mean \ + 'ml-dsa-44' (post-quantum) or 'ecdsa'/'p256'?", + )), + other => Err(CertError::usage(format!( + "unknown algorithm '{other}': known algorithms are \ + ed25519, p256, rsa-4096, rsa-2048 (legacy), ml-dsa-44" + ))), + } + } +} + +/// Every registered algorithm, in canonical registry order. +pub fn registry() -> Vec { + [ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::Rsa2048, + AlgorithmId::MlDsa44, + ] + .iter() + .map(|a| a.info()) + .collect() +} + +/// The default root/issuer algorithm set (spec §§3.1, 24.3 example): +/// the three classical roots plus the ML-DSA-44 root. RSA-2048 is +/// deliberately absent — it is the legacy opt-in, not a default. +pub const DEFAULT_ALGORITHMS: &[AlgorithmId] = &[ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::MlDsa44, +]; + +/// The classical subset of the default set (trust bundle +/// `roots-classical`, spec §3.5). +pub const CLASSICAL_ALGORITHMS: &[AlgorithmId] = &[ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, +]; + +/// Parse a comma-separated algorithm list (spec §6.3 `--algorithms` +/// replacement semantics). Order is preserved; warnings are collected +/// for the caller to surface. Duplicates are preserved — a repeated +/// algorithm is meaningful input (distinct partition keys, §24.4) and +/// each caller decides what duplicates mean in its context. +pub fn parse_algorithm_list(input: &str) -> Result<(Vec, Vec)> { + let mut out = Vec::new(); + let mut warnings = Vec::new(); + for part in input.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let (algo, warn) = AlgorithmId::parse(part)?; + if let Some(w) = warn { + warnings.push(w); + } + out.push(algo); + } + if out.is_empty() { + return Err(CertError::usage("empty algorithm list")); + } + Ok((out, warnings)) +} + +/// Enforce the CA policy gate: any legacy-gated algorithm in a CA +/// (root or issuer) set requires the explicit opt-in (spec §24.1(1)). +pub fn check_ca_policy(algorithms: &[AlgorithmId], allow_legacy: bool) -> Result<()> { + for algo in algorithms { + if matches!(algo.info().policy, PolicyClass::LegacyGated) && !allow_legacy { + return Err(CertError::policy(format!( + "algorithm {} is a legacy/compatibility profile: CA use requires \ + the explicit --allow-legacy-root-strength opt-in (spec §24.1(1))", + algo.name() + ))); + } + if !algo.is_supported() { + return Err(CertError::policy(format!( + "algorithm {} is registered as UNSUPPORTED in this build", + algo.name() + ))); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn registry_covers_the_spec_root_set() { + let reg = registry(); + assert_eq!(reg.len(), 5); + let defaults: Vec<&str> = DEFAULT_ALGORITHMS.iter().map(|a| a.name()).collect(); + assert_eq!(defaults, ["ed25519", "p256", "rsa-4096", "ml-dsa-44"]); + // Exactly one PQ algorithm, and it carries the RFC 9881 OID. + let pq: Vec<&AlgorithmInfo> = reg.iter().filter(|i| i.post_quantum).collect(); + assert_eq!(pq.len(), 1); + assert_eq!(pq[0].signature_oid, "2.16.840.1.101.3.4.3.17"); + } + + #[test] + fn aliases_normalize_and_dsa_is_rejected() { + assert_eq!(AlgorithmId::parse("rsa").unwrap().0, AlgorithmId::Rsa4096); + assert_eq!(AlgorithmId::parse("P-256").unwrap().0, AlgorithmId::P256); + assert_eq!(AlgorithmId::parse("ed").unwrap().0, AlgorithmId::Ed25519); + let (a, w) = AlgorithmId::parse("dilithium2").unwrap(); + assert_eq!(a, AlgorithmId::MlDsa44); + assert!(w.is_some(), "dilithium2 alias must carry the warning"); + assert!(AlgorithmId::parse("dsa").is_err()); + assert!(AlgorithmId::parse("rsa-8192").is_err()); + } + + #[test] + fn legacy_gate() { + assert!(check_ca_policy(&[AlgorithmId::Ed25519], false).is_ok()); + assert!(check_ca_policy(&[AlgorithmId::Rsa2048], false).is_err()); + assert!(check_ca_policy(&[AlgorithmId::Rsa2048], true).is_ok()); + } + + #[test] + fn list_parsing_preserves_duplicates() { + let (list, _) = parse_algorithm_list("rsa,rsa,ed25519").unwrap(); + assert_eq!( + list, + [AlgorithmId::Rsa4096, AlgorithmId::Rsa4096, AlgorithmId::Ed25519] + ); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/bundle.rs b/pkgs/fleet/crates/fleet-cert/src/bundle.rs new file mode 100644 index 0000000000..2070fd0b70 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/bundle.rs @@ -0,0 +1,320 @@ +//! Bundle directories: the on-disk form of root sets, issuer sets +//! and leaf deliveries (spec §7). +//! +//! A bundle is a directory with a canonical `manifest.json` +//! (§7.1) plus the artifacts it indexes. The manifest's file index +//! carries a SHA-256 per file; loading a bundle verifies every +//! indexed file, so a tampered or truncated bundle fails loudly +//! instead of issuing from corrupt state. Private key files are +//! written `0600` under a `0700` directory and are never included +//! in any public artifact. + +use crate::error::{CertError, Result}; +use crate::model::{BundleManifest, BundleType, FileRecord, MANIFEST_SCHEMA}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +/// SHA-256 of `bytes`, lowercase hex. +pub fn sha256_hex(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Encode DER bytes as a PEM block with 64-column lines. +pub fn pem_encode(label: &str, der: &[u8]) -> String { + let b64 = base64_encode(der); + let mut out = format!("-----BEGIN {label}-----\n"); + for chunk in b64.as_bytes().chunks(64) { + out.push_str(std::str::from_utf8(chunk).unwrap_or("")); + out.push('\n'); + } + out.push_str(&format!("-----END {label}-----\n")); + out +} + +/// Decode every PEM block in `text` into (label, DER) pairs. +/// Non-PEM text between blocks is ignored. +pub fn pem_decode_all(text: &str) -> Result)>> { + let mut out = Vec::new(); + let mut rest = text; + while let Some(begin) = rest.find("-----BEGIN ") { + let after = &rest[begin + 11..]; + let label_end = after + .find("-----") + .ok_or_else(|| CertError::manifest("malformed PEM: unterminated BEGIN line"))?; + let label = after[..label_end].trim().to_string(); + let body_start = begin + 11 + label_end + 5; + let end_marker = format!("-----END {label}-----"); + let body_end = rest[body_start..] + .find(&end_marker) + .ok_or_else(|| CertError::manifest(format!("malformed PEM: no END for {label}")))? + + body_start; + let der = base64_decode(&rest[body_start..body_end])?; + out.push((label, der)); + rest = &rest[body_end + end_marker.len()..]; + } + Ok(out) +} + +const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +pub fn base64_encode(data: &[u8]) -> String { + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [ + chunk[0] as u32, + *chunk.get(1).unwrap_or(&0) as u32, + *chunk.get(2).unwrap_or(&0) as u32, + ]; + let n = (b[0] << 16) | (b[1] << 8) | b[2]; + out.push(B64[(n >> 18) as usize & 63] as char); + out.push(B64[(n >> 12) as usize & 63] as char); + out.push(if chunk.len() > 1 { + B64[(n >> 6) as usize & 63] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + B64[n as usize & 63] as char + } else { + '=' + }); + } + out +} + +pub fn base64_decode(text: &str) -> Result> { + let mut vals = Vec::new(); + for c in text.chars() { + match c { + 'A'..='Z' => vals.push(c as u32 - 'A' as u32), + 'a'..='z' => vals.push(c as u32 - 'a' as u32 + 26), + '0'..='9' => vals.push(c as u32 - '0' as u32 + 52), + '+' => vals.push(62), + '/' => vals.push(63), + '=' => break, + c if c.is_whitespace() => {} + other => { + return Err(CertError::manifest(format!( + "invalid base64 character '{other}'" + ))) + } + } + } + let mut out = Vec::with_capacity(vals.len() * 3 / 4); + for chunk in vals.chunks(4) { + if chunk.len() < 2 { + break; + } + let n = (chunk[0] << 18) + | (chunk[1] << 12) + | (*chunk.get(2).unwrap_or(&0) << 6) + | *chunk.get(3).unwrap_or(&0); + out.push((n >> 16) as u8); + if chunk.len() > 2 { + out.push((n >> 8) as u8); + } + if chunk.len() > 3 { + out.push(n as u8); + } + } + Ok(out) +} + +/// One artifact to write into a bundle. +#[derive(Debug, Clone)] +pub struct Artifact { + /// Bundle-relative path (`public/...` or `private/...`). + pub rel_path: String, + /// File-index kind: `certificate-pem`, `private-key-pkcs8`, + /// `trust-bundle-pem`, `chain-pem`. + pub kind: String, + /// `public` | `private`. + pub visibility: String, + pub bytes: Vec, +} + +/// Write a complete bundle: artifacts first (so their checksums can +/// be indexed), then the manifest. The target directory must not +/// already contain a manifest — overwriting a CA bundle is a +/// ceremony, not a default. +pub fn write_bundle( + dir: &Path, + mut manifest: BundleManifest, + artifacts: &[Artifact], +) -> Result { + if dir.join("manifest.json").exists() { + return Err(CertError::policy(format!( + "bundle already exists at {} (manifest.json present); refusing to overwrite a CA bundle", + dir.display() + ))); + } + std::fs::create_dir_all(dir)?; + let mut records = Vec::new(); + for art in artifacts { + if art.rel_path.contains("..") { + return Err(CertError::usage(format!( + "artifact path '{}' escapes the bundle", + art.rel_path + ))); + } + let path = dir.join(&art.rel_path); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + if art.visibility == "private" { + set_dir_private(parent); + } + } + std::fs::write(&path, &art.bytes)?; + if art.visibility == "private" { + set_file_private(&path); + } + records.push(FileRecord { + path: art.rel_path.clone(), + kind: art.kind.clone(), + sha256: sha256_hex(&art.bytes), + bytes: art.bytes.len() as u64, + visibility: art.visibility.clone(), + }); + } + records.sort_by(|a, b| a.path.cmp(&b.path)); + manifest.files = records; + let manifest_json = serde_json::to_string_pretty(&manifest)?; + std::fs::write(dir.join("manifest.json"), manifest_json + "\n")?; + Ok(manifest) +} + +#[cfg(unix)] +fn set_file_private(path: &Path) { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); +} + +#[cfg(not(unix))] +fn set_file_private(_path: &Path) {} + +#[cfg(unix)] +fn set_dir_private(path: &Path) { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); +} + +#[cfg(not(unix))] +fn set_dir_private(_path: &Path) {} + +/// A loaded, checksum-verified bundle. +#[derive(Debug)] +pub struct Bundle { + pub dir: PathBuf, + pub manifest: BundleManifest, +} + +/// Load a bundle and verify it: schema, file presence, and every +/// indexed file's SHA-256 (§7.1 read mode: strict verification). +pub fn load_bundle(dir: &Path) -> Result { + let manifest_path = dir.join("manifest.json"); + let text = std::fs::read_to_string(&manifest_path).map_err(|e| { + CertError::manifest(format!( + "no readable manifest.json in {}: {e}", + dir.display() + )) + })?; + let manifest: BundleManifest = serde_json::from_str(&text)?; + if manifest.schema != MANIFEST_SCHEMA { + return Err(CertError::manifest(format!( + "unsupported manifest schema '{}' (this build reads {MANIFEST_SCHEMA})", + manifest.schema + ))); + } + let mut failures = Vec::new(); + for file in &manifest.files { + let path = dir.join(&file.path); + match std::fs::read(&path) { + Ok(bytes) => { + if sha256_hex(&bytes) != file.sha256 { + failures.push(format!("{}: checksum mismatch", file.path)); + } else if bytes.len() as u64 != file.bytes { + failures.push(format!("{}: size mismatch", file.path)); + } + } + Err(e) => failures.push(format!("{}: unreadable ({e})", file.path)), + } + } + if !failures.is_empty() { + return Err(CertError::manifest(format!( + "bundle at {} fails verification: {}", + dir.display(), + failures.join("; ") + ))); + } + Ok(Bundle { + dir: dir.to_path_buf(), + manifest, + }) +} + +/// Read a bundle's manifest without checksum verification (for +/// listing damaged bundles honestly). Returns `None` when the +/// directory is not a bundle. +pub fn read_manifest_unverified(dir: &Path) -> Option { + let text = std::fs::read_to_string(dir.join("manifest.json")).ok()?; + serde_json::from_str(&text).ok() +} + +/// List bundles under a parent directory: the parent itself when it +/// is a bundle, plus each immediate subdirectory that is one. +/// Optionally filtered by bundle type. +pub fn list_bundles(parent: &Path, want: Option) -> Vec<(PathBuf, BundleManifest)> { + let mut out = Vec::new(); + let consider = |dir: &Path, out: &mut Vec<(PathBuf, BundleManifest)>| { + if let Some(m) = read_manifest_unverified(dir) { + if want.is_none() || want == Some(m.bundle_type) { + out.push((dir.to_path_buf(), m)); + } + } + }; + consider(parent, &mut out); + if let Ok(entries) = std::fs::read_dir(parent) { + let mut dirs: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_dir()) + .collect(); + dirs.sort(); + for d in dirs { + consider(&d, &mut out); + } + } + out +} + +/// Read one indexed artifact's bytes from a loaded bundle. +pub fn read_artifact(bundle: &Bundle, rel_path: &str) -> Result> { + Ok(std::fs::read(bundle.dir.join(rel_path))?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pem_round_trip() { + let der = vec![0x30, 0x82, 0x01, 0x00, 0xff, 0x10, 0x42]; + let pem = pem_encode("CERTIFICATE", &der); + let blocks = pem_decode_all(&pem).unwrap(); + assert_eq!(blocks, vec![("CERTIFICATE".to_string(), der)]); + // Multi-block and noise tolerance. + let two = format!("noise\n{pem}{pem}"); + assert_eq!(pem_decode_all(&two).unwrap().len(), 2); + } + + #[test] + fn base64_vectors() { + assert_eq!(base64_encode(b"Man"), "TWFu"); + assert_eq!(base64_encode(b"Ma"), "TWE="); + assert_eq!(base64_encode(b"M"), "TQ=="); + assert_eq!(base64_decode("TWFu").unwrap(), b"Man"); + assert_eq!(base64_decode("TW\nE=").unwrap(), b"Ma"); + assert!(base64_decode("T!Fu").is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/chain.rs b/pkgs/fleet/crates/fleet-cert/src/chain.rs new file mode 100644 index 0000000000..5d1d8c950c --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/chain.rs @@ -0,0 +1,475 @@ +//! Certificate parsing, signature verification, chain building and +//! validation — the verifier half of the engine. +//! +//! Parsing is x509-parser; signature verification is aws-lc-rs (the +//! same backend that signs), covering every registered algorithm +//! including ML-DSA-44. Path building matches issuer→subject by raw +//! DER name plus AKI→SKI, then *proves* each link cryptographically +//! — a name match alone never validates. +//! +//! Trust selection is a verifier policy (§3.2/§3.5): `classical` +//! trusts only classical roots, `pq` trusts only the ML-DSA root +//! **and** requires every key and signature in the path to be +//! ML-DSA-44. Providing a classical cross-certificate cannot smuggle +//! a classical path past a PQ selection — the separation is enforced +//! here, not by issuance. + +use crate::algorithm::AlgorithmId; +use crate::bundle::sha256_hex; +use crate::error::{CertError, Result}; +use crate::timeparse::Rfc3339; +use serde::Serialize; +use x509_parser::extensions::ParsedExtension; +use x509_parser::prelude::*; + +/// A parsed certificate with everything validation needs. +#[derive(Debug, Clone)] +pub struct CertInfo { + pub der: Vec, + pub fingerprint_sha256: String, + pub subject_dn: String, + pub issuer_dn: String, + /// Raw DER of the subject / issuer Name (exact-match key for + /// path building — string DNs are display only). + pub subject_name_der: Vec, + pub issuer_name_der: Vec, + pub serial_hex: String, + pub ski: Option>, + pub aki: Option>, + pub not_before: Rfc3339, + pub not_after: Rfc3339, + pub is_ca: bool, + pub path_len: Option, + /// Subject key algorithm, when it is a registered one. + pub subject_algorithm: Option, + /// Signature algorithm OID (dotted). + pub signature_oid: String, + /// Subject signature-algorithm classification: true when the + /// signature over this certificate is ML-DSA-44. + pub signature_is_pq: bool, + tbs: Vec, + signature: Vec, + spki_bytes: Vec, + spki_oid: String, +} + +pub fn hex_bytes(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Extract the raw TBS bytes from a certificate DER blob: the first +/// element inside the outer SEQUENCE. +fn tbs_bytes(der: &[u8]) -> Result> { + fn read_len(der: &[u8], mut i: usize) -> Result<(usize, usize)> { + if i >= der.len() { + return Err(CertError::manifest("truncated DER")); + } + let first = der[i]; + i += 1; + if first < 0x80 { + return Ok((first as usize, i)); + } + let n = (first & 0x7f) as usize; + if n == 0 || n > 4 || i + n > der.len() { + return Err(CertError::manifest("bad DER length")); + } + let mut len = 0usize; + for k in 0..n { + len = (len << 8) | der[i + k] as usize; + } + Ok((len, i + n)) + } + if der.is_empty() || der[0] != 0x30 { + return Err(CertError::manifest("certificate DER does not start with a SEQUENCE")); + } + let (_, content_start) = read_len(der, 1)?; + if content_start >= der.len() || der[content_start] != 0x30 { + return Err(CertError::manifest("certificate TBS is not a SEQUENCE")); + } + let (tbs_len, tbs_content) = read_len(der, content_start + 1)?; + let tbs_end = tbs_content + tbs_len; + if tbs_end > der.len() { + return Err(CertError::manifest("truncated TBS")); + } + Ok(der[content_start..tbs_end].to_vec()) +} + +/// Classify a subject key from its SPKI OID (+ size for RSA). +fn classify_subject(spki_oid: &str, spki_bytes: &[u8]) -> Option { + match spki_oid { + "1.3.101.112" => Some(AlgorithmId::Ed25519), + "1.2.840.10045.2.1" => Some(AlgorithmId::P256), + "2.16.840.1.101.3.4.3.17" => Some(AlgorithmId::MlDsa44), + "1.2.840.113549.1.1.1" => { + // RSAPublicKey inside the BIT STRING: ~270 bytes total + // for 2048-bit, ~526 for 4096-bit moduli. + if spki_bytes.len() > 400 { + Some(AlgorithmId::Rsa4096) + } else { + Some(AlgorithmId::Rsa2048) + } + } + _ => None, + } +} + +/// Parse one certificate from DER. +pub fn parse_cert(der: &[u8]) -> Result { + let (_, cert) = parse_x509_certificate(der) + .map_err(|e| CertError::manifest(format!("certificate parse failed: {e}")))?; + let tbs = &cert.tbs_certificate; + let (bc_is_ca, bc_path_len) = match tbs.basic_constraints() { + Ok(Some(bc)) => ( + bc.value.ca, + bc.value.path_len_constraint.map(|n| n as u8), + ), + _ => (false, None), + }; + // Extension lookup by OID string (2.5.29.14 SKI, 2.5.29.35 AKI). + let ext_by_oid = |oid: &str| { + tbs.extensions() + .iter() + .find(|e| e.oid.to_id_string() == oid) + }; + let ski = match ext_by_oid("2.5.29.14") { + Some(ext) => match ext.parsed_extension() { + ParsedExtension::SubjectKeyIdentifier(ki) => Some(ki.0.to_vec()), + _ => None, + }, + None => None, + }; + let aki = match ext_by_oid("2.5.29.35") { + Some(ext) => match ext.parsed_extension() { + ParsedExtension::AuthorityKeyIdentifier(aki) => { + aki.key_identifier.as_ref().map(|ki| ki.0.to_vec()) + } + _ => None, + }, + None => None, + }; + let spki_oid = tbs.subject_pki.algorithm.algorithm.to_id_string(); + let spki_bytes = tbs.subject_pki.subject_public_key.data.to_vec(); + let signature_oid = cert.signature_algorithm.algorithm.to_id_string(); + Ok(CertInfo { + der: der.to_vec(), + fingerprint_sha256: sha256_hex(der), + subject_dn: tbs.subject.to_string(), + issuer_dn: tbs.issuer.to_string(), + subject_name_der: tbs.subject.as_raw().to_vec(), + issuer_name_der: tbs.issuer.as_raw().to_vec(), + serial_hex: hex_bytes(&tbs.serial.to_bytes_be()), + ski, + aki, + not_before: Rfc3339(tbs.validity.not_before.to_datetime()), + not_after: Rfc3339(tbs.validity.not_after.to_datetime()), + is_ca: bc_is_ca, + path_len: bc_path_len, + subject_algorithm: classify_subject(&spki_oid, &spki_bytes), + signature_is_pq: signature_oid == "2.16.840.1.101.3.4.3.17", + signature_oid, + tbs: tbs_bytes(der)?, + signature: cert.signature_value.data.to_vec(), + spki_bytes, + spki_oid, + }) +} + +/// Verify `subject`'s signature using `issuer`'s public key. +/// Returns false for any mismatch or unsupported pairing — never +/// panics on untrusted input. +pub fn verify_signature(issuer: &CertInfo, subject: &CertInfo) -> bool { + use aws_lc_rs::signature::{ + UnparsedPublicKey, ECDSA_P256_SHA256_ASN1, ED25519, ML_DSA_44, RSA_PKCS1_2048_8192_SHA256, + }; + let key = &issuer.spki_bytes; + let ok = match subject.signature_oid.as_str() { + "1.3.101.112" => UnparsedPublicKey::new(&ED25519, key) + .verify(&subject.tbs, &subject.signature) + .is_ok(), + "1.2.840.10045.4.3.2" => UnparsedPublicKey::new(&ECDSA_P256_SHA256_ASN1, key) + .verify(&subject.tbs, &subject.signature) + .is_ok(), + "1.2.840.113549.1.1.11" => { + UnparsedPublicKey::new(&RSA_PKCS1_2048_8192_SHA256, key) + .verify(&subject.tbs, &subject.signature) + .is_ok() + } + "2.16.840.1.101.3.4.3.17" => UnparsedPublicKey::new(&ML_DSA_44, key) + .verify(&subject.tbs, &subject.signature) + .is_ok(), + _ => false, + }; + ok +} + +/// Which roots a validation trusts (§3.5 trust bundles). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum TrustSelection { + /// Every self-signed root in the set (`roots-all`). + All, + /// Classical roots only (`roots-classical`). + Classical, + /// The ML-DSA root only, with an all-ML-DSA path requirement + /// (`roots-pq`, §3.2 verifier policy). + Pq, +} + +impl TrustSelection { + pub fn parse(input: &str) -> Result { + match input.trim().to_ascii_lowercase().as_str() { + "all" | "roots-all" => Ok(TrustSelection::All), + "classical" | "roots-classical" => Ok(TrustSelection::Classical), + "pq" | "roots-pq" => Ok(TrustSelection::Pq), + other => Err(CertError::usage(format!( + "unknown trust selection '{other}' (all | classical | pq)" + ))), + } + } + pub fn as_str(&self) -> &'static str { + match self { + TrustSelection::All => "all", + TrustSelection::Classical => "classical", + TrustSelection::Pq => "pq", + } + } + fn root_admitted(&self, root: &CertInfo) -> bool { + match self { + TrustSelection::All => true, + TrustSelection::Classical => { + root.subject_algorithm.map(|a| a.is_classical()).unwrap_or(false) + } + TrustSelection::Pq => root.subject_algorithm == Some(AlgorithmId::MlDsa44), + } + } +} + +/// One named check in a validation report. +#[derive(Debug, Clone, Serialize)] +pub struct Check { + pub name: String, + pub ok: bool, + pub detail: String, +} + +/// The outcome of a chain validation. +#[derive(Debug, Clone, Serialize)] +pub struct ChainReport { + pub valid: bool, + pub trust_selection: String, + /// The built path, leaf first, anchor last (subject DNs). + pub path: Vec, + pub path_fingerprints: Vec, + pub checks: Vec, +} + +fn is_self_signed(cert: &CertInfo) -> bool { + cert.subject_name_der == cert.issuer_name_der && verify_signature(cert, cert) +} + +/// Build a path from `leaf` through `pool` (intermediates and roots, +/// any order) to a self-signed anchor admitted by `trust`. Every +/// link is signature-verified. +/// +/// The search is iterative-deepening: the *shortest* valid path +/// wins. That matters for cross-signing — a directly cross-signed +/// issuer variant (§24.2) yields a shorter path than routing the +/// same key through a root-level cross-certificate (§3.2), and the +/// longer route can be genuinely invalid: a cross-certificate is a +/// CA certificate in the path, so an anchor with pathLenConstraint +/// 1 cannot top a leaf → issuer → cross → root path (2 CA below). +/// Path-length feasibility is therefore pruned during the search +/// (anchor constraints enforced, RFC 5280 §6.1 reading), not +/// discovered after it. +pub fn build_path( + leaf: &CertInfo, + pool: &[CertInfo], + trust: TrustSelection, +) -> Option> { + for limit in 1..=6 { + if let Some(path) = dfs(leaf, pool, trust, 0, limit, 0) { + return Some(path); + } + } + None +} + +fn dfs( + current: &CertInfo, + pool: &[CertInfo], + trust: TrustSelection, + depth: usize, + limit: usize, + ca_below_current: usize, +) -> Option> { + // Anchor case: current is itself a trusted self-signed root. + if is_self_signed(current) && trust.root_admitted(current) { + return Some(vec![current.clone()]); + } + if depth >= limit { + return None; + } + // Candidate issuers: name match, AKI→SKI when both present, + // a signature that actually verifies, CA flag set, and a + // path-length budget that fits the CAs already below it. + let mut candidates: Vec<&CertInfo> = pool + .iter() + .filter(|cand| cand.subject_name_der == current.issuer_name_der) + .filter(|cand| { + match (¤t.aki, &cand.ski) { + (Some(aki), Some(ski)) => aki == ski, + _ => true, + } + }) + .filter(|cand| cand.is_ca || is_self_signed(cand)) + .filter(|cand| verify_signature(cand, current)) + .filter(|cand| { + let ca_below_cand = ca_below_current + usize::from(depth > 0); + match cand.path_len { + Some(pl) => ca_below_cand <= pl as usize, + None => true, + } + }) + .collect(); + // Prefer anchors, then primaries-by-name stability. + candidates.sort_by_key(|c| (!is_self_signed(c), c.fingerprint_sha256.clone())); + for cand in candidates { + let ca_below_cand = ca_below_current + usize::from(depth > 0); + if let Some(mut tail) = dfs(cand, pool, trust, depth + 1, limit, ca_below_cand) { + let mut path = vec![current.clone()]; + path.append(&mut tail); + return Some(path); + } + } + None +} + +/// Validate a leaf against a pool and a trust selection at time +/// `at`, producing a per-check report. Checks: path exists, +/// signatures (inherent to path building), per-certificate validity +/// window, CA flags + path length on every CA in the path, and the +/// trust selection's own rule (for `pq`: every key and signature in +/// the path is ML-DSA-44). +pub fn validate_chain( + leaf: &CertInfo, + pool: &[CertInfo], + trust: TrustSelection, + at: Rfc3339, +) -> ChainReport { + let mut checks = Vec::new(); + let path = build_path(leaf, pool, trust); + match &path { + Some(p) => checks.push(Check { + name: "path-builds".into(), + ok: true, + detail: format!("{} certificates to the anchor", p.len()), + }), + None => checks.push(Check { + name: "path-builds".into(), + ok: false, + detail: format!( + "no verified path from {} to a {} trust anchor", + leaf.subject_dn, + trust.as_str() + ), + }), + } + let mut valid = path.is_some(); + if let Some(p) = &path { + // Validity windows. + for cert in p { + let ok = cert.not_before <= at && at <= cert.not_after; + if !ok { + valid = false; + } + checks.push(Check { + name: format!("validity:{}", cert.subject_dn), + ok, + detail: format!("{} .. {}", cert.not_before, cert.not_after), + }); + } + // CA flags + path length: every non-leaf in the path must be + // a CA, and the number of CA certificates below it must fit + // its pathLenConstraint. + for (i, cert) in p.iter().enumerate().skip(1) { + let ok_ca = cert.is_ca; + if !ok_ca { + valid = false; + } + checks.push(Check { + name: format!("ca-flag:{}", cert.subject_dn), + ok: ok_ca, + detail: if ok_ca { "CA:true".into() } else { "not a CA".into() }, + }); + if let Some(pl) = cert.path_len { + let below = (i - 1) as u8; // CA certs strictly below this one + let ok = below <= pl; + if !ok { + valid = false; + } + checks.push(Check { + name: format!("pathlen:{}", cert.subject_dn), + ok, + detail: format!("{below} CA below, constraint {pl}"), + }); + } + } + // Signature spot-check is inherent to build_path; record it. + checks.push(Check { + name: "signatures-verify".into(), + ok: true, + detail: "every link verified with the issuer's public key".into(), + }); + // Trust-selection rule. + match trust { + TrustSelection::Pq => { + let all_pq = p.iter().all(|c| { + c.subject_algorithm == Some(AlgorithmId::MlDsa44) && c.signature_is_pq + }); + // The anchor's own signature is self-referential; it + // is ML-DSA by the subject check. Non-anchor links + // must carry ML-DSA signatures. + if !all_pq { + valid = false; + } + checks.push(Check { + name: "pq-only-path".into(), + ok: all_pq, + detail: if all_pq { + "every key and signature in the path is ML-DSA-44".into() + } else { + "a classical key or signature appears in the path".into() + }, + }); + } + TrustSelection::Classical => { + let anchor = p.last(); + let ok = anchor + .map(|a| a.subject_algorithm.map(|x| x.is_classical()).unwrap_or(false)) + .unwrap_or(false); + if !ok { + valid = false; + } + checks.push(Check { + name: "classical-anchor".into(), + ok, + detail: "anchor is a classical root".into(), + }); + } + TrustSelection::All => {} + } + } + ChainReport { + valid, + trust_selection: trust.as_str().to_string(), + path: path + .as_ref() + .map(|p| p.iter().map(|c| c.subject_dn.clone()).collect()) + .unwrap_or_default(), + path_fingerprints: path + .as_ref() + .map(|p| p.iter().map(|c| c.fingerprint_sha256.clone()).collect()) + .unwrap_or_default(), + checks, + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/cli.rs b/pkgs/fleet/crates/fleet-cert/src/cli.rs new file mode 100644 index 0000000000..5ce75b320e --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/cli.rs @@ -0,0 +1,981 @@ +//! The `fleet cert` CLI: a thin shell over the crate API (spec +//! §6.4). Each verb parses flags into a typed request in +//! [`crate::model`], calls [`crate::engine`], and renders text or, +//! with `--json`, one JSON value on stdout. +//! +//! Exit codes follow the fleet contract: 0 ok · 2 usage · 1 +//! operational/policy/validation failure. + +use crate::algorithm::{self, AlgorithmId}; +use crate::bundle::{list_bundles, load_bundle}; +use crate::chain::TrustSelection; +use crate::engine; +use crate::error::{CertError, Result}; +use crate::graph::CrossSigningMode; +use crate::model::{ + BundleType, IssuerCreateRequest, IssuerPurpose, LeafIssueRequest, RootCreateRequest, + SignerSource, +}; +use crate::profile; +use crate::timeparse::{CalendarDuration, Rfc3339}; +use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +/// Full usage for the cert domain (also what `fleet cert --help` +/// prints through the bin crate's help carve-out). +pub const CERT_USAGE: &str = "\ +Usage: fleet cert [options] + fleet pki [options] (alias) + +Groups and verbs (spec §6.1 tree; status as built): + root create | inspect | list | validate + issuer create | inspect | list + leaf issue | inspect | list + chain build | test + bundle inspect + profile list | show + algorithms list | describe + explain [topic] + doctor + +Common options: + --json Emit one JSON value instead of text. + --not-before Validity start (default: now). + --not-after Exact validity end (mutually exclusive with --valid-for). + --valid-for Lifetime from not-before: 20y, 90d, '15 years 7 days'. + +Signing operations never discover keys ambiently: issuer/leaf +creation requires the signer's key directory as an explicit +argument (spec §24.3). Run `fleet cert explain signer-source` +for the rule, `fleet cert doctor` for what is built vs not. +"; + +pub fn run(args: &[String]) -> i32 { + match run_inner(args) { + Ok(code) => code, + Err(e) => { + eprintln!("fleet cert: {e}"); + e.exit_code() + } + } +} + +// ---------------------------------------------------------------- parsing + +/// A minimal flag parser in the fleet-agent style: `--flag value`, +/// `--flag=value`, boolean switches, repeatable value flags. +struct Parsed { + positionals: Vec, + values: BTreeMap>, + bools: BTreeSet, +} + +impl Parsed { + fn get(&self, name: &str) -> Option<&str> { + self.values.get(name).and_then(|v| v.last()).map(|s| s.as_str()) + } + fn all(&self, name: &str) -> Vec { + self.values.get(name).cloned().unwrap_or_default() + } + fn has(&self, name: &str) -> bool { + self.bools.contains(name) || self.values.contains_key(name) + } + fn require(&self, name: &str, what: &str) -> Result { + self.get(name) + .map(|s| s.to_string()) + .ok_or_else(|| CertError::usage(format!("{what} requires --{name} "))) + } + fn positional(&self, idx: usize) -> Option<&str> { + self.positionals.get(idx).map(|s| s.as_str()) + } +} + +fn parse_args( + args: &[String], + value_flags: &[&str], + bool_flags: &[&str], +) -> Result { + let mut parsed = Parsed { + positionals: Vec::new(), + values: BTreeMap::new(), + bools: BTreeSet::new(), + }; + let mut i = 0; + while i < args.len() { + let arg = &args[i]; + if let Some(flag) = arg.strip_prefix("--") { + let (name, inline) = match flag.split_once('=') { + Some((n, v)) => (n, Some(v.to_string())), + None => (flag, None), + }; + if bool_flags.contains(&name) { + if inline.is_some() { + return Err(CertError::usage(format!("--{name} takes no value"))); + } + parsed.bools.insert(name.to_string()); + } else if value_flags.contains(&name) { + let value = match inline { + Some(v) => v, + None => { + i += 1; + args.get(i).cloned().ok_or_else(|| { + CertError::usage(format!("--{name} needs a value")) + })? + } + }; + parsed.values.entry(name.to_string()).or_default().push(value); + } else { + return Err(CertError::usage(format!( + "unknown option --{name} (run 'fleet cert --help')" + ))); + } + } else if arg.starts_with('-') && arg.len() > 1 && arg != "-" { + return Err(CertError::usage(format!( + "unknown option {arg} (options are long-form --flag)" + ))); + } else { + parsed.positionals.push(arg.clone()); + } + i += 1; + } + Ok(parsed) +} + +fn json_mode(args: &[String]) -> bool { + args.iter().any(|a| a == "--json") +} + +fn emit(json_out: bool, text: String, value: Value) -> i32 { + if json_out { + println!( + "{}", + serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string()) + ); + } else { + print!("{text}"); + } + 0 +} + +/// The shared validity flags (§5.4/§6.3). +fn validity( + p: &Parsed, + default_lifetime: CalendarDuration, +) -> Result<(Rfc3339, Rfc3339)> { + let nb = p + .get("not-before") + .map(Rfc3339::parse) + .transpose()?; + let vf = p + .get("valid-for") + .map(CalendarDuration::parse) + .transpose()?; + let na = p.get("not-after").map(Rfc3339::parse).transpose()?; + crate::timeparse::resolve_validity(nb, vf, na, default_lifetime) +} + +const TIME_FLAGS: &[&str] = &["not-before", "not-after", "valid-for"]; + +fn signer_source(p: &Parsed, flag: &str, what: &str) -> Result { + match p.get(flag) { + Some(dir) => Ok(SignerSource { + key_dir: PathBuf::from(dir), + }), + None => Err(CertError::policy(format!( + "{what} requires an explicit signer source: --{flag} \ + (spec §24.3 — root/issuer signing never uses ambient key discovery)" + ))), + } +} + +fn algorithms_arg(p: &Parsed) -> Result> { + match p.get("algorithms") { + Some(csv) => { + let (algos, warnings) = algorithm::parse_algorithm_list(csv)?; + for w in warnings { + eprintln!("warning: {w}"); + } + Ok(algos) + } + None => Ok(algorithm::DEFAULT_ALGORITHMS.to_vec()), + } +} + +fn cross_arg(p: &Parsed, default: CrossSigningMode) -> Result { + match p.get("cross-signing") { + Some(s) => CrossSigningMode::parse(s), + None => Ok(default), + } +} + +// ---------------------------------------------------------------- dispatch + +fn run_inner(args: &[String]) -> Result { + if args.is_empty() { + print!("{CERT_USAGE}"); + return Ok(2); + } + if args.len() == 1 && (args[0] == "--help" || args[0] == "-h" || args[0] == "help") { + print!("{CERT_USAGE}"); + return Ok(0); + } + let json_out = json_mode(args); + let rest = &args[1..]; + match args[0].as_str() { + "root" => root_cmd(rest, json_out), + "issuer" => issuer_cmd(rest, json_out), + "leaf" => leaf_cmd(rest, json_out), + "chain" => chain_cmd(rest, json_out), + "bundle" => bundle_cmd(rest, json_out), + "profile" => profile_cmd(rest, json_out), + "algorithms" => algorithms_cmd(rest, json_out), + "explain" => explain_cmd(rest, json_out), + "doctor" => doctor_cmd(rest, json_out), + other => Err(CertError::usage(format!( + "unknown cert group '{other}' — run 'fleet cert --help' for the surface" + ))), + } +} + +// ---------------------------------------------------------------- root + +fn root_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "create" => { + let mut flags = vec![ + "out", + "organization", + "country", + "algorithms", + "generation", + "partition", + "cross-signing", + "private-store", + ]; + flags.extend(TIME_FLAGS); + let p = parse_args( + rest, + &flags, + &["allow-legacy-root-strength", "private-in-bundle", "json"], + )?; + // §24.3 ceremony: the key destination must be explicit. + let private_store = match (p.get("private-store"), p.has("private-in-bundle")) { + (Some(dir), _) => Some(PathBuf::from(dir)), + (None, true) => None, + (None, false) => { + return Err(CertError::policy( + "root creation is a ceremony: name the root key destination \ + explicitly — --private-store or --private-in-bundle \ + (spec §24.3)", + )) + } + }; + let generation: u32 = p + .get("generation") + .map(|s| { + s.parse() + .map_err(|_| CertError::usage(format!("bad --generation '{s}'"))) + }) + .transpose()? + .unwrap_or(1); + let (nb, na) = validity(&p, CalendarDuration::years(crate::timeparse::ROOT_DEFAULT_LIFETIME_YEARS))?; + let req = RootCreateRequest { + organization: p + .get("organization") + .unwrap_or("developing.today LLC") + .to_string(), + country: p.get("country").unwrap_or("US").to_string(), + algorithms: algorithms_arg(&p)?, + generation, + partition: p.get("partition").unwrap_or("A").to_string(), + cross_signing: cross_arg(&p, CrossSigningMode::Both)?, + not_before: nb, + not_after: na, + allow_legacy_root_strength: p.has("allow-legacy-root-strength"), + private_store, + }; + let out = p.require("out", "root create")?; + let manifest = engine::create_root_set(&req, &PathBuf::from(&out))?; + Ok(emit( + json_out, + manifest_text("Root set created", &manifest, &out), + manifest_json(&manifest, &out), + )) + } + "inspect" => inspect_cmd(rest, json_out, Some(BundleType::RootSet)), + "list" => list_cmd(rest, json_out, BundleType::RootSet), + "validate" => { + let p = parse_args(rest, &["bundle"], &["json"])?; + let dir = p + .get("bundle") + .map(|s| s.to_string()) + .or_else(|| p.positional(0).map(|s| s.to_string())) + .ok_or_else(|| CertError::usage("root validate needs a bundle directory"))?; + let checks = engine::validate_root_bundle(&PathBuf::from(&dir))?; + let all_ok = checks.iter().all(|c| c.ok); + let mut text = format!("Root bundle validation: {dir}\n"); + for c in &checks { + text.push_str(&format!( + " [{}] {} — {}\n", + if c.ok { "ok" } else { "FAIL" }, + c.name, + c.detail + )); + } + let value = json!({ + "bundle": dir, + "valid": all_ok, + "checks": checks.iter().map(|c| json!({"name": c.name, "ok": c.ok, "detail": c.detail})).collect::>(), + }); + let code = emit(json_out, text, value); + Ok(if all_ok { code } else { 1 }) + } + other => Err(CertError::usage(format!( + "unknown root verb '{other}' (create | inspect | list | validate)" + ))), + } +} + +// ---------------------------------------------------------------- issuer + +fn issuer_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "create" => { + let mut flags = vec![ + "root", + "root-key-dir", + "out", + "name", + "purpose", + "ou", + "algorithms", + "partitions", + "cross-signing", + "permitted-dns", + "private-store", + ]; + flags.extend(TIME_FLAGS); + let p = parse_args(rest, &flags, &["allow-legacy-root-strength", "json"])?; + let root = p.require("root", "issuer create")?; + let signer = signer_source(&p, "root-key-dir", "issuer create")?; + let algos = algorithms_arg(&p)?; + let partitions: Option> = p.get("partitions").map(|s| { + s.split(',') + .map(|x| x.trim().to_ascii_lowercase()) + .filter(|x| !x.is_empty()) + .collect() + }); + let slots = crate::model::resolve_slots(&algos, partitions.as_deref())?; + let (nb, na) = validity( + &p, + CalendarDuration::years(crate::timeparse::ISSUER_DEFAULT_LIFETIME_YEARS), + )?; + let req = IssuerCreateRequest { + root_bundle: PathBuf::from(&root), + root_signer: signer, + name: p.get("name").unwrap_or("Base").to_string(), + purpose: IssuerPurpose::parse(p.get("purpose").unwrap_or("general"))?, + ou: p.get("ou").map(|s| s.to_string()), + slots, + cross_signing: cross_arg(&p, CrossSigningMode::RootsOnly)?, + not_before: nb, + not_after: na, + allow_legacy_root_strength: p.has("allow-legacy-root-strength"), + permitted_dns: p.all("permitted-dns"), + private_store: p.get("private-store").map(PathBuf::from), + }; + let out = p.require("out", "issuer create")?; + let manifest = engine::create_issuer_set(&req, &PathBuf::from(&out))?; + Ok(emit( + json_out, + manifest_text("Issuer set created", &manifest, &out), + manifest_json(&manifest, &out), + )) + } + "inspect" => inspect_cmd(rest, json_out, Some(BundleType::IssuerSet)), + "list" => list_cmd(rest, json_out, BundleType::IssuerSet), + other => Err(CertError::usage(format!( + "unknown issuer verb '{other}' (create | inspect | list)" + ))), + } +} + +// ---------------------------------------------------------------- leaf + +fn leaf_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "issue" => { + let mut flags = vec![ + "issuer", + "issuer-key-dir", + "out", + "profile", + "name", + "cn", + "dns", + "algorithm", + "issuer-algorithm", + "issuer-partition", + "private-store", + ]; + flags.extend(TIME_FLAGS); + let p = parse_args(rest, &flags, &["json"])?; + let issuer = p.require("issuer", "leaf issue")?; + let signer = signer_source(&p, "issuer-key-dir", "leaf issue")?; + let profile_name = p.require("profile", "leaf issue")?; + let prof = profile::leaf_profile(&profile_name)?; + let name = p + .get("name") + .map(|s| s.to_string()) + .or_else(|| p.positional(0).map(|s| s.to_string())) + .ok_or_else(|| CertError::usage("leaf issue requires --name "))?; + let (nb, na) = validity(&p, prof.default_validity)?; + let parse_algo = |flag: &str| -> Result> { + match p.get(flag) { + Some(s) => { + let (a, w) = AlgorithmId::parse(s)?; + if let Some(w) = w { + eprintln!("warning: {w}"); + } + Ok(Some(a)) + } + None => Ok(None), + } + }; + let req = LeafIssueRequest { + issuer_bundle: PathBuf::from(&issuer), + issuer_signer: signer, + profile: profile_name, + name, + common_name: p.get("cn").map(|s| s.to_string()), + dns_names: p.all("dns"), + key_algorithm: parse_algo("algorithm")?, + issuer_algorithm: parse_algo("issuer-algorithm")?, + issuer_partition: p.get("issuer-partition").map(|s| s.to_string()), + not_before: nb, + not_after: na, + private_store: p.get("private-store").map(PathBuf::from), + }; + let out = p.require("out", "leaf issue")?; + let manifest = engine::issue_leaf(&req, &PathBuf::from(&out))?; + Ok(emit( + json_out, + manifest_text("Leaf issued", &manifest, &out), + manifest_json(&manifest, &out), + )) + } + "inspect" => inspect_cmd(rest, json_out, Some(BundleType::Leaf)), + "list" => list_cmd(rest, json_out, BundleType::Leaf), + other => Err(CertError::usage(format!( + "unknown leaf verb '{other}' (issue | inspect | list)" + ))), + } +} + +// ---------------------------------------------------------------- chain + +fn chain_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "build" | "test" => { + let p = parse_args( + rest, + &["leaf", "issuer", "root", "trust", "out", "at"], + &["include-root", "json"], + )?; + let leaf_dir = p.require("leaf", "chain")?; + let root_dir = p.require("root", "chain")?; + let leaf_bundle = load_bundle(&PathBuf::from(&leaf_dir))?; + let root_bundle = load_bundle(&PathBuf::from(&root_dir))?; + let mut pool_bundles = vec![&root_bundle]; + let mut issuer_bundles = Vec::new(); + for dir in p.all("issuer") { + issuer_bundles.push(load_bundle(&PathBuf::from(dir))?); + } + for b in &issuer_bundles { + pool_bundles.push(b); + } + let trust = TrustSelection::parse(p.get("trust").unwrap_or("all"))?; + let at = p + .get("at") + .map(Rfc3339::parse) + .transpose()? + .unwrap_or_else(Rfc3339::now); + let report = engine::validate_leaf(&leaf_bundle, &pool_bundles, trust, at)?; + if verb == "test" { + let mut text = format!( + "Chain test: {} (trust: {})\n", + leaf_bundle.manifest.name, report.trust_selection + ); + if !report.path.is_empty() { + text.push_str(" path:\n"); + for dn in &report.path { + text.push_str(&format!(" {dn}\n")); + } + } + for c in &report.checks { + text.push_str(&format!( + " [{}] {} — {}\n", + if c.ok { "ok" } else { "FAIL" }, + c.name, + c.detail + )); + } + text.push_str(&format!( + " result: {}\n", + if report.valid { "VALID" } else { "INVALID" } + )); + let value = serde_json::to_value(&report) + .map_err(|e| CertError::engine(e.to_string()))?; + let code = emit(json_out, text, value); + return Ok(if report.valid { code } else { 1 }); + } + // build: emit the chain PEM (leaf + intermediates, + // anchor omitted unless --include-root, §3.5). + if !report.valid { + return Err(CertError::validation(format!( + "no valid chain to build under trust selection {}: {}", + trust.as_str(), + report + .checks + .iter() + .filter(|c| !c.ok) + .map(|c| c.name.clone()) + .collect::>() + .join(", ") + ))); + } + let pool = engine::collect_pool(&pool_bundles)?; + let leaf_record = leaf_bundle + .manifest + .certificates + .iter() + .find(|r| r.role == "leaf") + .ok_or_else(|| CertError::manifest("leaf bundle has no leaf record"))?; + let leaf_pem = crate::bundle::read_artifact(&leaf_bundle, &leaf_record.cert_path)?; + let leaf_blocks = + crate::bundle::pem_decode_all(std::str::from_utf8(&leaf_pem).unwrap_or(""))?; + let leaf_der = leaf_blocks + .into_iter() + .find(|(l, _)| l == "CERTIFICATE") + .map(|(_, d)| d) + .ok_or_else(|| CertError::manifest("no CERTIFICATE block in leaf"))?; + let leaf_info = crate::chain::parse_cert(&leaf_der)?; + debug_assert_eq!(leaf_info.fingerprint_sha256, report.path_fingerprints[0]); + let path = crate::chain::build_path(&leaf_info, &pool, trust) + .ok_or_else(|| CertError::validation("path disappeared during build"))?; + let mut pem = String::new(); + let take = if p.has("include-root") { + path.len() + } else { + path.len().saturating_sub(1).max(1) + }; + for cert in path.iter().take(take) { + pem.push_str(&crate::bundle::pem_encode("CERTIFICATE", &cert.der)); + } + match p.get("out") { + Some(out_path) => { + std::fs::write(out_path, &pem)?; + Ok(emit( + json_out, + format!("Chain written to {out_path} ({} certificates)\n", take), + json!({"out": out_path, "certificates": take, "path": report.path}), + )) + } + None => Ok(emit( + json_out, + pem.clone(), + json!({"chain_pem": pem, "path": report.path}), + )), + } + } + other => Err(CertError::usage(format!( + "unknown chain verb '{other}' (build | test)" + ))), + } +} + +// ---------------------------------------------------------------- bundle/profile inspect+list + +fn manifest_text(verb: &str, m: &crate::model::BundleManifest, dir: &str) -> String { + let mut text = format!( + "{verb}: {} ({}) at {dir}\n bundle_id: {}\n certificates: {}\n", + m.name, + m.bundle_type.as_str(), + m.bundle_id, + m.certificates.len() + ); + for c in &m.certificates { + text.push_str(&format!( + " {:10} {:10} {:40} sha256:{}.. {}\n", + c.role, + c.algorithm.name(), + c.subject_dn, + &c.fingerprint_sha256[..12], + if c.primary { "primary" } else { "" } + )); + } + for w in &m.warnings { + text.push_str(&format!(" warning: {w}\n")); + } + text +} + +fn manifest_json(m: &crate::model::BundleManifest, dir: &str) -> Value { + let mut v = serde_json::to_value(m).unwrap_or_else(|_| json!({})); + if let Some(obj) = v.as_object_mut() { + obj.insert("dir".to_string(), json!(dir)); + } + v +} + +fn inspect_cmd(args: &[String], json_out: bool, want: Option) -> Result { + let p = parse_args(args, &["bundle"], &["json"])?; + let dir = p + .get("bundle") + .map(|s| s.to_string()) + .or_else(|| p.positional(0).map(|s| s.to_string())) + .ok_or_else(|| CertError::usage("inspect needs a bundle directory"))?; + let bundle = load_bundle(&PathBuf::from(&dir))?; + if let Some(w) = want { + if bundle.manifest.bundle_type != w { + return Err(CertError::usage(format!( + "{dir} is a {} bundle, not a {}", + bundle.manifest.bundle_type.as_str(), + w.as_str() + ))); + } + } + let m = &bundle.manifest; + let mut text = manifest_text("Bundle", m, &dir); + text.push_str(&format!( + " organization: {} ({})\n generation: {}\n key location: {}\n files: {} (all checksums verified)\n", + m.organization, + m.country, + m.generation, + m.key_location, + m.files.len() + )); + if let Some(parent) = &m.parent { + text.push_str(&format!( + " parent: {} {} ({})\n", + parent.bundle_type.as_str(), + parent.name, + parent.bundle_id + )); + } + Ok(emit(json_out, text, manifest_json(m, &dir))) +} + +fn bundle_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or(""); + let rest = &args[1.min(args.len())..]; + match verb { + "inspect" => inspect_cmd(rest, json_out, None), + other => Err(CertError::usage(format!( + "unknown bundle verb '{other}' (inspect; pack/unpack/validate/diff are follow-ups under #9157)" + ))), + } +} + +fn list_cmd(args: &[String], json_out: bool, want: BundleType) -> Result { + let p = parse_args(args, &["dir"], &["json"])?; + let dir = p.get("dir").unwrap_or(".").to_string(); + let found = list_bundles(&PathBuf::from(&dir), Some(want)); + let mut text = format!("{} bundles under {dir}:\n", want.as_str()); + if found.is_empty() { + text.push_str(" (none)\n"); + } + for (path, m) in &found { + text.push_str(&format!( + " {} — {} ({}, {} certificates, created {})\n", + path.display(), + m.name, + m.bundle_id, + m.certificates.len(), + m.created_at + )); + } + let value = json!({ + "dir": dir, + "bundle_type": want.as_str(), + "bundles": found.iter().map(|(path, m)| json!({ + "dir": path.display().to_string(), + "bundle_id": m.bundle_id, + "name": m.name, + "certificates": m.certificates.len(), + "created_at": m.created_at.to_string_canonical(), + })).collect::>(), + }); + Ok(emit(json_out, text, value)) +} + +fn profile_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or("list"); + let rest = &args[1.min(args.len())..]; + match verb { + "list" => { + let mut text = String::from("Leaf profiles (mirroring pkgs/idp-pki idp-ca):\n"); + for prof in profile::leaf_profiles() { + text.push_str(&format!( + " {:12} key={:8} validity={}d {}\n", + prof.name, + prof.key_algorithm.name(), + prof.default_validity.days, + prof.notes + )); + } + let value = json!({ + "profiles": profile::leaf_profiles().iter().map(|p| json!({ + "name": p.name, + "key_algorithm": p.key_algorithm.name(), + "key_usages": p.key_usages.iter().map(|k| format!("{k:?}")).collect::>(), + "extended_key_usages": p.extended_key_usages.iter().map(|k| format!("{k:?}")).collect::>(), + "default_validity_days": p.default_validity.days, + "san_defaults_to_cn": p.san_defaults_to_cn, + "notes": p.notes, + })).collect::>(), + }); + Ok(emit(json_out, text, value)) + } + "show" => { + let name = rest + .first() + .ok_or_else(|| CertError::usage("profile show needs a profile name"))?; + let prof = profile::leaf_profile(name)?; + let text = format!( + "{}: key={} validity={}d san-from-cn={}\n {}\n", + prof.name, + prof.key_algorithm.name(), + prof.default_validity.days, + prof.san_defaults_to_cn, + prof.notes + ); + let value = json!({ + "name": prof.name, + "key_algorithm": prof.key_algorithm.name(), + "default_validity_days": prof.default_validity.days, + "san_defaults_to_cn": prof.san_defaults_to_cn, + "notes": prof.notes, + }); + Ok(emit(json_out, text, value)) + } + other => Err(CertError::usage(format!( + "unknown profile verb '{other}' (list | show)" + ))), + } +} + +// ---------------------------------------------------------------- algorithms + +fn algorithms_cmd(args: &[String], json_out: bool) -> Result { + let verb = args.first().map(|s| s.as_str()).unwrap_or("list"); + match verb { + "list" => { + let reg = algorithm::registry(); + let mut text = String::from("Registered algorithms (spec §3.1/§24.1):\n"); + for info in ® { + text.push_str(&format!( + " {:10} {:9} support={:?} policy={:?} sig-oid={}\n", + info.name, info.display_name, info.support, info.policy, info.signature_oid + )); + } + let value = json!({ + "algorithms": reg.iter().map(|i| json!({ + "id": i.name, + "display_name": i.display_name, + "spki_oid": i.spki_oid, + "signature_oid": i.signature_oid, + "support": format!("{:?}", i.support).to_lowercase(), + "policy": format!("{:?}", i.policy).to_lowercase(), + "post_quantum": i.post_quantum, + "notes": i.notes, + })).collect::>(), + }); + Ok(emit(json_out, text, value)) + } + "describe" => { + let name = args + .get(1) + .ok_or_else(|| CertError::usage("algorithms describe needs an algorithm name"))?; + let (algo, warn) = AlgorithmId::parse(name)?; + let info = algo.info(); + let mut text = format!( + "{} ({})\n spki oid: {}\n signature oid: {}\n support: {:?}\n policy: {:?}\n post-quantum: {}\n {}\n", + info.name, + info.display_name, + info.spki_oid, + info.signature_oid, + info.support, + info.policy, + info.post_quantum, + info.notes + ); + if let Some(w) = &warn { + text.push_str(&format!(" warning: {w}\n")); + } + let value = json!({ + "id": info.name, + "display_name": info.display_name, + "spki_oid": info.spki_oid, + "signature_oid": info.signature_oid, + "support": format!("{:?}", info.support).to_lowercase(), + "policy": format!("{:?}", info.policy).to_lowercase(), + "post_quantum": info.post_quantum, + "notes": info.notes, + "warning": warn, + }); + Ok(emit(json_out, text, value)) + } + other => Err(CertError::usage(format!( + "unknown algorithms verb '{other}' (list | describe)" + ))), + } +} + +// ---------------------------------------------------------------- explain / doctor + +const NOT_BUILT: &[(&str, &str)] = &[ + ("revoke / crl", "revocation + signed CRLs (spec §13 phase F)"), + ("ocsp", "OCSP — only behind a functional responder (spec §4.3)"), + ("publish", "AIA/CDP publication machinery (spec §13 phase F)"), + ("dns", "DNS plan/render/verify (spec §24.7)"), + ("trust", "trust-store install/export (spec §3.5 follow-through)"), + ("key", "key inspect/import/export/convert-public (spec §6.1)"), + ("format", "format list/describe/export/convert (spec §7.5)"), + ("profile validate/scaffold", "profile validation + scaffolding (spec §6.1)"), + ("algorithms benchmark/doctor", "algorithm benchmarks (spec §6.1)"), + ("batch", "batch plan/validate/apply (spec §6.5)"), + ("inventory", "inventory list/show/search/audit (spec §6.1)"), + ("root/issuer renew/rotate/replace", "lifecycle verbs (spec §5.2)"), + ("bundle pack/unpack/diff/migrate", "bundle packaging verbs (spec §7)"), +]; + +fn explain_cmd(args: &[String], json_out: bool) -> Result { + let topic = args.first().map(|s| s.as_str()).unwrap_or("overview"); + let body = match topic { + "overview" => "fleet cert implements the §6.1 command tree's core: root, issuer, leaf, \ +chain, bundle, profile, algorithms, explain, doctor. Signing is library-first (§6.4): \ +the CLI is a thin shell over the fleet-cert crate. Cross-signing is policy data \ +(§§3.2/24.2), time is Gregorian calendar arithmetic (§5.4), and ML-DSA-44 is a \ +first-class algorithm with RFC 9881 identifiers. Topics: signer-source, \ +cross-signing, pq-policy, time, profiles." + .to_string(), + "signer-source" => "Spec §24.3: a root private key is used only when the operator \ +explicitly provides an authorized root source. In this CLI that is --root-key-dir \ +(for issuer create) and --issuer-key-dir (for leaf issue): directories holding the \ +signer's PKCS#8 keys. There is no default lookup, no config-file discovery, and no \ +environment fallback — a missing flag is a policy error, not a prompt. Root creation \ +is a ceremony the other way: it must name its key destination (--private-store or \ +--private-in-bundle) before any key is generated." + .to_string(), + "cross-signing" => "The cross-sign graph is data (crate::graph::GraphPolicy), never a \ +hardcoded loop. Root level (§3.2): classical roots cross-certify each other's keys and \ +the ML-DSA key; the ML-DSA root certifies nothing classical. Issuer level (§24.2): \ +issuer keys are directly cross-signed under every eligible root with the same \ +asymmetry. --cross-signing selects none | roots-only | issuers-direct | both." + .to_string(), + "pq-policy" => "Post-quantum assurance is a verifier policy (§3.2), not an issuance \ +property. `chain test --trust pq` trusts only the ML-DSA root AND requires every key \ +and signature in the path to be ML-DSA-44; a classical cross-certificate over the \ +ML-DSA key does not create a PQ path for a classical leaf. `roots-all` trust gives \ +compatibility, not PQ assurance." + .to_string(), + "time" => "Lifetimes are Gregorian calendar arithmetic (§5.4): 20y is twenty \ +calendar years from the start date (Feb 29 + 1y = Feb 28), never a fixed second \ +count. Defaults: root 20y, issuer 5y, leaf 90d unprofiled (idp-ca profiles carry \ +their own defaults). --not-after takes an exact RFC3339 instant and is mutually \ +exclusive with --valid-for. Every bundle manifest records the resolved RFC3339 \ +window." + .to_string(), + "profiles" => "Leaf profiles mirror pkgs/idp-pki's idp-ca: server (P-256, \ +serverAuth, 730d, SAN defaults to DNS:), client (P-256, clientAuth, 730d), \ +saml-signing and oidc-signing (RSA-2048, digitalSignature + nonRepudiation, 1095d, \ +no EKU). See `fleet cert profile list`." + .to_string(), + other => { + return Err(CertError::usage(format!( + "unknown explain topic '{other}' (overview | signer-source | cross-signing | pq-policy | time | profiles)" + ))) + } + }; + Ok(emit( + json_out, + format!("{body}\n"), + json!({"topic": topic, "explanation": body}), + )) +} + +fn doctor_cmd(_args: &[String], json_out: bool) -> Result { + // Live engine self-test per supported algorithm: generate, + // self-sign, verify — the honest form of "supported". + let mut algo_results = Vec::new(); + let mut all_ok = true; + for info in algorithm::registry() { + let ok = engine_self_test(info.id); + if !ok { + all_ok = false; + } + algo_results.push((info, ok)); + } + let openssl = std::process::Command::new("openssl") + .arg("version") + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()); + let mut text = String::from("fleet cert doctor\n engine self-test (generate + self-sign + verify):\n"); + for (info, ok) in &algo_results { + text.push_str(&format!( + " {:10} {}\n", + info.name, + if *ok { "ok" } else { "FAIL" } + )); + } + text.push_str(&format!( + " openssl (independent validator): {}\n", + openssl.as_deref().unwrap_or("not found") + )); + text.push_str(" built: root, issuer, leaf, chain, bundle (inspect), profile (list/show), algorithms (list/describe), explain, doctor\n"); + text.push_str(" not built yet (tracked as child issues under #9157):\n"); + for (name, what) in NOT_BUILT { + text.push_str(&format!(" {name} — {what}\n")); + } + let value = json!({ + "engine_self_test": algo_results.iter().map(|(i, ok)| json!({"algorithm": i.name, "ok": ok})).collect::>(), + "openssl": openssl, + "built": ["root", "issuer", "leaf", "chain", "bundle-inspect", "profile-list/show", "algorithms-list/describe", "explain", "doctor"], + "not_built": NOT_BUILT.iter().map(|(n, w)| json!({"surface": n, "scope": w})).collect::>(), + }); + let code = emit(json_out, text, value); + Ok(if all_ok { code } else { 1 }) +} + +fn engine_self_test(algo: AlgorithmId) -> bool { + let Ok(key) = engine::generate_key(algo) else { + return false; + }; + let mut params = CertificateParams::new(Vec::::new()).expect("empty SAN list"); + params.distinguished_name.push(DnType::CommonName, "fleet cert doctor self-test"); + params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let now = Rfc3339::now(); + params.not_before = now.0; + params.not_after = (now.0 + time::Duration::days(1)); + let Ok(cert) = params.self_signed(&key) else { + return false; + }; + match crate::chain::parse_cert(cert.der()) { + Ok(info) => crate::chain::verify_signature(&info, &info), + Err(_) => false, + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/engine.rs b/pkgs/fleet/crates/fleet-cert/src/engine.rs new file mode 100644 index 0000000000..ae731bb6a9 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/engine.rs @@ -0,0 +1,1145 @@ +//! The issuance engine: key generation, root/issuer/leaf creation, +//! and bundle-level validation, over rcgen + aws-lc-rs. +//! +//! Invariants the engine keeps: +//! - Every certificate it writes is recorded in the bundle manifest +//! with facts **parsed back from the issued DER** (never from the +//! request), so the manifest cannot drift from the artifacts. +//! - Cross-signing realizes the [`crate::graph`] policy tables; the +//! engine contains no per-algorithm-pair logic. +//! - Signing keys are loaded only from an explicitly passed +//! [`SignerSource`] (§24.3). `create_root_set` generates fresh +//! keys because creation *is* the ceremony; every later signing +//! operation takes its signer from a request field. +//! - Validity windows are clamped to the signer's window with the +//! clamp recorded as a manifest warning (§5.4: a leaf must not +//! outlive its issuer). + +use crate::algorithm::{check_ca_policy, AlgorithmId}; +use crate::bundle::{ + load_bundle, pem_encode, read_artifact, sha256_hex, write_bundle, Artifact, Bundle, +}; +use crate::chain::{parse_cert, validate_chain, CertInfo, ChainReport, TrustSelection}; +use crate::error::{CertError, Result}; +use crate::graph::{CrossSigningMode, GraphPolicy}; +use crate::model::{ + BundleManifest, BundleType, CertRecord, IssuerCreateRequest, LeafIssueRequest, ParentRef, + RootCreateRequest, MANIFEST_SCHEMA, +}; +use crate::naming::{slugify, GenerationPartition}; +use crate::profile::leaf_profile; +use crate::timeparse::Rfc3339; +use rcgen::{ + BasicConstraints, CertificateParams, DnType, DnValue, IsCa, Issuer, KeyPair, KeyUsagePurpose, + RsaKeySize, SerialNumber, PKCS_ECDSA_P256_SHA256, PKCS_ED25519, PKCS_ML_DSA_44, + PKCS_RSA_SHA256, +}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +// ---------------------------------------------------------------- keys + +/// Generate a fresh key pair for a registered algorithm. +pub fn generate_key(algo: AlgorithmId) -> Result { + let key = match algo { + AlgorithmId::Ed25519 => KeyPair::generate_for(&PKCS_ED25519)?, + AlgorithmId::P256 => KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?, + AlgorithmId::MlDsa44 => KeyPair::generate_for(&PKCS_ML_DSA_44)?, + AlgorithmId::Rsa4096 => KeyPair::generate_rsa_for(&PKCS_RSA_SHA256, RsaKeySize::_4096)?, + AlgorithmId::Rsa2048 => KeyPair::generate_rsa_for(&PKCS_RSA_SHA256, RsaKeySize::_2048)?, + }; + Ok(key) +} + +/// An ML-DSA-44 signer wrapping aws-lc-rs directly. +/// +/// rcgen 0.14 generates ML-DSA keys but cannot *reload* them: its +/// PKCS#8 loaders have no PQ branch (the typed loader panics, the +/// detecting loader returns CouldNotParseKeyPair). The signing +/// traits rcgen exposes are public, though, so this wrapper carries +/// a reloaded `PqdsaKeyPair` through the same `Issuer` machinery as +/// every classical key — one TBS builder, one extension profile, +/// no second certificate engine. +pub struct MlDsa44Signer { + key: aws_lc_rs::signature::PqdsaKeyPair, + public_key: Vec, +} + +impl MlDsa44Signer { + pub fn from_pkcs8(der: &[u8]) -> Result { + let key = aws_lc_rs::signature::PqdsaKeyPair::from_pkcs8( + &aws_lc_rs::signature::ML_DSA_44_SIGNING, + der, + ) + .map_err(|e| CertError::engine(format!("ML-DSA-44 key load failed: {e}")))?; + let public_key = aws_lc_rs::signature::KeyPair::public_key(&key) + .as_ref() + .to_vec(); + Ok(MlDsa44Signer { key, public_key }) + } +} + +impl rcgen::PublicKeyData for MlDsa44Signer { + fn der_bytes(&self) -> &[u8] { + &self.public_key + } + fn algorithm(&self) -> &'static rcgen::SignatureAlgorithm { + &PKCS_ML_DSA_44 + } +} + +impl rcgen::SigningKey for MlDsa44Signer { + fn sign(&self, msg: &[u8]) -> std::result::Result, rcgen::Error> { + let mut signature = vec![0; self.key.algorithm().signature_len()]; + self.key + .sign(msg, &mut signature) + .map_err(|_| rcgen::Error::RingUnspecified)?; + Ok(signature) + } +} + +/// A loaded CA signing key, whatever the algorithm. +pub enum CaSigner { + Classical(KeyPair), + MlDsa(Box), +} + +/// Load a signing key from an explicit signer source: the PKCS#8 +/// file named `file_name` inside `source.key_dir`. This is the only +/// key-loading path in the crate (§24.3). +pub fn load_signer_key( + source: &crate::model::SignerSource, + file_name: &str, + algo: AlgorithmId, +) -> Result { + let path = source.key_dir.join(file_name); + let der = std::fs::read(&path).map_err(|e| { + CertError::policy(format!( + "signer source {} does not provide key {file_name}: {e} \ + (signing requires an explicitly passed signer source, spec §24.3)", + source.key_dir.display() + )) + })?; + match algo { + AlgorithmId::MlDsa44 => Ok(CaSigner::MlDsa(Box::new(MlDsa44Signer::from_pkcs8(&der)?))), + _ => { + let sign_alg: &'static rcgen::SignatureAlgorithm = match algo { + AlgorithmId::Ed25519 => &PKCS_ED25519, + AlgorithmId::P256 => &PKCS_ECDSA_P256_SHA256, + AlgorithmId::Rsa4096 | AlgorithmId::Rsa2048 => &PKCS_RSA_SHA256, + AlgorithmId::MlDsa44 => unreachable!(), + }; + Ok(CaSigner::Classical(KeyPair::from_pkcs8_der_and_sign_algo( + &rustls_pki_types::PrivatePkcs8KeyDer::from(der), + sign_alg, + )?)) + } + } +} + +fn random_serial() -> SerialNumber { + let mut bytes = [0u8; 16]; + aws_lc_rs::rand::fill(&mut bytes).expect("system RNG available"); + // Keep the serial a positive 16-byte integer with the top bits + // set (high entropy, never a small or negative encoding). + bytes[0] = (bytes[0] & 0x3f) | 0x40; + SerialNumber::from_slice(&bytes) +} + +// ---------------------------------------------------------------- DNs + +/// Build a distinguished name with the crate's one encoding +/// convention: country as PrintableString (as in rcgen's examples), +/// everything else as UTF8String. Creation and later reconstruction +/// (when a stored CA signs again) use this same function, so issuer +/// names in children byte-match the CA's subject. +fn distinguished_name( + organization: &str, + country: &str, + ou: Option<&str>, + cn: &str, +) -> rcgen::DistinguishedName { + let mut dn = rcgen::DistinguishedName::new(); + if !country.is_empty() { + if let Ok(ps) = >::try_from(country) { + dn.push(DnType::CountryName, DnValue::PrintableString(ps)); + } + } + dn.push(DnType::OrganizationName, organization); + if let Some(ou) = ou { + dn.push(DnType::OrganizationalUnitName, ou); + } + dn.push(DnType::CommonName, cn); + dn +} + +/// Rebuild rcgen params for a stored CA certificate so it can sign: +/// subject DN reconstructed with the crate convention, CA profile +/// reapplied. The validity in the returned params is the *child's* +/// concern; the issuer's own window is enforced by clamping before +/// this is called. +fn ca_params_for( + org: &str, + country: &str, + ou: Option<&str>, + cn: &str, + path_len: u8, + not_before: Rfc3339, + not_after: Rfc3339, +) -> CertificateParams { + let mut params = CertificateParams::new(Vec::::new()) + .expect("empty SAN list is valid"); + params.distinguished_name = distinguished_name(org, country, ou, cn); + params.is_ca = IsCa::Ca(BasicConstraints::Constrained(path_len)); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + params.not_before = not_before.0; + params.not_after = not_after.0; + params.serial_number = Some(random_serial()); + params.use_authority_key_identifier_extension = true; + params +} + +/// A loaded CA: everything needed to sign with it. +struct CaHandle { + params: CertificateParams, + signer: CaSigner, + cert: CertInfo, +} + +impl CaHandle { + /// Sign `subject_params` for `subject_key` with this CA. + fn sign( + &self, + subject_params: &CertificateParams, + subject_key: &KeyPair, + ) -> Result { + match &self.signer { + CaSigner::Classical(key) => Ok(subject_params + .signed_by(subject_key, &Issuer::new(self.params.clone(), key))?), + CaSigner::MlDsa(signer) => Ok(subject_params + .signed_by(subject_key, &Issuer::new(self.params.clone(), signer.as_ref()))?), + } + } +} + +/// Load a CA (cert + key) from a bundle record through an explicit +/// signer source. The record supplies the cert path and the key file +/// name; the key bytes come only from `signer`. +fn load_ca( + bundle: &Bundle, + record: &CertRecord, + signer: &crate::model::SignerSource, + org: &str, + country: &str, + ou: Option<&str>, + cn: &str, + path_len: u8, +) -> Result { + let pem = read_artifact(bundle, &record.cert_path)?; + let blocks = crate::bundle::pem_decode_all(std::str::from_utf8(&pem).map_err(|_| { + CertError::manifest(format!("{} is not UTF-8 PEM", record.cert_path)) + })?)?; + let der = blocks + .into_iter() + .find(|(label, _)| label == "CERTIFICATE") + .map(|(_, der)| der) + .ok_or_else(|| CertError::manifest(format!("no CERTIFICATE block in {}", record.cert_path)))?; + let cert = parse_cert(&der)?; + // The key file name comes from the manifest record when the key + // lives in the bundle; for external-store custody the creation + // naming convention applies (`.pk8` roots, + // `-.pk8` issuers) inside the store directory + // the caller passes as the signer source. + let key_file = record + .key_path + .as_deref() + .and_then(|p| Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned())) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| match record.role.as_str() { + "root" => format!("{}.pk8", record.algorithm.name()), + _ => format!("{}-{}.pk8", record.algorithm.name(), record.partition), + }); + let signer_key = load_signer_key(signer, &key_file, record.algorithm)?; + let params = ca_params_for( + org, + country, + ou, + cn, + path_len, + cert.not_before, + cert.not_after, + ); + Ok(CaHandle { + params, + signer: signer_key, + cert, + }) +} + +// ---------------------------------------------------------------- records + +/// Build a manifest record from the issued DER (facts parsed back, +/// never copied from the request). +fn record_from_der( + der: &[u8], + role: &str, + partition: &str, + primary: bool, + cert_path: String, + key_path: Option, +) -> Result { + let info = parse_cert(der)?; + Ok(CertRecord { + role: role.to_string(), + algorithm: info + .subject_algorithm + .ok_or_else(|| CertError::engine("issued certificate has an unregistered subject algorithm"))?, + signer_algorithm: None, // filled by caller when not self-signed + partition: partition.to_string(), + primary, + subject_dn: info.subject_dn.clone(), + issuer_dn: info.issuer_dn.clone(), + serial_hex: info.serial_hex.clone(), + ski_hex: info.ski.as_deref().map(crate::chain::hex_bytes).unwrap_or_default(), + aki_hex: info.aki.as_deref().map(crate::chain::hex_bytes).unwrap_or_default(), + fingerprint_sha256: info.fingerprint_sha256.clone(), + not_before: info.not_before, + not_after: info.not_after, + is_ca: info.is_ca, + path_len: info.path_len, + cert_path, + key_path, + }) +} + +fn base_manifest( + bundle_type: BundleType, + name: &str, + organization: &str, + country: &str, + purpose: Option, + generation: u32, + parent: Option, + key_location: &str, + cross_signing: Option, + warnings: Vec, +) -> Result { + Ok(BundleManifest { + schema: MANIFEST_SCHEMA.to_string(), + bundle_id: String::new(), // set by caller once a fingerprint exists + bundle_type, + bundle_version: 1, + name: name.to_string(), + slug: slugify(name)?, + organization: organization.to_string(), + country: country.to_string(), + purpose, + generation, + created_at: Rfc3339::now(), + engine_version: env!("CARGO_PKG_VERSION").to_string(), + parent, + key_location: key_location.to_string(), + cross_signing, + certificates: Vec::new(), + files: Vec::new(), + warnings, + }) +} + +fn key_rel_path(file_name: &str) -> String { + format!("private/keys/{file_name}") +} + +/// Where a created bundle's keys physically go, and the manifest's +/// custody class for them. +fn key_destination( + out_dir: &Path, + private_store: &Option, +) -> (PathBuf, &'static str) { + match private_store { + Some(store) => (store.clone(), "external-store"), + None => (out_dir.join("private/keys"), "bundle-private"), + } +} + +/// Write key files for a creation run. Keys in an external store are +/// written there directly (0600); keys in the bundle go through the +/// artifact list so they are checksummed in the manifest. +fn stage_key( + artifacts: &mut Vec, + external_dir: Option<&Path>, + file_name: &str, + key: &KeyPair, +) -> Result> { + let der = key.serialize_der(); + match external_dir { + Some(dir) => { + std::fs::create_dir_all(dir)?; + let path = dir.join(file_name); + std::fs::write(&path, &der)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + } + Ok(None) + } + None => { + let rel = key_rel_path(file_name); + artifacts.push(Artifact { + rel_path: rel.clone(), + kind: "private-key-pkcs8".into(), + visibility: "private".into(), + bytes: der, + }); + Ok(Some(rel)) + } + } +} + +// ---------------------------------------------------------------- roots + +/// `cert root create`: generate a root set — one self-signed root +/// per algorithm, plus the root-level cross-certificates the graph +/// policy and mode call for — and the §3.5 trust bundles. +pub fn create_root_set(req: &RootCreateRequest, out_dir: &Path) -> Result { + check_ca_policy(&req.algorithms, req.allow_legacy_root_strength)?; + let mut seen = Vec::new(); + for algo in &req.algorithms { + if seen.contains(algo) { + return Err(CertError::usage(format!( + "duplicate algorithm {} in a root set (one key per algorithm per generation/partition)", + algo.name() + ))); + } + seen.push(*algo); + } + let gp = GenerationPartition::new(req.generation, &req.partition)?; + let graph = GraphPolicy::spec_default(); + let (key_dir, key_location) = key_destination(out_dir, &req.private_store); + let external = if req.private_store.is_some() { + Some(key_dir.as_path()) + } else { + None + }; + + // Generate keys and self-signed roots. + struct RootKey { + algo: AlgorithmId, + key: KeyPair, + params: CertificateParams, + der: Vec, + key_path: Option, + } + let mut artifacts: Vec = Vec::new(); + let mut roots: Vec = Vec::new(); + for algo in &req.algorithms { + let key = generate_key(*algo)?; + let cn = format!( + "{} Root {} CA {}", + req.organization, + algo.display_name(), + gp.cn_tail() + ); + let params = ca_params_for( + &req.organization, + &req.country, + None, + &cn, + 1, + req.not_before, + req.not_after, + ); + let cert = params.self_signed(&key)?; + let key_path = stage_key( + &mut artifacts, + external, + &format!("{}.pk8", algo.name()), + &key, + )?; + roots.push(RootKey { + algo: *algo, + key, + params, + der: cert.der().to_vec(), + key_path, + }); + } + + let mut records = Vec::new(); + let mut warnings = Vec::new(); + // Self-signed records + public artifacts. + for root in &roots { + let rel = format!("public/roots/{}/root.crt.pem", root.algo.name()); + artifacts.push(Artifact { + rel_path: rel.clone(), + kind: "certificate-pem".into(), + visibility: "public".into(), + bytes: pem_encode("CERTIFICATE", &root.der).into_bytes(), + }); + records.push(record_from_der( + &root.der, + "root", + &gp.partition, + true, + rel, + root.key_path.clone(), + )?); + } + // Cross-certificates, realized from the policy table. + if req.cross_signing.root_level_active() { + for subject in &roots { + for signer_algo in graph.root_signers_for(subject.algo) { + let Some(signer) = roots.iter().find(|r| r.algo == signer_algo) else { + continue; + }; + let issuer = Issuer::new(signer.params.clone(), &signer.key); + let mut cross_params = subject.params.clone(); + cross_params.serial_number = Some(random_serial()); + let cert = cross_params.signed_by(&subject.key, &issuer)?; + let der = cert.der().to_vec(); + let rel = format!( + "public/cross/{}/signed-by-{}.crt.pem", + subject.algo.name(), + signer_algo.name() + ); + artifacts.push(Artifact { + rel_path: rel.clone(), + kind: "certificate-pem".into(), + visibility: "public".into(), + bytes: pem_encode("CERTIFICATE", &der).into_bytes(), + }); + let mut rec = record_from_der(&der, "root-cross", &gp.partition, false, rel, None)?; + rec.signer_algorithm = Some(signer_algo); + records.push(rec); + } + } + } else if req.cross_signing.issuer_level_active() { + warnings.push( + "cross-signing mode issuers-direct creates no root-level cross-certificates".into(), + ); + } + + // Trust bundles (§3.5). + let mut bundle_pem = |name: &str, ders: &[&Vec]| { + let mut text = String::new(); + for der in ders { + text.push_str(&pem_encode("CERTIFICATE", der)); + } + artifacts.push(Artifact { + rel_path: format!("public/bundles/{name}"), + kind: "trust-bundle-pem".into(), + visibility: "public".into(), + bytes: text.into_bytes(), + }); + }; + let all: Vec<&Vec> = roots.iter().map(|r| &r.der).collect(); + bundle_pem("roots-all.pem", &all); + let classical: Vec<&Vec> = roots + .iter() + .filter(|r| r.algo.is_classical()) + .map(|r| &r.der) + .collect(); + if !classical.is_empty() { + bundle_pem("roots-classical.pem", &classical); + } + let pq: Vec<&Vec> = roots + .iter() + .filter(|r| r.algo.is_post_quantum()) + .map(|r| &r.der) + .collect(); + if !pq.is_empty() { + bundle_pem("roots-pq.pem", &pq); + } + let cross_ders: Vec> = records + .iter() + .filter(|r| r.role == "root-cross") + .filter_map(|r| { + artifacts + .iter() + .find(|a| a.rel_path == r.cert_path) + .map(|a| a.bytes.clone()) + }) + .collect(); + if !cross_ders.is_empty() { + // cross-certs.pem holds the PEM text of every cross cert. + let mut text = String::new(); + for pem in &cross_ders { + text.push_str(std::str::from_utf8(pem).unwrap_or("")); + } + artifacts.push(Artifact { + rel_path: "public/bundles/cross-certs.pem".into(), + kind: "trust-bundle-pem".into(), + visibility: "public".into(), + bytes: text.into_bytes(), + }); + } + + let name = format!("Root Set {}", gp.machine_id().to_ascii_uppercase()); + let mut manifest = base_manifest( + BundleType::RootSet, + &name, + &req.organization, + &req.country, + None, + req.generation, + None, + key_location, + Some(req.cross_signing.as_str().to_string()), + warnings, + )?; + manifest.bundle_id = format!( + "rootset-{}-{}", + gp.machine_id(), + &records + .first() + .map(|r| r.fingerprint_sha256[..12].to_string()) + .unwrap_or_default() + ); + manifest.certificates = records; + let manifest = write_bundle(out_dir, manifest, &artifacts)?; + Ok(manifest) +} + +// ---------------------------------------------------------------- issuers + +/// `cert issuer create`: generate an issuer set — independent keys +/// per (algorithm, partition) slot, each certified by its primary +/// root plus the direct cross-sign variants the policy realizes. +/// Root signing keys come only from `req.root_signer` (§24.3). +pub fn create_issuer_set(req: &IssuerCreateRequest, out_dir: &Path) -> Result { + let slot_algos: Vec = req.slots.iter().map(|(a, _)| *a).collect(); + check_ca_policy(&slot_algos, req.allow_legacy_root_strength)?; + let root_bundle = load_bundle(&req.root_bundle)?; + if root_bundle.manifest.bundle_type != BundleType::RootSet { + return Err(CertError::usage(format!( + "{} is a {} bundle, not a root set", + req.root_bundle.display(), + root_bundle.manifest.bundle_type.as_str() + ))); + } + let root_records: Vec<&CertRecord> = root_bundle + .manifest + .certificates + .iter() + .filter(|r| r.role == "root") + .collect(); + let root_algos: Vec = root_records.iter().map(|r| r.algorithm).collect(); + for algo in &slot_algos { + if !root_algos.contains(algo) { + return Err(CertError::usage(format!( + "the root set has no {} root to sign a {} issuer", + algo.name(), + algo.name() + ))); + } + } + let graph = GraphPolicy::spec_default(); + let (key_dir, key_location) = key_destination(out_dir, &req.private_store); + let external = if req.private_store.is_some() { + Some(key_dir.as_path()) + } else { + None + }; + let ou = req.ou.clone().or_else(|| match req.purpose { + crate::model::IssuerPurpose::WebServer => Some(format!("{} Services", req.name)), + crate::model::IssuerPurpose::General => None, + }); + + // Load every root signer handle up front (fail before keygen if + // the signer source is incomplete). + let mut root_handles: BTreeMap = BTreeMap::new(); + for record in &root_records { + // Rebuild the root's CN from its record facts: the subject DN + // was produced by this crate's convention; extract the CN. + let root_cn = extract_cn(&record.subject_dn).ok_or_else(|| { + CertError::manifest(format!( + "root record for {} has no CN in its subject DN", + record.algorithm.name() + )) + })?; + let handle = load_ca( + &root_bundle, + record, + &req.root_signer, + &root_bundle.manifest.organization, + &root_bundle.manifest.country, + None, + &root_cn, + 1, + )?; + root_handles.insert(record.algorithm, handle); + } + + let mut artifacts: Vec = Vec::new(); + let mut records = Vec::new(); + let mut warnings = Vec::new(); + for (algo, partition) in &req.slots { + let gp = GenerationPartition::new(root_bundle.manifest.generation, partition)?; + let key = generate_key(*algo)?; + let cn = format!( + "{} {} Issuing {} CA {}", + root_bundle.manifest.organization, + req.name, + algo.display_name(), + gp.cn_tail() + ); + // Clamp the issuer window to the primary root's window. + let primary_root = &root_handles[algo]; + let (nb, na) = clamp_window( + req.not_before, + req.not_after, + primary_root.cert.not_before, + primary_root.cert.not_after, + &cn, + &mut warnings, + )?; + let mut params = ca_params_for( + &root_bundle.manifest.organization, + &root_bundle.manifest.country, + ou.as_deref(), + &cn, + 0, + nb, + na, + ); + if req.purpose == crate::model::IssuerPurpose::WebServer && !req.permitted_dns.is_empty() { + params.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: req + .permitted_dns + .iter() + .map(|d| rcgen::GeneralSubtree::DnsName(d.clone())) + .collect(), + excluded_subtrees: Vec::new(), + }); + } + let key_file = format!("{}-{}.pk8", algo.name(), partition); + let key_path = stage_key(&mut artifacts, external, &key_file, &key)?; + + // Signer set: primary first, then policy direct signers. + let mut signers = vec![*algo]; + if req.cross_signing.issuer_level_active() { + for signer in graph.issuer_signers_for(*algo) { + if root_algos.contains(&signer) { + signers.push(signer); + } + } + } + for (i, signer_algo) in signers.iter().enumerate() { + let signer = &root_handles[signer_algo]; + // Each variant's window clamps to its own signer's window. + let (snb, sna) = clamp_window( + nb, + na, + signer.cert.not_before, + signer.cert.not_after, + &cn, + &mut warnings, + )?; + let mut variant_params = params.clone(); + variant_params.not_before = snb.0; + variant_params.not_after = sna.0; + variant_params.serial_number = Some(random_serial()); + let cert = signer.sign(&variant_params, &key)?; + let der = cert.der().to_vec(); + let rel = format!( + "public/certs/{}/{}/signed-by-{}.crt.pem", + algo.name(), + partition, + signer_algo.name() + ); + artifacts.push(Artifact { + rel_path: rel.clone(), + kind: "certificate-pem".into(), + visibility: "public".into(), + bytes: pem_encode("CERTIFICATE", &der).into_bytes(), + }); + let mut rec = record_from_der(&der, "issuer", partition, i == 0, rel, key_path.clone())?; + rec.signer_algorithm = Some(*signer_algo); + records.push(rec); + } + } + + let parent = ParentRef { + bundle_type: BundleType::RootSet, + bundle_id: root_bundle.manifest.bundle_id.clone(), + name: root_bundle.manifest.name.clone(), + anchor_fingerprints: root_records + .iter() + .map(|r| r.fingerprint_sha256.clone()) + .collect(), + }; + let generation = root_bundle.manifest.generation; + let mut manifest = base_manifest( + BundleType::IssuerSet, + &req.name, + &root_bundle.manifest.organization, + &root_bundle.manifest.country, + Some(req.purpose.as_str().to_string()), + generation, + Some(parent), + key_location, + Some(req.cross_signing.as_str().to_string()), + warnings, + )?; + manifest.bundle_id = format!( + "issuerset-{}-{}", + manifest.slug, + &records + .first() + .map(|r| r.fingerprint_sha256[..12].to_string()) + .unwrap_or_default() + ); + manifest.certificates = records; + let manifest = write_bundle(out_dir, manifest, &artifacts)?; + Ok(manifest) +} + +fn extract_cn(dn: &str) -> Option { + // rcgen/x509-parser DN rendering: "CN=..., O=..., C=..." — take + // the CN RDN value (crate-produced DNs have no escaped commas in + // the CN by construction of our naming). + for part in dn.split(", ") { + if let Some(v) = part.strip_prefix("CN=") { + return Some(v.to_string()); + } + } + None +} + +fn clamp_window( + nb: Rfc3339, + na: Rfc3339, + signer_nb: Rfc3339, + signer_na: Rfc3339, + what: &str, + warnings: &mut Vec, +) -> Result<(Rfc3339, Rfc3339)> { + let nb2 = nb.max(signer_nb); + let na2 = na.min(signer_na); + if nb2 != nb || na2 != na { + warnings.push(format!( + "{what}: validity clamped to the signer's window ({signer_nb} .. {signer_na})" + )); + } + if na2 <= nb2 { + return Err(CertError::policy(format!( + "{what}: requested validity {nb} .. {na} does not intersect the signer's window {signer_nb} .. {signer_na}" + ))); + } + Ok((nb2, na2)) +} + +// ---------------------------------------------------------------- leaves + +/// `cert leaf issue`: issue one leaf from an issuer bundle, signed +/// by the selected issuer key loaded from `req.issuer_signer`. +pub fn issue_leaf(req: &LeafIssueRequest, out_dir: &Path) -> Result { + let profile = leaf_profile(&req.profile)?; + let issuer_bundle = load_bundle(&req.issuer_bundle)?; + if issuer_bundle.manifest.bundle_type != BundleType::IssuerSet { + return Err(CertError::usage(format!( + "{} is a {} bundle, not an issuer set", + req.issuer_bundle.display(), + issuer_bundle.manifest.bundle_type.as_str() + ))); + } + let key_algo = req.key_algorithm.unwrap_or(profile.key_algorithm); + let issuer_partition = req + .issuer_partition + .clone() + .unwrap_or_else(|| "a".to_string()) + .to_ascii_lowercase(); + // The primary variant record for the selected issuer slot. The + // signer selection defaults to the requested issuer algorithm, + // then the leaf key's algorithm, then the set's first primary + // slot in the partition — a signing profile whose key algorithm + // has no CA slot (idp-ca's RSA-2048 signing leaves) still signs + // from a real issuer key. + let wanted = req.issuer_algorithm.unwrap_or(key_algo); + let slot_record = issuer_bundle + .manifest + .certificates + .iter() + .filter(|r| r.role == "issuer" && r.primary && r.partition == issuer_partition) + .find(|r| r.algorithm == wanted) + .or_else(|| { + issuer_bundle + .manifest + .certificates + .iter() + .find(|r| r.role == "issuer" && r.primary && r.partition == issuer_partition) + }) + .ok_or_else(|| { + CertError::usage(format!( + "issuer set has no primary {} partition {} CA (slots: {})", + wanted.name(), + issuer_partition.to_ascii_uppercase(), + issuer_bundle + .manifest + .certificates + .iter() + .filter(|r| r.role == "issuer" && r.primary) + .map(|r| format!("{}-{}", r.algorithm.name(), r.partition)) + .collect::>() + .join(", ") + )) + })?; + let issuer_cn = extract_cn(&slot_record.subject_dn).ok_or_else(|| { + CertError::manifest("issuer record has no CN in its subject DN".to_string()) + })?; + let issuer_ou = extract_ou(&slot_record.subject_dn); + let issuer = load_ca( + &issuer_bundle, + slot_record, + &req.issuer_signer, + &issuer_bundle.manifest.organization, + &issuer_bundle.manifest.country, + issuer_ou.as_deref(), + &issuer_cn, + 0, + )?; + + let mut warnings = Vec::new(); + let (nb, na) = clamp_window( + req.not_before, + req.not_after, + issuer.cert.not_before, + issuer.cert.not_after, + &req.name, + &mut warnings, + )?; + + // Subject + SANs. + let mut sans: Vec = req.dns_names.clone(); + let cn = req + .common_name + .clone() + .or_else(|| sans.first().cloned()) + .unwrap_or_else(|| req.name.clone()); + if sans.is_empty() && profile.san_defaults_to_cn { + sans.push(cn.clone()); + } + let key = generate_key(key_algo)?; + let mut params = + CertificateParams::new(sans.clone()).map_err(|e| CertError::engine(e.to_string()))?; + params.distinguished_name = distinguished_name( + &issuer_bundle.manifest.organization, + &issuer_bundle.manifest.country, + None, + &cn, + ); + params.is_ca = IsCa::ExplicitNoCa; + params.key_usages = profile.key_usages.to_vec(); + params.extended_key_usages = profile.extended_key_usages.to_vec(); + params.not_before = nb.0; + params.not_after = na.0; + params.serial_number = Some(random_serial()); + params.use_authority_key_identifier_extension = true; + let cert = issuer.sign(¶ms, &key)?; + let der = cert.der().to_vec(); + + let (key_dir, key_location) = key_destination(out_dir, &req.private_store); + let external = if req.private_store.is_some() { + Some(key_dir.as_path()) + } else { + None + }; + let mut artifacts = Vec::new(); + let key_path = stage_key(&mut artifacts, external, "leaf.pk8", &key)?; + let leaf_rel = "leaf.crt.pem".to_string(); + artifacts.push(Artifact { + rel_path: leaf_rel.clone(), + kind: "certificate-pem".into(), + visibility: "public".into(), + bytes: pem_encode("CERTIFICATE", &der).into_bytes(), + }); + // chain.pem: leaf + the primary issuer variant. + let issuer_pem = read_artifact(&issuer_bundle, &slot_record.cert_path)?; + let mut chain = pem_encode("CERTIFICATE", &der); + chain.push_str(std::str::from_utf8(&issuer_pem).unwrap_or("")); + artifacts.push(Artifact { + rel_path: "chain.pem".into(), + kind: "chain-pem".into(), + visibility: "public".into(), + bytes: chain.into_bytes(), + }); + let mut rec = record_from_der(&der, "leaf", &issuer_partition, true, leaf_rel, key_path)?; + rec.signer_algorithm = Some(slot_record.algorithm); + + let parent = ParentRef { + bundle_type: BundleType::IssuerSet, + bundle_id: issuer_bundle.manifest.bundle_id.clone(), + name: issuer_bundle.manifest.name.clone(), + anchor_fingerprints: vec![slot_record.fingerprint_sha256.clone()], + }; + let mut manifest = base_manifest( + BundleType::Leaf, + &req.name, + &issuer_bundle.manifest.organization, + &issuer_bundle.manifest.country, + Some(req.profile.clone()), + issuer_bundle.manifest.generation, + Some(parent), + key_location, + None, + warnings, + )?; + manifest.bundle_id = format!( + "leaf-{}-{}", + manifest.slug, + &rec.fingerprint_sha256[..12] + ); + manifest.certificates = vec![rec]; + let manifest = write_bundle(out_dir, manifest, &artifacts)?; + Ok(manifest) +} + +fn extract_ou(dn: &str) -> Option { + for part in dn.split(", ") { + if let Some(v) = part.strip_prefix("OU=") { + return Some(v.to_string()); + } + } + None +} + +// ---------------------------------------------------------------- validation + +/// Validate a root bundle end to end: manifest checksums (via +/// load), every self-signed root's self-signature, every cross +/// certificate's signature against its signer root, and the +/// realized graph against the policy's expected inventory. +pub fn validate_root_bundle(dir: &Path) -> Result> { + let bundle = load_bundle(dir)?; + if bundle.manifest.bundle_type != BundleType::RootSet { + return Err(CertError::usage(format!( + "{} is not a root set bundle", + dir.display() + ))); + } + let mut checks = vec![crate::chain::Check { + name: "manifest-checksums".into(), + ok: true, + detail: format!("{} files verified", bundle.manifest.files.len()), + }]; + let mut infos: BTreeMap = BTreeMap::new(); + for record in &bundle.manifest.certificates { + let pem = read_artifact(&bundle, &record.cert_path)?; + let blocks = crate::bundle::pem_decode_all(std::str::from_utf8(&pem).unwrap_or(""))?; + let der = blocks + .into_iter() + .find(|(l, _)| l == "CERTIFICATE") + .map(|(_, d)| d) + .ok_or_else(|| CertError::manifest("no CERTIFICATE block"))?; + infos.insert(record.fingerprint_sha256.clone(), parse_cert(&der)?); + } + let by_algo: BTreeMap = bundle + .manifest + .certificates + .iter() + .filter(|r| r.role == "root") + .map(|r| (r.algorithm, r)) + .collect(); + for record in &bundle.manifest.certificates { + let info = &infos[&record.fingerprint_sha256]; + let (ok, detail) = if record.role == "root" { + ( + crate::chain::verify_signature(info, info), + "self-signature verifies".to_string(), + ) + } else { + let signer_algo = record.signer_algorithm.unwrap_or(record.algorithm); + match by_algo.get(&signer_algo) { + Some(signer_rec) => { + let signer_info = &infos[&signer_rec.fingerprint_sha256]; + ( + crate::chain::verify_signature(signer_info, info), + format!("signed by {} root", signer_algo.name()), + ) + } + None => (false, format!("signer {} root missing", signer_algo.name())), + } + }; + checks.push(crate::chain::Check { + name: format!("signature:{}", record.subject_dn), + ok, + detail, + }); + } + // Graph inventory vs policy. + let algos: Vec = by_algo.keys().copied().collect(); + let mode = bundle + .manifest + .cross_signing + .as_deref() + .map(CrossSigningMode::parse) + .transpose()? + .unwrap_or(CrossSigningMode::Both); + let expected = GraphPolicy::spec_default().expected_root_certificates(&algos, mode); + let actual = bundle.manifest.certificates.len(); + checks.push(crate::chain::Check { + name: "graph-inventory".into(), + ok: expected == actual, + detail: format!( + "policy expects {expected} root-level certificates for {} under {}, bundle carries {actual}", + algos + .iter() + .map(|a| a.name()) + .collect::>() + .join(","), + mode.as_str() + ), + }); + Ok(checks) +} + +/// Collect every certificate from a set of bundles into one pool +/// (for chain building/testing across bundle boundaries). +pub fn collect_pool(bundles: &[&Bundle]) -> Result> { + let mut out = Vec::new(); + for bundle in bundles { + for record in &bundle.manifest.certificates { + let pem = read_artifact(bundle, &record.cert_path)?; + let blocks = + crate::bundle::pem_decode_all(std::str::from_utf8(&pem).unwrap_or(""))?; + for (label, der) in blocks { + if label == "CERTIFICATE" { + out.push(parse_cert(&der)?); + } + } + } + } + Ok(out) +} + +/// Validate a leaf bundle's certificate against issuer + root +/// bundles under a trust selection. +pub fn validate_leaf( + leaf_bundle: &Bundle, + pool_bundles: &[&Bundle], + trust: TrustSelection, + at: Rfc3339, +) -> Result { + let leaf_record = leaf_bundle + .manifest + .certificates + .iter() + .find(|r| r.role == "leaf") + .ok_or_else(|| CertError::manifest("leaf bundle has no leaf record"))?; + let pem = read_artifact(leaf_bundle, &leaf_record.cert_path)?; + let blocks = crate::bundle::pem_decode_all(std::str::from_utf8(&pem).unwrap_or(""))?; + let der = blocks + .into_iter() + .find(|(l, _)| l == "CERTIFICATE") + .map(|(_, d)| d) + .ok_or_else(|| CertError::manifest("no CERTIFICATE block in leaf"))?; + let leaf = parse_cert(&der)?; + let pool = collect_pool(pool_bundles)?; + Ok(validate_chain(&leaf, &pool, trust, at)) +} + +/// Fingerprint helper kept public for reports. +pub fn fingerprint_of(der: &[u8]) -> String { + sha256_hex(der) +} diff --git a/pkgs/fleet/crates/fleet-cert/src/error.rs b/pkgs/fleet/crates/fleet-cert/src/error.rs new file mode 100644 index 0000000000..a3be627a91 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/error.rs @@ -0,0 +1,85 @@ +//! The crate's error type. Every failure the CLI can produce is one of +//! these; `exit_code` maps them onto the fleet binary's contract +//! (0 ok · 2 usage · 1 operational failure · 69 unavailable). + +use std::fmt; + +#[derive(Debug)] +pub enum CertError { + /// Bad flags, bad values, contradictory options — the caller's fault. + Usage(String), + /// A spec policy gate refused the operation (legacy algorithm + /// without its opt-in, a missing explicit signer source, a + /// forbidden cross-sign edge, a PQ-policy violation, ...). + Policy(String), + /// The underlying engine (rcgen / aws-lc-rs) refused. + Engine(String), + /// A bundle or manifest is missing, malformed, or fails its own + /// checksums. + Manifest(String), + /// Chain building or validation failed; the message carries the + /// per-check detail. + Validation(String), + /// Filesystem failure. + Io(std::io::Error), +} + +impl CertError { + pub fn usage(msg: impl Into) -> Self { + CertError::Usage(msg.into()) + } + pub fn policy(msg: impl Into) -> Self { + CertError::Policy(msg.into()) + } + pub fn engine(msg: impl Into) -> Self { + CertError::Engine(msg.into()) + } + pub fn manifest(msg: impl Into) -> Self { + CertError::Manifest(msg.into()) + } + pub fn validation(msg: impl Into) -> Self { + CertError::Validation(msg.into()) + } + + pub fn exit_code(&self) -> i32 { + match self { + CertError::Usage(_) => 2, + _ => 1, + } + } +} + +impl fmt::Display for CertError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CertError::Usage(m) => write!(f, "usage: {m}"), + CertError::Policy(m) => write!(f, "policy: {m}"), + CertError::Engine(m) => write!(f, "engine: {m}"), + CertError::Manifest(m) => write!(f, "manifest: {m}"), + CertError::Validation(m) => write!(f, "validation: {m}"), + CertError::Io(e) => write!(f, "io: {e}"), + } + } +} + +impl std::error::Error for CertError {} + +impl From for CertError { + fn from(e: std::io::Error) -> Self { + CertError::Io(e) + } +} + +impl From for CertError { + fn from(e: rcgen::Error) -> Self { + CertError::Engine(e.to_string()) + } +} + +impl From for CertError { + fn from(e: serde_json::Error) -> Self { + CertError::Manifest(format!("json: {e}")) + } +} + +pub type Result = std::result::Result; diff --git a/pkgs/fleet/crates/fleet-cert/src/graph.rs b/pkgs/fleet/crates/fleet-cert/src/graph.rs new file mode 100644 index 0000000000..37691f736a --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/graph.rs @@ -0,0 +1,269 @@ +//! The cross-signing graph as data/policy (spec §§3.2, 24.2). +//! +//! The graph is **never** a hardcoded four-by-four loop in the +//! engine. It is two explicit edge tables — one for root-level +//! cross-certificates (§3.2), one for directly cross-signed issuer +//! variants (§24.2) — plus a mode that selects how much of the table +//! a given creation run realizes. A future algorithm or a changed +//! policy edits the tables, not the engine. +//! +//! The invariant both tables encode: classical signers may certify +//! every subject (including the ML-DSA subject — a classical +//! cross-certificate over the ML-DSA key is how classical-only +//! clients reach the PQ hierarchy), while the ML-DSA signer +//! certifies **only** ML-DSA subjects. No ML-DSA→classical edge +//! exists, by policy: a PQ-enforced verifier trusting only the +//! ML-DSA root must never be handed a path in which the ML-DSA key +//! vouched for a classical key (§3.2 rationale). + +use crate::algorithm::AlgorithmId; +use crate::error::{CertError, Result}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// How much of the graph a creation run realizes (spec §24.2: +/// `--cross-signing roots-only|issuers-direct|both|none`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum CrossSigningMode { + /// No cross-certificates at all; each key has only its primary + /// (self-signed for roots, same-algorithm-signed for issuers). + None, + /// Cross-sign at the root level only; issuer keys get only their + /// primary variant. Recommended where graph simplicity matters. + RootsOnly, + /// Issuer keys are directly cross-signed under every eligible + /// root; no root-level cross-certificates. + IssuersDirect, + /// Both levels (the §24.2 reference-run shape). + Both, +} + +impl CrossSigningMode { + pub fn parse(input: &str) -> Result { + match input.trim().to_ascii_lowercase().as_str() { + "none" => Ok(CrossSigningMode::None), + "roots-only" | "roots" => Ok(CrossSigningMode::RootsOnly), + "issuers-direct" | "direct" => Ok(CrossSigningMode::IssuersDirect), + "both" => Ok(CrossSigningMode::Both), + other => Err(CertError::usage(format!( + "unknown cross-signing mode '{other}' (none | roots-only | issuers-direct | both)" + ))), + } + } + + pub fn as_str(&self) -> &'static str { + match self { + CrossSigningMode::None => "none", + CrossSigningMode::RootsOnly => "roots-only", + CrossSigningMode::IssuersDirect => "issuers-direct", + CrossSigningMode::Both => "both", + } + } + + pub fn root_level_active(&self) -> bool { + matches!(self, CrossSigningMode::RootsOnly | CrossSigningMode::Both) + } + + pub fn issuer_level_active(&self) -> bool { + matches!(self, CrossSigningMode::IssuersDirect | CrossSigningMode::Both) + } +} + +/// One directed edge: `signer` may certify `subject`'s key. +pub type Edge = (AlgorithmId, AlgorithmId); + +/// The policy tables. Rows are data; adding an algorithm or changing +/// who may sign whom is an edit here, reviewed like policy. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GraphPolicy { + /// Root-level cross-sign edges (§3.2), excluding self-pairs + /// (self-signing is not an edge, it is the primary certificate). + pub root_edges: BTreeSet, + /// Issuer-level direct cross-sign edges (§24.2), excluding the + /// primary same-algorithm signer. + pub issuer_edges: BTreeSet, +} + +impl GraphPolicy { + /// The spec default: §§3.2 + 24.2 matrices. Classical signers + /// certify all subjects; the ML-DSA signer certifies only the + /// ML-DSA subject. + pub fn spec_default() -> Self { + let classical = [ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::Rsa2048, + ]; + let all_subjects = [ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::Rsa2048, + AlgorithmId::MlDsa44, + ]; + let mut root_edges = BTreeSet::new(); + let mut issuer_edges = BTreeSet::new(); + for signer in classical { + for subject in all_subjects { + if signer != subject { + root_edges.insert((signer, subject)); + issuer_edges.insert((signer, subject)); + } + } + } + // The ML-DSA signer's only non-self edge would be to a + // classical subject — forbidden — so it contributes no edges + // at all. (Its self-pair is the primary certificate.) + GraphPolicy { + root_edges, + issuer_edges, + } + } + + /// May `signer` certify `subject` at the root level? Self-pairs + /// are always allowed (they are the primary certificate, not a + /// cross edge). + pub fn root_allows(&self, signer: AlgorithmId, subject: AlgorithmId) -> bool { + signer == subject || self.root_edges.contains(&(signer, subject)) + } + + /// May `signer` directly certify an issuer key of `subject` + /// algorithm? The primary same-algorithm signer always may. + pub fn issuer_allows(&self, signer: AlgorithmId, subject: AlgorithmId) -> bool { + signer == subject || self.issuer_edges.contains(&(signer, subject)) + } + + /// The non-self signers eligible to cross-certify a root key of + /// `subject` algorithm, in registry order. + pub fn root_signers_for(&self, subject: AlgorithmId) -> Vec { + self.root_edges + .iter() + .filter(|(_, s)| *s == subject) + .map(|(signer, _)| *signer) + .collect() + } + + /// The non-primary signers eligible to directly certify an issuer + /// key of `subject` algorithm, in registry order. + pub fn issuer_signers_for(&self, subject: AlgorithmId) -> Vec { + self.issuer_edges + .iter() + .filter(|(_, s)| *s == subject) + .map(|(signer, _)| *signer) + .collect() + } + + /// Expected root-level certificate count for a root set with the + /// given algorithms under `mode`: one self-signed per algorithm + /// plus one cross-certificate per realized edge whose signer and + /// subject are both present (§3.2 inventory: 4 + 9 = 13 for the + /// default set). + pub fn expected_root_certificates( + &self, + algorithms: &[AlgorithmId], + mode: CrossSigningMode, + ) -> usize { + let mut n = algorithms.len(); + if mode.root_level_active() { + n += self + .root_edges + .iter() + .filter(|(signer, subject)| { + algorithms.contains(signer) && algorithms.contains(subject) + }) + .count(); + } + n + } + + /// Expected issuer-variant count for one issuer key of `subject` + /// algorithm under `mode`, given which root algorithms exist: + /// the primary variant plus one per realized direct edge. + pub fn expected_issuer_variants( + &self, + subject: AlgorithmId, + root_algorithms: &[AlgorithmId], + mode: CrossSigningMode, + ) -> usize { + let mut n = 1; + if mode.issuer_level_active() { + n += self + .issuer_signers_for(subject) + .iter() + .filter(|signer| root_algorithms.contains(signer)) + .count(); + } + n + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::algorithm::DEFAULT_ALGORITHMS; + + #[test] + fn spec_inventory_counts() { + let g = GraphPolicy::spec_default(); + // §3.2: 4 self-signed + 9 cross = 13 root certificates. + assert_eq!( + g.expected_root_certificates(DEFAULT_ALGORITHMS, CrossSigningMode::Both), + 13 + ); + assert_eq!( + g.expected_root_certificates(DEFAULT_ALGORITHMS, CrossSigningMode::RootsOnly), + 13 + ); + assert_eq!( + g.expected_root_certificates(DEFAULT_ALGORITHMS, CrossSigningMode::None), + 4 + ); + // §24.2 per partition: classical issuer keys get 3 variants + // under `both` when counted per signer-root presence in the + // default root set (primary + 2 classical crosses... the + // ML-DSA root may not sign them), ML-DSA issuer keys get 4. + assert_eq!( + g.expected_issuer_variants(AlgorithmId::Ed25519, DEFAULT_ALGORITHMS, CrossSigningMode::Both), + 3 + ); + assert_eq!( + g.expected_issuer_variants(AlgorithmId::MlDsa44, DEFAULT_ALGORITHMS, CrossSigningMode::Both), + 4 + ); + assert_eq!( + g.expected_issuer_variants(AlgorithmId::MlDsa44, DEFAULT_ALGORITHMS, CrossSigningMode::RootsOnly), + 1 + ); + } + + #[test] + fn ml_dsa_never_signs_classical() { + let g = GraphPolicy::spec_default(); + for subject in [ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::Rsa2048, + ] { + assert!(!g.root_allows(AlgorithmId::MlDsa44, subject)); + assert!(!g.issuer_allows(AlgorithmId::MlDsa44, subject)); + } + // Classical signers may certify the ML-DSA subject. + assert!(g.root_allows(AlgorithmId::Ed25519, AlgorithmId::MlDsa44)); + assert!(g.issuer_allows(AlgorithmId::Rsa4096, AlgorithmId::MlDsa44)); + } + + #[test] + fn mode_parsing() { + assert_eq!( + CrossSigningMode::parse("both").unwrap(), + CrossSigningMode::Both + ); + assert!(CrossSigningMode::parse("everything").is_err()); + assert!(CrossSigningMode::Both.root_level_active()); + assert!(CrossSigningMode::Both.issuer_level_active()); + assert!(!CrossSigningMode::RootsOnly.issuer_level_active()); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/lib.rs b/pkgs/fleet/crates/fleet-cert/src/lib.rs new file mode 100644 index 0000000000..911c06bab2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/lib.rs @@ -0,0 +1,53 @@ +//! fleet-cert — the `fleet cert` domain (alias `fleet pki`): +//! PKI/X.509 roots, issuers, leaves, chains and bundles. +//! +//! Governing spec: `doc/2026-11-13T01-34-11Z_design_fleet_ca_credentials_secrets/ +//! sources/fleet_architecture_spec_v0_3.md` (§§3, 5.4, 6, 7, 13 +//! phases B–D, 24, 25, 26), tracked by developing-today/code#9157 +//! under the fleet CA program epic #9155. +//! +//! Library-first (spec §6.4): every CLI verb in [`cli`] is a thin +//! shell over the public API in this crate — +//! +//! - [`algorithm`] — the algorithm registry (§§3.1, 6.3, 24.1); +//! - [`timeparse`] — the §5.4 time grammar (RFC3339 + Gregorian +//! calendar durations); +//! - [`naming`] — generation/partition coordinates and slugs (§5.2); +//! - [`graph`] — the cross-signing graph as data/policy (§§3.2, 24.2), +//! never a hardcoded loop; +//! - [`profile`] — leaf profiles mirroring `pkgs/idp-pki`'s `idp-ca`; +//! - [`model`] — typed requests and the bundle manifest schema (§7.1); +//! - [`engine`] — key generation, issuance, chain building and +//! validation over rcgen + aws-lc-rs; +//! - [`bundle`] — bundle directories: manifest load/save, artifact +//! index, checksum verification. +//! +//! Safety rails baked into the API, not just the CLI: +//! - Root/issuer signing always requires an explicitly passed signer +//! source (a key directory argument). There is no ambient key +//! discovery anywhere in this crate (§24.3). +//! - Legacy algorithms are policy-gated for CA use (§24.1(1)). +//! - The cross-sign matrices forbid ML-DSA→classical edges; a +//! PQ-only trust selection is a verifier policy enforced by the +//! chain validator (§3.2). + +pub mod algorithm; +pub mod bundle; +pub mod chain; +pub mod cli; +pub mod engine; +pub mod error; +pub mod graph; +pub mod model; +pub mod naming; +pub mod profile; +pub mod timeparse; + +pub use error::{CertError, Result}; + +/// The CLI entry point the fleet multicall binary dispatches to: +/// `fleet cert ` (and `fleet pki `). Returns the +/// process exit code (0 ok · 2 usage · 1 failure). +pub fn run(args: &[String]) -> i32 { + cli::run(args) +} diff --git a/pkgs/fleet/crates/fleet-cert/src/model.rs b/pkgs/fleet/crates/fleet-cert/src/model.rs new file mode 100644 index 0000000000..96b59ffbdf --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/model.rs @@ -0,0 +1,295 @@ +//! Typed requests and the bundle manifest schema (spec §7.1). +//! +//! The CLI parses flags into these requests; the engine consumes +//! them. Nothing in the engine reads argv, the environment, or a +//! config file — in particular, **signer sources are explicit +//! request fields** (§24.3): an issuer or leaf creation request +//! cannot even be constructed without naming the directory that +//! holds the signing keys. + +use crate::algorithm::AlgorithmId; +use crate::graph::CrossSigningMode; +use crate::timeparse::Rfc3339; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// The manifest schema id written into every bundle (§7.1: +/// schema-versioned `manifest.json` is the canonical record). +pub const MANIFEST_SCHEMA: &str = "fleet-cert-manifest/v1"; + +/// An explicitly passed signer source (§24.3): the directory holding +/// a CA bundle's private keys (its `private/keys` directory, or an +/// external store directory named at creation time). Root/issuer +/// signing operations take this as a required argument — there is +/// no ambient key discovery anywhere in this crate. +#[derive(Debug, Clone)] +pub struct SignerSource { + pub key_dir: PathBuf, +} + +/// `cert root create` (§§6.2, 24.3). +#[derive(Debug, Clone)] +pub struct RootCreateRequest { + pub organization: String, + pub country: String, + pub algorithms: Vec, + pub generation: u32, + /// Partition label (`A`); a root set has one partition per + /// generation in this slice. + pub partition: String, + pub cross_signing: CrossSigningMode, + pub not_before: Rfc3339, + pub not_after: Rfc3339, + /// The §24.1(1) explicit opt-in for legacy-gated algorithms. + pub allow_legacy_root_strength: bool, + /// Where private keys go: `None` = the bundle's own + /// `private/keys`; `Some(dir)` = that external store directory + /// (recorded in the manifest as a location class, never synced). + pub private_store: Option, +} + +/// Issuer set purpose (§24.4): drives CN/OU derivation, EKU-less CA +/// profile, and (for web) optional permitted-DNS name constraints. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum IssuerPurpose { + General, + WebServer, +} + +impl IssuerPurpose { + pub fn parse(input: &str) -> crate::Result { + match input.trim().to_ascii_lowercase().as_str() { + "general" | "base" => Ok(IssuerPurpose::General), + "web" | "web-server" | "webserver" => Ok(IssuerPurpose::WebServer), + other => Err(crate::CertError::usage(format!( + "unknown issuer purpose '{other}' (general | web-server)" + ))), + } + } + pub fn as_str(&self) -> &'static str { + match self { + IssuerPurpose::General => "general", + IssuerPurpose::WebServer => "web-server", + } + } +} + +/// `cert issuer create` (§§6.2, 24.4, 24.5). +#[derive(Debug, Clone)] +pub struct IssuerCreateRequest { + /// The root bundle directory (public material + manifest). + pub root_bundle: PathBuf, + /// REQUIRED explicit signer source for the root keys (§24.3). + pub root_signer: SignerSource, + pub name: String, + pub purpose: IssuerPurpose, + pub ou: Option, + /// (algorithm, partition) key slots to create — resolved from + /// the `--algorithms` × `--partitions` grammar by the caller + /// ([`resolve_slots`]). + pub slots: Vec<(AlgorithmId, String)>, + pub cross_signing: CrossSigningMode, + pub not_before: Rfc3339, + pub not_after: Rfc3339, + pub allow_legacy_root_strength: bool, + /// Permitted DNS name constraints (web purpose, §24.4). + pub permitted_dns: Vec, + pub private_store: Option, +} + +/// `cert leaf issue` (§§6.2, 24.6). +#[derive(Debug, Clone)] +pub struct LeafIssueRequest { + /// The issuer bundle directory. + pub issuer_bundle: PathBuf, + /// REQUIRED explicit signer source for the issuer key (§24.3). + pub issuer_signer: SignerSource, + /// Leaf profile name (see [`crate::profile`]). + pub profile: String, + /// Delivery name (directory + manifest identity). + pub name: String, + pub common_name: Option, + pub dns_names: Vec, + /// Subject key algorithm; `None` = the profile's key algorithm. + pub key_algorithm: Option, + /// Which issuer key signs: (algorithm, partition). `None` = + /// (the leaf key algorithm if the profile's is a CA-supported + /// pairing, else the first slot), partition A. + pub issuer_algorithm: Option, + pub issuer_partition: Option, + pub not_before: Rfc3339, + pub not_after: Rfc3339, + pub private_store: Option, +} + +/// Resolve the `--algorithms` × `--partitions` grammar into key +/// slots (§24.4): +/// - partitions given → Cartesian product (the documented default: +/// `--algorithms ed25519,p256 --partitions A,B` gives every +/// algorithm both partitions); +/// - partitions omitted + a repeated algorithm in the list → the +/// repeats take successive partitions in input order +/// (`rsa,rsa,ed25519` → RSA A, RSA B, Ed25519 A); +/// - partitions omitted, no repeats → partition A for each. +pub fn resolve_slots( + algorithms: &[AlgorithmId], + partitions: Option<&[String]>, +) -> crate::Result> { + use std::collections::BTreeMap; + match partitions { + Some(parts) => { + let mut out = Vec::new(); + for algo in algorithms { + for part in parts { + let slot = (*algo, part.to_ascii_lowercase()); + if out.contains(&slot) { + return Err(crate::CertError::usage(format!( + "duplicate issuer slot {} partition {}", + algo.name(), + part + ))); + } + out.push(slot); + } + } + Ok(out) + } + None => { + let mut counts: BTreeMap = BTreeMap::new(); + let mut out = Vec::new(); + for algo in algorithms { + let idx = counts.entry(*algo).or_insert(0); + let part = crate::naming::partition_label(*idx); + *idx += 1; + out.push((*algo, part)); + } + Ok(out) + } + } +} + +/// The kind of a bundle (§7.1 `bundle_type`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum BundleType { + RootSet, + IssuerSet, + Leaf, +} + +impl BundleType { + pub fn as_str(&self) -> &'static str { + match self { + BundleType::RootSet => "root-set", + BundleType::IssuerSet => "issuer-set", + BundleType::Leaf => "leaf", + } + } +} + +/// One certificate in a bundle (§7.1 per-certificate record). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CertRecord { + /// `root` | `root-cross` | `issuer` | `leaf`. + pub role: String, + /// Subject key algorithm. + pub algorithm: AlgorithmId, + /// Signing key algorithm (`None` = self-signed). + pub signer_algorithm: Option, + /// Partition label (lowercase) of the subject key. + pub partition: String, + /// The variant a chain builder should prefer for this key. + #[serde(default)] + pub primary: bool, + pub subject_dn: String, + pub issuer_dn: String, + pub serial_hex: String, + pub ski_hex: String, + pub aki_hex: String, + pub fingerprint_sha256: String, + pub not_before: Rfc3339, + pub not_after: Rfc3339, + pub is_ca: bool, + pub path_len: Option, + /// Bundle-relative PEM path. + pub cert_path: String, + /// Bundle-relative PKCS#8 path when the key lives in the bundle; + /// `None` when the key lives in an external store. + pub key_path: Option, +} + +/// One file in a bundle's index (§7.1 file index with checksums). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FileRecord { + pub path: String, + pub kind: String, + pub sha256: String, + pub bytes: u64, + /// `public` | `private` (§7.1 visibility). + pub visibility: String, +} + +/// A reference to a parent bundle (§7.1 `parent_refs`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ParentRef { + pub bundle_type: BundleType, + pub bundle_id: String, + pub name: String, + /// SHA-256 fingerprints of the parent's anchor certificates. + pub anchor_fingerprints: Vec, +} + +/// The canonical bundle manifest (§7.1). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BundleManifest { + pub schema: String, + pub bundle_id: String, + pub bundle_type: BundleType, + pub bundle_version: u32, + pub name: String, + pub slug: String, + pub organization: String, + pub country: String, + pub purpose: Option, + pub generation: u32, + pub created_at: Rfc3339, + /// fleet-cert crate version that created the bundle. + pub engine_version: String, + pub parent: Option, + /// `bundle-private` | `external-store` (§7.1: the manifest + /// records the custody class, never a secret value). + pub key_location: String, + pub cross_signing: Option, + pub certificates: Vec, + pub files: Vec, + pub warnings: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slots_cartesian_and_zipped() { + let algos = [AlgorithmId::Ed25519, AlgorithmId::P256]; + let parts = vec!["a".to_string(), "b".to_string()]; + let slots = resolve_slots(&algos, Some(&parts)).unwrap(); + assert_eq!(slots.len(), 4); + // Zipped repeats: rsa,rsa,ed25519 → A, B, A (§24.4). + let algos = [ + AlgorithmId::Rsa4096, + AlgorithmId::Rsa4096, + AlgorithmId::Ed25519, + ]; + let slots = resolve_slots(&algos, None).unwrap(); + assert_eq!( + slots, + vec![ + (AlgorithmId::Rsa4096, "a".to_string()), + (AlgorithmId::Rsa4096, "b".to_string()), + (AlgorithmId::Ed25519, "a".to_string()), + ] + ); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/naming.rs b/pkgs/fleet/crates/fleet-cert/src/naming.rs new file mode 100644 index 0000000000..cf42f5b84a --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/naming.rs @@ -0,0 +1,193 @@ +//! Generation / partition naming and slugs (spec §§5.1, 5.2, 24.4). +//! +//! The structured form is authoritative — `{generation: 4, +//! partition: "b"}` — and the human/machine spellings derive from it: +//! machine id `g4b`, subject-CN tail `B G4` (the partition sits before +//! the generation, and the CN ends in `G`, §24.4). + +use crate::error::{CertError, Result}; +use serde::{Deserialize, Serialize}; + +/// A generation + partition coordinate. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GenerationPartition { + /// Generation number, >= 1 (`g1` is the initial generation). + pub generation: u32, + /// Partition label, lowercase in structured form: `a`..`z`, then + /// `aa`, `ab`, ... (§5.2: partitions are extensible past `z`). + pub partition: String, +} + +impl GenerationPartition { + pub fn new(generation: u32, partition_label: &str) -> Result { + if generation == 0 { + return Err(CertError::usage("generation must be >= 1")); + } + let p = partition_label.trim().to_ascii_lowercase(); + if p.is_empty() || !p.chars().all(|c| c.is_ascii_lowercase()) { + return Err(CertError::usage(format!( + "partition label '{partition_label}' must be letters (A, B, ..., AA)" + ))); + } + Ok(GenerationPartition { + generation, + partition: p, + }) + } + + /// The initial coordinate: generation 1, partition A. + pub fn initial() -> Self { + GenerationPartition { + generation: 1, + partition: "a".to_string(), + } + } + + /// Machine id: `g1a`, `g4b` (§5.2). + pub fn machine_id(&self) -> String { + format!("g{}{}", self.generation, self.partition) + } + + /// Subject-CN tail (§24.4): partition before generation, CN ends + /// in `G` — e.g. `A G1`. + pub fn cn_tail(&self) -> String { + format!("{} G{}", self.partition.to_ascii_uppercase(), self.generation) + } + + /// Parse a machine id like `g4b` (case-insensitive). + pub fn parse_machine_id(input: &str) -> Result { + let text = input.trim().to_ascii_lowercase(); + let digits: String = text + .strip_prefix('g') + .ok_or_else(|| CertError::usage(format!("generation id '{input}' must start with 'g'")))? + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + if digits.is_empty() { + return Err(CertError::usage(format!( + "generation id '{input}' has no generation number" + ))); + } + let partition = &text[1 + digits.len()..]; + let generation: u32 = digits + .parse() + .map_err(|_| CertError::usage(format!("generation id '{input}': bad number")))?; + GenerationPartition::new(generation, partition) + } +} + +/// Partition label for a zero-based index: 0→`a`, 25→`z`, 26→`aa`. +pub fn partition_label(index: usize) -> String { + let mut n = index + 1; + let mut out = String::new(); + while n > 0 { + n -= 1; + out.push((b'a' + (n % 26) as u8) as char); + n /= 26; + } + out.chars().rev().collect() +} + +/// Parse a comma-separated partition list (`A,B`) into coordinates at +/// one generation. Labels are case-insensitive; duplicates are an +/// error (two partitions with one label would collide). +pub fn parse_partitions(input: &str, generation: u32) -> Result> { + let mut out = Vec::new(); + for part in input.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + let gp = GenerationPartition::new(generation, part)?; + if out.contains(&gp) { + return Err(CertError::usage(format!( + "duplicate partition '{}'", + part.to_ascii_uppercase() + ))); + } + out.push(gp); + } + if out.is_empty() { + return Err(CertError::usage("empty partition list")); + } + Ok(out) +} + +/// Canonical slug for a display name (§5.2): lowercase ASCII, +/// hyphenated, punctuation stripped, length-limited. The original +/// display text is always retained separately in metadata — a slug is +/// never the identity, only a path component. +pub fn slugify(name: &str) -> Result { + let mut out = String::new(); + let mut last_dash = true; // suppresses a leading dash + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + out.push(ch.to_ascii_lowercase()); + last_dash = false; + } else if !last_dash { + out.push('-'); + last_dash = true; + } + } + while out.ends_with('-') { + out.pop(); + } + if out.is_empty() { + return Err(CertError::usage(format!( + "name '{name}' produces an empty slug; give a name with letters or digits" + ))); + } + if out.len() > 64 { + out.truncate(64); + while out.ends_with('-') { + out.pop(); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn machine_id_round_trip() { + let gp = GenerationPartition::parse_machine_id("g4b").unwrap(); + assert_eq!(gp.generation, 4); + assert_eq!(gp.partition, "b"); + assert_eq!(gp.machine_id(), "g4b"); + assert_eq!(gp.cn_tail(), "B G4"); + assert_eq!( + GenerationPartition::initial().machine_id(), + "g1a" + ); + assert!(GenerationPartition::parse_machine_id("4b").is_err()); + assert!(GenerationPartition::parse_machine_id("g0a").is_err()); + assert!(GenerationPartition::parse_machine_id("g1").is_err()); + } + + #[test] + fn partition_labels_extend_past_z() { + assert_eq!(partition_label(0), "a"); + assert_eq!(partition_label(25), "z"); + assert_eq!(partition_label(26), "aa"); + assert_eq!(partition_label(27), "ab"); + } + + #[test] + fn partition_lists() { + let ps = parse_partitions("A,B", 1).unwrap(); + assert_eq!(ps.len(), 2); + assert_eq!(ps[1].machine_id(), "g1b"); + assert!(parse_partitions("A,A", 1).is_err()); + assert!(parse_partitions("", 1).is_err()); + } + + #[test] + fn slugs() { + assert_eq!(slugify("Internal Web").unwrap(), "internal-web"); + assert_eq!(slugify("developing.today LLC").unwrap(), "developing-today-llc"); + assert_eq!(slugify(" Base ").unwrap(), "base"); + assert!(slugify("!!!").is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/profile.rs b/pkgs/fleet/crates/fleet-cert/src/profile.rs new file mode 100644 index 0000000000..d2e36f8dad --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/profile.rs @@ -0,0 +1,134 @@ +//! Leaf profiles, mirroring `pkgs/idp-pki`'s `idp-ca` (the interim +//! IdP CA tool) as the behavioural reference: +//! +//! | profile | key | key usage | EKU | default validity | +//! |---------------|------------|----------------------------------|------------|------------------| +//! | `server` | EC P-256 | digitalSignature | serverAuth | 730 days | +//! | `client` | EC P-256 | digitalSignature | clientAuth | 730 days | +//! | `saml-signing`| RSA-2048 | digitalSignature, nonRepudiation (contentCommitment) | — | 1095 days | +//! | `oidc-signing`| RSA-2048 | digitalSignature, nonRepudiation (contentCommitment) | — | 1095 days | +//! +//! All leaves carry `basicConstraints CA:false` (critical) and +//! SKI/AKI, as idp-ca's extension files do. The `server` profile +//! defaults its SAN to `DNS:` when no SAN is supplied, again as +//! idp-ca does. +//! +//! Validity note: the per-profile defaults above are idp-ca's. The +//! spec's generic unprofiled leaf default is 90 days (§5.4); a +//! profile's own default governs when a profile is named, and +//! `--valid-for`/`--not-after` always override. + +use crate::algorithm::AlgorithmId; +use crate::error::{CertError, Result}; +use crate::timeparse::CalendarDuration; + +/// A leaf certificate profile. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LeafProfile { + pub name: &'static str, + /// The subject key algorithm the profile generates by default. + pub key_algorithm: AlgorithmId, + /// Key usage bits, as rcgen names. + pub key_usages: &'static [rcgen::KeyUsagePurpose], + /// Extended key usages (empty = no EKU extension, as in idp-ca's + /// signing profiles). + pub extended_key_usages: &'static [rcgen::ExtendedKeyUsagePurpose], + /// Default validity when the caller gives no time flags. + pub default_validity: CalendarDuration, + /// idp-ca behaviour: a `server` leaf with no SANs gets + /// `DNS:`. + pub san_defaults_to_cn: bool, + pub notes: &'static str, +} + +const PROFILES: &[LeafProfile] = &[ + LeafProfile { + name: "server", + key_algorithm: AlgorithmId::P256, + key_usages: &[rcgen::KeyUsagePurpose::DigitalSignature], + extended_key_usages: &[rcgen::ExtendedKeyUsagePurpose::ServerAuth], + default_validity: CalendarDuration::days(730), + san_defaults_to_cn: true, + notes: "TLS server leaf (idp-ca `server`): P-256, serverAuth, SAN defaults to DNS:.", + }, + LeafProfile { + name: "client", + key_algorithm: AlgorithmId::P256, + key_usages: &[rcgen::KeyUsagePurpose::DigitalSignature], + extended_key_usages: &[rcgen::ExtendedKeyUsagePurpose::ClientAuth], + default_validity: CalendarDuration::days(730), + san_defaults_to_cn: false, + notes: "TLS client leaf (idp-ca `client`): P-256, clientAuth.", + }, + LeafProfile { + name: "saml-signing", + key_algorithm: AlgorithmId::Rsa2048, + key_usages: &[ + rcgen::KeyUsagePurpose::DigitalSignature, + rcgen::KeyUsagePurpose::ContentCommitment, + ], + extended_key_usages: &[], + default_validity: CalendarDuration::days(1095), + san_defaults_to_cn: false, + notes: "SAML signing leaf (idp-ca `saml-signing`): RSA-2048, digitalSignature + nonRepudiation (contentCommitment), no EKU.", + }, + LeafProfile { + name: "oidc-signing", + key_algorithm: AlgorithmId::Rsa2048, + key_usages: &[ + rcgen::KeyUsagePurpose::DigitalSignature, + rcgen::KeyUsagePurpose::ContentCommitment, + ], + extended_key_usages: &[], + default_validity: CalendarDuration::days(1095), + san_defaults_to_cn: false, + notes: "OIDC signing leaf (idp-ca `oidc-signing`): RSA-2048, digitalSignature + nonRepudiation (contentCommitment), no EKU.", + }, +]; + +/// All leaf profiles, in registry order. +pub fn leaf_profiles() -> &'static [LeafProfile] { + PROFILES +} + +/// Look a profile up by name. +pub fn leaf_profile(name: &str) -> Result<&'static LeafProfile> { + PROFILES + .iter() + .find(|p| p.name == name.trim().to_ascii_lowercase()) + .ok_or_else(|| { + CertError::usage(format!( + "unknown leaf profile '{name}' (known: {})", + PROFILES + .iter() + .map(|p| p.name) + .collect::>() + .join(", ") + )) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profiles_mirror_idp_ca() { + let server = leaf_profile("server").unwrap(); + assert_eq!(server.key_algorithm, AlgorithmId::P256); + assert_eq!(server.default_validity.days, 730); + assert!(server.san_defaults_to_cn); + let saml = leaf_profile("saml-signing").unwrap(); + assert_eq!(saml.key_algorithm, AlgorithmId::Rsa2048); + assert_eq!(saml.default_validity.days, 1095); + assert!(saml.extended_key_usages.is_empty()); + assert_eq!( + saml.key_usages, + [ + rcgen::KeyUsagePurpose::DigitalSignature, + rcgen::KeyUsagePurpose::ContentCommitment + ] + ); + assert!(leaf_profile("web").is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/src/timeparse.rs b/pkgs/fleet/crates/fleet-cert/src/timeparse.rs new file mode 100644 index 0000000000..cdd5c50b1c --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/src/timeparse.rs @@ -0,0 +1,363 @@ +//! The §5.4 time grammar: RFC3339 timestamps and calendar durations. +//! +//! Rules that matter (spec §5.4): +//! - Lifetimes are **Gregorian calendar arithmetic** from the start +//! date — `20y` is twenty calendar years, never a fixed count of +//! seconds. Leap-day behaviour is explicit: Feb 29 + 1y lands on +//! Feb 28 of the following year (clamp, never overflow into March). +//! - Exact instants serialize as precise RFC3339 UTC +//! (`YYYY-MM-DDTHH:MM:SSZ`). +//! - `--not-after` (exact) and `--valid-for` (duration) are mutually +//! exclusive; the resolved pair is always reported back as explicit +//! RFC3339 timestamps in manifests. + +use crate::error::{CertError, Result}; +use serde::{Deserialize, Serialize}; +use std::fmt; +use time::format_description::well_known::Rfc3339 as Rfc3339Format; +use time::{Date, Duration as TimeDuration, Month, OffsetDateTime, Time}; + +/// An instant, serialized canonically as RFC3339 UTC seconds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct Rfc3339(pub OffsetDateTime); + +impl Rfc3339 { + pub fn now() -> Self { + Rfc3339(OffsetDateTime::now_utc()) + } + + pub fn parse(input: &str) -> Result { + OffsetDateTime::parse(input.trim(), &Rfc3339Format) + .map(Rfc3339) + .map_err(|e| CertError::usage(format!("invalid RFC3339 timestamp '{input}': {e}"))) + } + + pub fn to_string_canonical(&self) -> String { + // OffsetDateTime::format with the well-known Rfc3339 description + // emits e.g. 2026-11-23T14:00:00Z for UTC values. + self.0 + .format(&Rfc3339Format) + .unwrap_or_else(|_| "invalid".to_string()) + } +} + +impl fmt::Display for Rfc3339 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_string_canonical()) + } +} + +impl Serialize for Rfc3339 { + fn serialize(&self, s: S) -> std::result::Result { + s.serialize_str(&self.to_string_canonical()) + } +} + +impl<'de> Deserialize<'de> for Rfc3339 { + fn deserialize>(d: D) -> std::result::Result { + let text = String::deserialize(d)?; + Rfc3339::parse(&text).map_err(serde::de::Error::custom) + } +} + +/// A calendar-aware duration: year/month parts are Gregorian calendar +/// arithmetic; the rest are exact clock quantities (spec §5.4). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CalendarDuration { + pub years: i64, + pub months: i64, + pub weeks: i64, + pub days: i64, + pub hours: i64, + pub minutes: i64, + pub seconds: i64, +} + +impl CalendarDuration { + pub const fn years(n: i64) -> Self { + CalendarDuration { + years: n, + months: 0, + weeks: 0, + days: 0, + hours: 0, + minutes: 0, + seconds: 0, + } + } + pub const fn days(n: i64) -> Self { + CalendarDuration { + years: 0, + months: 0, + weeks: 0, + days: n, + hours: 0, + minutes: 0, + seconds: 0, + } + } + + pub fn is_zero(&self) -> bool { + *self == CalendarDuration::default() + } + + /// Parse the duration grammar: a sequence of `` + /// terms, separated by spaces or commas — `20y`, `1y`, + /// `15 years 7 days`, `90d`, `15m`, `15 minutes`, `2w`, `12h`. + /// A bare number or an unknown unit is an error, never a guess + /// (spec §5.4: never use an ambiguous conversion silently). + /// `m` means minutes (spec §24.1(2)'s "15 minutes" short-lived + /// identities); months are `mo`/`month`/`months`. + pub fn parse(input: &str) -> Result { + let text = input.trim().to_ascii_lowercase(); + if text.is_empty() { + return Err(CertError::usage("empty duration")); + } + let mut out = CalendarDuration::default(); + let mut rest = text.as_str(); + let mut terms = 0usize; + while !rest.is_empty() { + rest = rest.trim_start_matches([' ', ',', '+']); + if rest.is_empty() { + break; + } + let num_end = rest + .find(|c: char| !c.is_ascii_digit()) + .ok_or_else(|| { + CertError::usage(format!( + "duration '{input}': bare number without a unit is ambiguous; \ + add a unit (y, mo, w, d, h, m, s)" + )) + })?; + if num_end == 0 { + return Err(CertError::usage(format!( + "duration '{input}': expected a number at '{rest}'" + ))); + } + let n: i64 = rest[..num_end].parse().map_err(|_| { + CertError::usage(format!("duration '{input}': bad number in '{rest}'")) + })?; + rest = rest[num_end..].trim_start(); + let unit_end = rest + .find(|c: char| !c.is_ascii_alphabetic()) + .unwrap_or(rest.len()); + if unit_end == 0 { + return Err(CertError::usage(format!( + "duration '{input}': missing unit after {n}" + ))); + } + let unit = &rest[..unit_end]; + rest = &rest[unit_end..]; + match unit { + "y" | "yr" | "yrs" | "year" | "years" => out.years += n, + "mo" | "month" | "months" => out.months += n, + "w" | "week" | "weeks" => out.weeks += n, + "d" | "day" | "days" => out.days += n, + "h" | "hr" | "hour" | "hours" => out.hours += n, + "m" | "min" | "mins" | "minute" | "minutes" => out.minutes += n, + "s" | "sec" | "secs" | "second" | "seconds" => out.seconds += n, + other => { + return Err(CertError::usage(format!( + "duration '{input}': unknown unit '{other}' \ + (known: y, mo, w, d, h, m, s — spelled-out forms accepted)" + ))) + } + } + terms += 1; + } + if terms == 0 || out.is_zero() { + return Err(CertError::usage(format!( + "duration '{input}': no positive terms" + ))); + } + if out.years < 0 + || out.months < 0 + || out.weeks < 0 + || out.days < 0 + || out.hours < 0 + || out.minutes < 0 + || out.seconds < 0 + { + return Err(CertError::usage(format!( + "duration '{input}': negative terms are not allowed" + ))); + } + Ok(out) + } + + /// Add this duration to an instant using Gregorian calendar + /// arithmetic for the year/month parts (clamping the day of month + /// when the target month is shorter — Feb 29 + 1y = Feb 28), then + /// exact arithmetic for weeks/days and clock parts. The + /// time-of-day is preserved across the calendar parts. + pub fn add_to(&self, start: Rfc3339) -> Result { + let dt = start.0; + let date = dt.date(); + let time_of_day: Time = dt.time(); + + // Calendar years, then months, with day clamping. + let mut year = date.year() as i64 + self.years; + let mut month_idx = (date.month() as i64 - 1) + self.months; + year += month_idx.div_euclid(12); + month_idx = month_idx.rem_euclid(12); + let month_num = (month_idx + 1) as u8; + let month = Month::try_from(month_num) + .map_err(|_| CertError::engine("month arithmetic overflow"))?; + let year_i32 = i32::try_from(year) + .map_err(|_| CertError::engine("year arithmetic overflow"))?; + let max_day = days_in_month(year_i32, month); + let day = date.day().min(max_day); + let new_date = Date::from_calendar_date(year_i32, month, day) + .map_err(|e| CertError::engine(format!("date arithmetic failed: {e}")))?; + let mut out = OffsetDateTime::new_utc(new_date, time_of_day); + + let exact = TimeDuration::weeks(self.weeks) + + TimeDuration::days(self.days) + + TimeDuration::hours(self.hours) + + TimeDuration::minutes(self.minutes) + + TimeDuration::seconds(self.seconds); + out += exact; + Ok(Rfc3339(out)) + } +} + +fn days_in_month(year: i32, month: Month) -> u8 { + match month { + Month::January + | Month::March + | Month::May + | Month::July + | Month::August + | Month::October + | Month::December => 31, + Month::April | Month::June | Month::September | Month::November => 30, + Month::February => { + if time::util::is_leap_year(year) { + 29 + } else { + 28 + } + } + } +} + +/// Default lifetimes (spec §5.4 / §24.1(2)). +pub const ROOT_DEFAULT_LIFETIME_YEARS: i64 = 20; +pub const ISSUER_DEFAULT_LIFETIME_YEARS: i64 = 5; +pub const LEAF_DEFAULT_LIFETIME_DAYS: i64 = 90; + +/// Resolve a validity window from the flag grammar: `--not-before` +/// (default: now), then exactly one of `--not-after` (exact) or +/// `--valid-for` (duration from not-before), else the caller's +/// default lifetime. Both given is a usage error (spec §6.3 mutual +/// exclusion). +pub fn resolve_validity( + not_before: Option, + valid_for: Option, + not_after: Option, + default_lifetime: CalendarDuration, +) -> Result<(Rfc3339, Rfc3339)> { + if valid_for.is_some() && not_after.is_some() { + return Err(CertError::usage( + "--valid-for and --not-after are mutually exclusive (spec §6.3)", + )); + } + let nb = not_before.unwrap_or_else(Rfc3339::now); + let na = match (valid_for, not_after) { + (_, Some(exact)) => exact, + (Some(dur), None) => dur.add_to(nb)?, + (None, None) => default_lifetime.add_to(nb)?, + }; + if na <= nb { + return Err(CertError::usage(format!( + "not-after ({na}) must be strictly after not-before ({nb})" + ))); + } + Ok((nb, na)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ts(s: &str) -> Rfc3339 { + Rfc3339::parse(s).unwrap() + } + + #[test] + fn grammar_terms() { + assert_eq!(CalendarDuration::parse("20y").unwrap().years, 20); + assert_eq!(CalendarDuration::parse("90d").unwrap().days, 90); + assert_eq!(CalendarDuration::parse("15m").unwrap().minutes, 15); + let d = CalendarDuration::parse("15 years 7 days").unwrap(); + assert_eq!((d.years, d.days), (15, 7)); + let d = CalendarDuration::parse("1y 6mo").unwrap(); + assert_eq!((d.years, d.months), (1, 6)); + assert!(CalendarDuration::parse("20").is_err(), "bare number rejected"); + assert!(CalendarDuration::parse("3 fortnights").is_err()); + assert!(CalendarDuration::parse("").is_err()); + assert!(CalendarDuration::parse("0d").is_err()); + } + + #[test] + fn gregorian_year_arithmetic_and_leap_clamp() { + // 20 calendar years from a fixed start. + let end = CalendarDuration::years(20) + .add_to(ts("2026-07-07T12:00:00Z")) + .unwrap(); + assert_eq!(end.to_string_canonical(), "2046-07-07T12:00:00Z"); + // Leap day + 1y clamps to Feb 28, never Mar 1. + let end = CalendarDuration::years(1) + .add_to(ts("2024-02-29T00:00:00Z")) + .unwrap(); + assert_eq!(end.to_string_canonical(), "2025-02-28T00:00:00Z"); + // Leap day + 4y lands back on Feb 29. + let end = CalendarDuration::years(4) + .add_to(ts("2024-02-29T00:00:00Z")) + .unwrap(); + assert_eq!(end.to_string_canonical(), "2028-02-29T00:00:00Z"); + // Month arithmetic clamps too: Jan 31 + 1mo = Feb 28/29. + let end = CalendarDuration::parse("1mo") + .unwrap() + .add_to(ts("2025-01-31T00:00:00Z")) + .unwrap(); + assert_eq!(end.to_string_canonical(), "2025-02-28T00:00:00Z"); + // Mixed calendar + exact parts. + let end = CalendarDuration::parse("15 years 7 days") + .unwrap() + .add_to(ts("2026-07-07T12:00:00Z")) + .unwrap(); + assert_eq!(end.to_string_canonical(), "2041-07-14T12:00:00Z"); + } + + #[test] + fn rfc3339_round_trip() { + let t = ts("2050-07-07T12:00:00Z"); + assert_eq!(t.to_string_canonical(), "2050-07-07T12:00:00Z"); + assert!(Rfc3339::parse("2050-07-07").is_err()); + assert!(Rfc3339::parse("not a date").is_err()); + } + + #[test] + fn validity_resolution_rules() { + let nb = ts("2026-01-01T00:00:00Z"); + // Default lifetime applies. + let (b, a) = resolve_validity(Some(nb), None, None, CalendarDuration::years(20)).unwrap(); + assert_eq!(a.to_string_canonical(), "2046-01-01T00:00:00Z"); + assert_eq!(b, nb); + // Exact not-after wins; both flags together are an error. + let exact = ts("2032-07-07T12:00:00Z"); + let (_, a) = resolve_validity(Some(nb), None, Some(exact), CalendarDuration::years(5)) + .unwrap(); + assert_eq!(a, exact); + assert!(resolve_validity( + Some(nb), + Some(CalendarDuration::days(90)), + Some(exact), + CalendarDuration::years(5) + ) + .is_err()); + // not-after <= not-before is an error. + assert!(resolve_validity(Some(nb), None, Some(nb), CalendarDuration::years(5)).is_err()); + } +} diff --git a/pkgs/fleet/crates/fleet-cert/tests/hierarchy.rs b/pkgs/fleet/crates/fleet-cert/tests/hierarchy.rs new file mode 100644 index 0000000000..91644de437 --- /dev/null +++ b/pkgs/fleet/crates/fleet-cert/tests/hierarchy.rs @@ -0,0 +1,501 @@ +//! Integration tests for the fleet-cert Phase 1 slice (#9157). +//! +//! Every test names its oracle — the independent source of truth its +//! assertions are checked against: +//! - the spec's own inventory arithmetic (§§3.2, 24.2), +//! - the crate's chain validator (aws-lc-rs signature checks), +//! - the system `openssl` binary as a fully independent validator +//! (skipped only when openssl is absent from the test host), +//! - the manifest checksum index (§7.1). + +use fleet_cert::algorithm::AlgorithmId; +use fleet_cert::bundle::load_bundle; +use fleet_cert::chain::TrustSelection; +use fleet_cert::engine; +use fleet_cert::graph::CrossSigningMode; +use fleet_cert::model::{ + IssuerCreateRequest, IssuerPurpose, LeafIssueRequest, RootCreateRequest, SignerSource, +}; +use fleet_cert::timeparse::{CalendarDuration, Rfc3339}; +use std::path::{Path, PathBuf}; + +fn ts(s: &str) -> Rfc3339 { + Rfc3339::parse(s).unwrap() +} + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = std::env::temp_dir().join(format!( + "fleet-cert-test-{tag}-{}-{nanos}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +const NB: &str = "2026-01-01T00:00:00Z"; +const AT: &str = "2026-06-01T00:00:00Z"; + +fn root_request(algorithms: Vec) -> RootCreateRequest { + RootCreateRequest { + organization: "Test Org LLC".into(), + country: "US".into(), + algorithms, + generation: 1, + partition: "A".into(), + cross_signing: CrossSigningMode::Both, + not_before: ts(NB), + not_after: ts("2046-01-01T00:00:00Z"), + allow_legacy_root_strength: false, + private_store: None, + } +} + +fn issuer_request(root: &Path, slots: Vec<(AlgorithmId, String)>) -> IssuerCreateRequest { + IssuerCreateRequest { + root_bundle: root.to_path_buf(), + root_signer: SignerSource { + key_dir: root.join("private/keys"), + }, + name: "Base".into(), + purpose: IssuerPurpose::General, + ou: None, + slots, + cross_signing: CrossSigningMode::Both, + not_before: ts(NB), + not_after: ts("2031-01-01T00:00:00Z"), + allow_legacy_root_strength: false, + permitted_dns: vec![], + private_store: None, + } +} + +fn leaf_request( + issuer: &Path, + profile: &str, + name: &str, + key_algorithm: Option, + issuer_algorithm: Option, + valid_for: CalendarDuration, +) -> LeafIssueRequest { + LeafIssueRequest { + issuer_bundle: issuer.to_path_buf(), + issuer_signer: SignerSource { + key_dir: issuer.join("private/keys"), + }, + profile: profile.into(), + name: name.into(), + common_name: None, + dns_names: vec!["www.example.test".into()], + key_algorithm, + issuer_algorithm, + issuer_partition: None, + not_before: ts(NB), + not_after: valid_for.add_to(ts(NB)).unwrap(), + private_store: None, + } +} + +/// Build a root set + Base issuer set (A,B) in `tmp`; returns +/// (root_dir, issuer_dir). Oracle for counts: §§3.2/24.2 inventory. +fn build_hierarchy(tmp: &TempDir, algorithms: Vec) -> (PathBuf, PathBuf) { + let root_dir = tmp.path().join("roots"); + let manifest = engine::create_root_set(&root_request(algorithms.clone()), &root_dir).unwrap(); + let expected_roots = + fleet_cert::graph::GraphPolicy::spec_default() + .expected_root_certificates(&algorithms, CrossSigningMode::Both); + assert_eq!( + manifest.certificates.len(), + expected_roots, + "root inventory must match the §3.2 policy arithmetic" + ); + let slots: Vec<(AlgorithmId, String)> = algorithms + .iter() + .flat_map(|a| [(a.clone(), "a".to_string()), (a.clone(), "b".to_string())]) + .collect(); + let issuer_dir = tmp.path().join("base"); + let im = engine::create_issuer_set(&issuer_request(&root_dir, slots), &issuer_dir).unwrap(); + // §24.2: per partition, classical keys carry 3 variants and the + // ML-DSA key 4, scaled by which roots exist. + let graph = fleet_cert::graph::GraphPolicy::spec_default(); + let expected_variants: usize = algorithms + .iter() + .map(|a| graph.expected_issuer_variants(*a, &algorithms, CrossSigningMode::Both) * 2) + .sum(); + assert_eq!( + im.certificates.len(), + expected_variants, + "issuer inventory must match the §24.2 policy arithmetic" + ); + (root_dir, issuer_dir) +} + +#[test] +fn full_synthetic_hierarchy_validates() { + // Oracle: the spec inventory arithmetic (§§3.2/24.2) + the + // crate validator's per-link signature checks. + let tmp = TempDir::new("full"); + let (root_dir, issuer_dir) = build_hierarchy( + &tmp, + vec![ + AlgorithmId::Ed25519, + AlgorithmId::P256, + AlgorithmId::Rsa4096, + AlgorithmId::MlDsa44, + ], + ); + // Root bundle self-validation: every signature + inventory. + let checks = engine::validate_root_bundle(&root_dir).unwrap(); + assert!( + checks.iter().all(|c| c.ok), + "root validation failed: {:?}", + checks.iter().filter(|c| !c.ok).collect::>() + ); + // §3.2 exact count for the default set under `both`. + let root_bundle = load_bundle(&root_dir).unwrap(); + assert_eq!(root_bundle.manifest.certificates.len(), 13); + let issuer_bundle = load_bundle(&issuer_dir).unwrap(); + assert_eq!(issuer_bundle.manifest.certificates.len(), 26); + // Distinct issuer keys: 8 key files for 8 slots. + let mut key_paths: Vec<&str> = issuer_bundle + .manifest + .certificates + .iter() + .filter_map(|r| r.key_path.as_deref()) + .collect(); + key_paths.sort(); + key_paths.dedup(); + assert_eq!(key_paths.len(), 8, "A/B slots must be independent keys"); + + // One leaf per idp-ca profile; every chain validates. + let root_b = load_bundle(&root_dir).unwrap(); + let issuer_b = load_bundle(&issuer_dir).unwrap(); + for (profile_name, _) in [ + ("server", ()), + ("client", ()), + ("saml-signing", ()), + ("oidc-signing", ()), + ] { + let leaf_dir = tmp.path().join(format!("leaf-{profile_name}")); + let req = leaf_request( + &issuer_dir, + profile_name, + &format!("leaf-{profile_name}"), + None, + None, + CalendarDuration::days(365), + ); + engine::issue_leaf(&req, &leaf_dir).unwrap(); + let leaf_b = load_bundle(&leaf_dir).unwrap(); + let report = engine::validate_leaf( + &leaf_b, + &[&issuer_b, &root_b], + TrustSelection::All, + ts(AT), + ) + .unwrap(); + assert!( + report.valid, + "{profile_name} chain invalid: {:?}", + report.checks.iter().filter(|c| !c.ok).collect::>() + ); + assert_eq!(report.path.len(), 3, "leaf → issuer → root"); + } +} + +#[test] +fn pq_policy_negative_and_positive() { + // Oracle: §3.2's verifier-policy rule — under a PQ-only trust + // selection, a classical path must be rejected even though + // classical cross-certificates over the ML-DSA key exist, and + // the all-ML-DSA path must be accepted. + let tmp = TempDir::new("pq"); + let (root_dir, issuer_dir) = build_hierarchy( + &tmp, + vec![AlgorithmId::Ed25519, AlgorithmId::P256, AlgorithmId::MlDsa44], + ); + let root_b = load_bundle(&root_dir).unwrap(); + let issuer_b = load_bundle(&issuer_dir).unwrap(); + + // Classical leaf (profile default P-256 key + issuer). + let leaf_dir = tmp.path().join("leaf-classical"); + engine::issue_leaf( + &leaf_request(&issuer_dir, "server", "classical", None, None, CalendarDuration::days(90)), + &leaf_dir, + ) + .unwrap(); + let leaf_b = load_bundle(&leaf_dir).unwrap(); + let report = engine::validate_leaf( + &leaf_b, + &[&issuer_b, &root_b], + TrustSelection::Pq, + ts("2026-02-01T00:00:00Z"), + ) + .unwrap(); + assert!( + !report.valid, + "classical leaf must be rejected under PQ-only trust" + ); + assert!( + report + .checks + .iter() + .any(|c| c.name == "path-builds" && !c.ok), + "the rejection must be the missing PQ path, not a side effect: {:?}", + report.checks + ); + + // ML-DSA leaf under the ML-DSA issuer partition. + let pq_dir = tmp.path().join("leaf-pq"); + engine::issue_leaf( + &leaf_request( + &issuer_dir, + "server", + "pq", + Some(AlgorithmId::MlDsa44), + Some(AlgorithmId::MlDsa44), + CalendarDuration::days(90), + ), + &pq_dir, + ) + .unwrap(); + let pq_b = load_bundle(&pq_dir).unwrap(); + let report = engine::validate_leaf( + &pq_b, + &[&issuer_b, &root_b], + TrustSelection::Pq, + ts("2026-02-01T00:00:00Z"), + ) + .unwrap(); + assert!( + report.valid, + "all-ML-DSA path must validate under PQ trust: {:?}", + report.checks.iter().filter(|c| !c.ok).collect::>() + ); + assert!(report + .checks + .iter() + .any(|c| c.name == "pq-only-path" && c.ok)); + // And the same leaf is fine under the all-roots selection. + let report = engine::validate_leaf( + &pq_b, + &[&issuer_b, &root_b], + TrustSelection::All, + ts("2026-02-01T00:00:00Z"), + ) + .unwrap(); + assert!(report.valid); +} + +#[test] +fn cross_signed_path_survives_primary_root_removal() { + // Oracle: path building must find the cross-signed variant — + // with the P-256 root removed from the pool, a P-256 issuer's + // leaf still chains to a classical cross-signing root. + let tmp = TempDir::new("cross"); + let (root_dir, issuer_dir) = build_hierarchy( + &tmp, + vec![AlgorithmId::Ed25519, AlgorithmId::P256, AlgorithmId::MlDsa44], + ); + let leaf_dir = tmp.path().join("leaf"); + engine::issue_leaf( + &leaf_request(&issuer_dir, "server", "x", None, None, CalendarDuration::days(90)), + &leaf_dir, + ) + .unwrap(); + let leaf_b = load_bundle(&leaf_dir).unwrap(); + let issuer_b = load_bundle(&issuer_dir).unwrap(); + let root_b = load_bundle(&root_dir).unwrap(); + let mut pool = engine::collect_pool(&[&issuer_b, &root_b]).unwrap(); + // Remove the P-256 self-signed root from the pool. + pool.retain(|c| { + !(c.subject_algorithm == Some(AlgorithmId::P256) + && c.subject_dn.contains("Root") + && c.issuer_dn == c.subject_dn) + }); + let leaf_record = &leaf_b.manifest.certificates[0]; + let pem = std::fs::read(leaf_dir.join(&leaf_record.cert_path)).unwrap(); + let blocks = fleet_cert::bundle::pem_decode_all(std::str::from_utf8(&pem).unwrap()).unwrap(); + let leaf = fleet_cert::chain::parse_cert(&blocks[0].1).unwrap(); + let report = fleet_cert::chain::validate_chain( + &leaf, + &pool, + TrustSelection::All, + ts("2026-02-01T00:00:00Z"), + ); + assert!( + report.valid, + "cross-signed path must validate without the primary root: {:?}", + report.checks.iter().filter(|c| !c.ok).collect::>() + ); + let anchor = report.path.last().unwrap(); + assert!( + anchor.contains("Ed25519") || anchor.contains("ML-DSA"), + "anchor should be a cross-signing root, got {anchor}" + ); +} + +#[test] +fn openssl_independent_validation() { + // Oracle: the system openssl binary — a fully independent + // implementation (§11.2). Skipped only when openssl is absent. + if std::process::Command::new("openssl") + .arg("version") + .output() + .is_err() + { + eprintln!("openssl not available; skipping independent validation"); + return; + } + let tmp = TempDir::new("openssl"); + let (root_dir, issuer_dir) = build_hierarchy( + &tmp, + vec![AlgorithmId::Ed25519, AlgorithmId::P256, AlgorithmId::MlDsa44], + ); + let verify = |cafile: &Path, untrusted: &Path, leaf: &Path| -> bool { + std::process::Command::new("openssl") + .args([ + "verify", + "-CAfile", + cafile.to_str().unwrap(), + "-untrusted", + untrusted.to_str().unwrap(), + leaf.to_str().unwrap(), + ]) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) + }; + // Classical leaf against roots-all via its primary issuer. + let leaf_dir = tmp.path().join("leaf"); + engine::issue_leaf( + &leaf_request(&issuer_dir, "server", "ossl", None, None, CalendarDuration::years(3)), + &leaf_dir, + ) + .unwrap(); + assert!(verify( + &root_dir.join("public/bundles/roots-all.pem"), + &issuer_dir.join("public/certs/p256/a/signed-by-p256.crt.pem"), + &leaf_dir.join("leaf.crt.pem"), + )); + // ML-DSA leaf against roots-pq via the ML-DSA primary issuer. + let pq_dir = tmp.path().join("leaf-pq"); + engine::issue_leaf( + &leaf_request( + &issuer_dir, + "server", + "ossl-pq", + Some(AlgorithmId::MlDsa44), + Some(AlgorithmId::MlDsa44), + CalendarDuration::years(3), + ), + &pq_dir, + ) + .unwrap(); + assert!(verify( + &root_dir.join("public/bundles/roots-pq.pem"), + &issuer_dir.join("public/certs/ml-dsa-44/a/signed-by-ml-dsa-44.crt.pem"), + &pq_dir.join("leaf.crt.pem"), + )); + // Cross path: the P-256 issuer variant signed by the Ed25519 + // root, anchored on the Ed25519 root alone. + let ed_root_pem = root_dir.join("public/roots/ed25519/root.crt.pem"); + assert!(verify( + &ed_root_pem, + &issuer_dir.join("public/certs/p256/a/signed-by-ed25519.crt.pem"), + &leaf_dir.join("leaf.crt.pem"), + )); +} + +#[test] +fn signer_source_and_legacy_gates() { + // Oracle: §24.3 (explicit signer source) and §24.1(1) (legacy + // gate) as policy errors, not silent fallbacks. + let tmp = TempDir::new("gates"); + // Empty signer source directory: the root key load must fail + // with a policy error naming the signer source. + let empty = tmp.path().join("empty-keys"); + std::fs::create_dir_all(&empty).unwrap(); + let err = engine::load_signer_key( + &SignerSource { key_dir: empty }, + "ed25519.pk8", + AlgorithmId::Ed25519, + ) + .err() + .expect("missing key must error"); + assert!( + format!("{err}").contains("signer source"), + "error must name the signer-source rule: {err}" + ); + // RSA-2048 root without the opt-in is refused; with it, created. + let mut req = root_request(vec![AlgorithmId::Rsa2048]); + let out = tmp.path().join("legacy-denied"); + let err = engine::create_root_set(&req, &out).err().expect("must refuse"); + assert!(format!("{err}").contains("--allow-legacy-root-strength")); + req.allow_legacy_root_strength = true; + let out2 = tmp.path().join("legacy-allowed"); + let m = engine::create_root_set(&req, &out2).unwrap(); + assert_eq!(m.certificates.len(), 1); +} + +#[test] +fn leaf_validity_clamps_to_issuer_with_warning() { + // Oracle: §5.4 — a leaf must not outlive its issuer; the clamp + // is applied and recorded as a manifest warning. + let tmp = TempDir::new("clamp"); + let (root_dir, issuer_dir) = build_hierarchy(&tmp, vec![AlgorithmId::Ed25519]); + let _ = root_dir; + let leaf_dir = tmp.path().join("leaf"); + let mut req = leaf_request( + &issuer_dir, + "server", + "longlived", + None, + None, + CalendarDuration::years(20), + ); + req.not_after = ts("2046-01-01T00:00:00Z"); + let m = engine::issue_leaf(&req, &leaf_dir).unwrap(); + assert_eq!( + m.certificates[0].not_after, + ts("2031-01-01T00:00:00Z"), + "leaf not-after must clamp to the issuer's" + ); + assert!( + m.warnings.iter().any(|w| w.contains("clamped")), + "the clamp must be recorded as a warning: {:?}", + m.warnings + ); +} + +#[test] +fn tampered_bundle_is_rejected() { + // Oracle: the §7.1 manifest checksum index — flipping bytes in + // an indexed artifact must make the bundle unloadable. + let tmp = TempDir::new("tamper"); + let root_dir = tmp.path().join("roots"); + engine::create_root_set(&root_request(vec![AlgorithmId::Ed25519]), &root_dir).unwrap(); + assert!(load_bundle(&root_dir).is_ok()); + let cert_path = root_dir.join("public/roots/ed25519/root.crt.pem"); + let mut bytes = std::fs::read(&cert_path).unwrap(); + bytes[40] ^= 0xff; + std::fs::write(&cert_path, bytes).unwrap(); + let err = load_bundle(&root_dir).err().expect("tamper must be caught"); + assert!(format!("{err}").contains("checksum"), "got: {err}"); +} diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 775cbd3288..dc4b566a83 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -65,6 +65,10 @@ pub enum Capability { /// the next piece of work down the intake ladder, and run a command /// where builds belong. Composes the other domains' verbs. Agent, + /// `fleet cert …` (alias `fleet pki …`) — the PKI/X.509 domain: + /// roots, issuers, leaves, chains and bundles (code#9157, fleet CA + /// program #9155). A working-seat client surface, so full only. + Cert, } impl Capability { @@ -87,6 +91,7 @@ impl Capability { Capability::Gh => "gh", Capability::Bridge => "bridge", Capability::Agent => "agent", + Capability::Cert => "cert", } } @@ -108,6 +113,7 @@ impl Capability { Capability::Gh, Capability::Bridge, Capability::Agent, + Capability::Cert, ]; } @@ -358,6 +364,17 @@ pub const DOMAINS: &[Domain] = &[ aliases: &["atlas-search"], subcommands: &["search", "get-chunk", "serve"], }, + Domain { + name: "cert", + summary: "PKI/X.509: root and issuer CAs, leaf certificates, chains and bundles (alias: pki).", + capabilities: &[Capability::Cert], + primary: Capability::Cert, + aliases: &["pki"], + subcommands: &[ + "root", "issuer", "leaf", "chain", "bundle", "profile", "algorithms", "explain", + "doctor", + ], + }, Domain { name: "laptop-agent", summary: "Client for the laptop-agent daemon: run and manage jobs on the laptop.", @@ -408,6 +425,10 @@ pub fn alias_route(argv0: &str) -> Option { domain: "laptop-agent", implied_arg: None, }), + "pki" => Some(AliasRoute { + domain: "cert", + implied_arg: None, + }), _ => None, } } @@ -466,6 +487,7 @@ mod tests { "laptop-agent-broker", "atlas-search", "laptop-agent", + "pki", ] { let route = alias_route(name).unwrap_or_else(|| panic!("alias {name} must route")); assert!( diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 21d30b6972..f7f1c6f8c6 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -36,6 +36,9 @@ fleet-bridge = { workspace = true, optional = true } # verbs (enroll, doctor, next, shortlist) and `fleet shell`; a # working-seat client, so full only. fleet-agent = { workspace = true, optional = true } +# The cert domain (code#9157): PKI/X.509 roots, issuers, leaves, +# chains and bundles over the fleet-cert library crate. +fleet-cert = { workspace = true, optional = true } serde_json = { workspace = true } # The OpenCode session liveness probe (session_state.rs) only; # optional so the connect variant stays under the D7 size gate. @@ -84,6 +87,7 @@ full = [ "gh", "bridge", "agent", + "cert", "opencode-probe", ] # The serve variant's set, as one feature for the nix build. @@ -144,6 +148,9 @@ bridge = ["dep:fleet-bridge"] # It runs the other domains' verbs through this same binary, so it links # only fleet-config. Full only. agent = ["dep:fleet-agent"] +# The cert domain: a working-seat PKI client surface, so full only — +# never in serve (no daemon role) or connect (size gate). +cert = ["dep:fleet-cert"] [dev-dependencies] # Property tests for the gh read classifier (AGENTS.md testing diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 870dc0897c..62ca1730ac 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -9,7 +9,10 @@ //! roles run for real below; step 3 (#5431) the proxy domain; step 4 //! (#5432) the dispatch thin client; step 6 (#5554) the secrets verb; //! step 5 (#5433) the search client domain, with its serve role -//! (`fleet serve search`, the Atlas service) following in #5604. A +//! (`fleet serve search`, the Atlas service) following in #5604. +//! The cert domain (#9157, fleet CA program #9155) landed later: +//! `fleet cert` (alias `fleet pki`) — PKI/X.509 roots, issuers, +//! leaves, chains and bundles over the fleet-cert library crate. A //! compiled-in domain that has //! not landed yet answers with the "not implemented yet" form of //! the stub — but the *surface* is complete and honest: every @@ -120,6 +123,9 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "agent") { caps.insert(Capability::Agent); } + if cfg!(feature = "cert") { + caps.insert(Capability::Cert); + } caps } @@ -407,6 +413,7 @@ fn print_domain_help(surface: &Surface, d: &Domain) { "search" => "included in this build (options: fleet search --help)", "proxy" => "included in this build", "bridge" => "included in this build (options: fleet bridge --help)", + "cert" => "included in this build (options: fleet cert --help)", "agent" => "included in this build (options: fleet agent --help)", "shell" => "included in this build (options: fleet shell --help)", "gh" => "included in this build", @@ -427,6 +434,18 @@ fn print_domain_help(surface: &Surface, d: &Domain) { println!("Status: {status}"); } +/// Resolve a root-level subcommand name to its domain. Canonical +/// names come from the registry; `pki` is the cert domain's +/// documented alias (spec §6: `fleet pki ...` ≡ `fleet cert ...`), +/// the same name the argv0 map routes to cert. +fn resolve_domain(name: &str) -> Option<&'static Domain> { + match domain(name) { + Some(d) => Some(d), + None if name == "pki" => domain("cert"), + None => None, + } +} + fn usage_error(message: &str) -> i32 { eprintln!("error: {message}"); eprintln!(); @@ -776,6 +795,18 @@ fn run_domain_with_initializer( println!("{}", fleet_search::SEARCH_USAGE); return EXIT_OK; } + // The cert domain's own usage answers `fleet cert --help`: + // the registry's domain help names the verb groups but not the + // flags, and the cert usage is the documented surface — the + // same carve-out the search client gets above (#12782). + #[cfg(feature = "cert")] + if d.name == "cert" + && args.first().is_some_and(|a| is_help_flag(a)) + && surface.cap_state(Capability::Cert, d.name) == CapState::Available + { + println!("{}", fleet_cert::cli::CERT_USAGE); + return EXIT_OK; + } // The proxy role under its serve spelling has its own usage // (SERVE_PROXY_USAGE, #6770): `fleet serve proxy --help` asks for // the role's help, not the serve domain's — answer it before the @@ -983,6 +1014,13 @@ fn run_domain_with_initializer( if d.name == "shell" { return fleet_agent::run_shell(&surface.config, args); } + // The cert domain (#9157): PKI/X.509 roots, issuers, + // leaves, chains and bundles — the fleet-cert library + // crate's CLI shell (full build only). + #[cfg(feature = "cert")] + if d.name == "cert" { + return fleet_cert::run(args); + } // Step 5 (#5433): the search domain runs for real — // the atlas-search client surface over the live Atlas // service (full build only; the serve build carries @@ -1504,7 +1542,7 @@ fn run_root(surface: &Surface, args: &[String], invoked_as: &str) -> i32 { println!("{HELP_USAGE}"); EXIT_OK } - Some("help") => match args.get(1).and_then(|name| domain(name)) { + Some("help") => match args.get(1).and_then(|name| resolve_domain(name)) { Some(d) => { // `help` takes exactly one argument — the domain name. // Anything after it is a usage error naming the first @@ -1554,7 +1592,7 @@ fn run_root(surface: &Surface, args: &[String], invoked_as: &str) -> i32 { } Some("init") => cmd_init(surface, &args[1..], invoked_as), Some("session") => session_state::run(&args[1..]), - Some(name) => match domain(name) { + Some(name) => match resolve_domain(name) { Some(d) => run_domain(surface, d, &args[1..], invoked_as), None => usage_error(&format!("unrecognized subcommand '{name}'")), },