From 9ca139bff5aabe6c233824e4bd2640a17e171492 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 10:23:06 -0600 Subject: [PATCH 1/2] feat(fleet-cert): add standalone key generate and inspect --- pkgs/fleet/crates/fleet-cert/src/cli.rs | 166 ++++++++++++++++++++- pkgs/fleet/crates/fleet-cert/src/engine.rs | 28 ++++ 2 files changed, 190 insertions(+), 4 deletions(-) diff --git a/pkgs/fleet/crates/fleet-cert/src/cli.rs b/pkgs/fleet/crates/fleet-cert/src/cli.rs index 3456ea041..c04444ccf 100644 --- a/pkgs/fleet/crates/fleet-cert/src/cli.rs +++ b/pkgs/fleet/crates/fleet-cert/src/cli.rs @@ -21,6 +21,8 @@ use crate::timeparse::{CalendarDuration, Rfc3339}; use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose}; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet}; +use std::fs::OpenOptions; +use std::io::Write; use std::path::PathBuf; /// Full usage for the cert domain (also what `fleet cert --help` @@ -36,6 +38,7 @@ Groups and verbs (spec §6.1 tree; status as built): ocsp sign | inspect | test chain build | test bundle inspect + key generate | inspect profile list | show algorithms list | describe explain [topic] @@ -228,6 +231,7 @@ fn run_inner(args: &[String]) -> Result { "ocsp" => ocsp_cmd(rest, json_out), "chain" => chain_cmd(rest, json_out), "bundle" => bundle_cmd(rest, json_out), + "key" => key_cmd(rest, json_out), "profile" => profile_cmd(rest, json_out), "algorithms" => algorithms_cmd(rest, json_out), "explain" => explain_cmd(rest, json_out), @@ -238,6 +242,93 @@ fn run_inner(args: &[String]) -> Result { } } +// ---------------------------------------------------------------- standalone key ceremony + +fn key_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 { + "generate" => { + let p = parse_args(rest, &["algorithm", "out"], &["json"])?; + let algorithm = parse_key_algorithm(&p)?; + let out = PathBuf::from(p.require("out", "key generate")?); + let key = engine::generate_key(algorithm)?; + let der = key.serialize_der(); + // Key generation is an explicit ceremony: create a new + // owner-readable file, and never replace an existing key. + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&out).map_err(|e| { + CertError::policy(format!( + "cannot create private key {} without replacing an existing file: {e}", + out.display() + )) + })?; + file.write_all(&der) + .and_then(|_| file.sync_all()) + .map_err(|e| { + let _ = std::fs::remove_file(&out); + CertError::engine(format!("writing private key {} failed: {e}", out.display())) + })?; + let value = json!({"algorithm": algorithm.info().name, "private_key": out.display().to_string(), "encoding": "PKCS#8 DER"}); + Ok(emit( + json_out, + format!( + "Generated {} private key at {} (PKCS#8 DER)\n", + algorithm.info().name, + out.display() + ), + value, + )) + } + "inspect" => { + let p = parse_args(rest, &["algorithm", "in"], &["json"])?; + let algorithm = parse_key_algorithm(&p)?; + let path = PathBuf::from(p.require("in", "key inspect")?); + let pkcs8 = std::fs::read(&path).map_err(|e| { + CertError::policy(format!("cannot read private key {}: {e}", path.display())) + })?; + let public = engine::inspect_key(algorithm, &pkcs8)?; + let fingerprint = crate::bundle::sha256_hex(&public); + let value = json!({ + "algorithm": algorithm.info().name, + "private_key": path.display().to_string(), + "encoding": "PKCS#8 DER", + "public_key_fingerprint_sha256": fingerprint, + "public_key_bytes": public.len(), + "private_material_emitted": false, + }); + Ok(emit( + json_out, + format!( + "{} private key\n encoding: PKCS#8 DER\n public-key SHA-256: {fingerprint}\n public-key bytes: {}\n private material: redacted\n", + algorithm.info().name, + public.len() + ), + value, + )) + } + other => Err(CertError::usage(format!( + "unknown key verb '{other}' (generate | inspect)" + ))), + } +} + +fn parse_key_algorithm(p: &Parsed) -> Result { + let name = p.require("algorithm", "key operation")?; + AlgorithmId::parse(&name).map(|(algorithm, warning)| { + if let Some(warning) = warning { + eprintln!("warning: {warning}"); + } + algorithm + }) +} + // ---------------------------------------------------------------- root fn root_cmd(args: &[String], json_out: bool) -> Result { @@ -861,8 +952,8 @@ const NOT_BUILT: &[(&str, &str)] = &[ "trust-store install/export (spec §3.5 follow-through)", ), ( - "key", - "key inspect/import/export/convert-public (spec §6.1)", + "key import/export/escrow/restore/rotate", + "remaining standalone key ceremonies (spec §6.1)", ), ("format", "format list/describe/export/convert (spec §7.5)"), ( @@ -984,7 +1075,7 @@ fn doctor_cmd(_args: &[String], json_out: bool) -> Result { " 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(" built: root, issuer, leaf, key (generate/inspect), 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")); @@ -992,7 +1083,7 @@ fn doctor_cmd(_args: &[String], json_out: bool) -> Result { 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"], + "built": ["root", "issuer", "leaf", "key-generate/inspect", "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); @@ -1021,6 +1112,73 @@ fn engine_self_test(algo: AlgorithmId) -> bool { } } +#[cfg(test)] +mod key_ceremony_tests { + use super::*; + + #[test] + fn generate_creates_private_file_once_and_inspect_redacts_material() { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("fleet-cert-key-{}-{nonce}", std::process::id())); + std::fs::create_dir(&dir).expect("create isolated test directory"); + let path = dir.join("p256.pk8"); + let path_text = path.to_string_lossy().into_owned(); + let generated = key_cmd( + &[ + "generate".into(), + "--algorithm".into(), + "p256".into(), + "--out".into(), + path_text.clone(), + ], + true, + ); + assert!(generated.is_ok()); + let bytes = std::fs::read(&path).expect("generated PKCS#8 key"); + assert!(!bytes.is_empty()); + assert!(engine::inspect_key(AlgorithmId::P256, &bytes).is_ok()); + assert!( + key_cmd( + &[ + "inspect".into(), + "--algorithm".into(), + "p256".into(), + "--in".into(), + path_text.clone(), + ], + true, + ) + .is_ok() + ); + assert!( + key_cmd( + &[ + "generate".into(), + "--algorithm".into(), + "p256".into(), + "--out".into(), + path_text, + ], + true, + ) + .is_err() + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + std::fs::remove_dir_all(dir).expect("remove isolated test directory"); + } +} + // ---------------------------------------------------------------- ocsp fn ocsp_cmd(args: &[String], json_out: bool) -> Result { diff --git a/pkgs/fleet/crates/fleet-cert/src/engine.rs b/pkgs/fleet/crates/fleet-cert/src/engine.rs index cb4fa241f..2427ea427 100644 --- a/pkgs/fleet/crates/fleet-cert/src/engine.rs +++ b/pkgs/fleet/crates/fleet-cert/src/engine.rs @@ -77,6 +77,34 @@ impl MlDsa44Signer { .to_vec(); Ok(MlDsa44Signer { key, public_key }) } + + pub fn public_key(&self) -> &[u8] { + &self.public_key + } +} + +/// Parse a PKCS#8 key using the explicitly named algorithm and return +/// only its public key bytes. Private material is never part of the +/// result, which is the metadata boundary used by `key inspect`. +pub fn inspect_key(algo: AlgorithmId, pkcs8: &[u8]) -> Result> { + match algo { + AlgorithmId::MlDsa44 => Ok(MlDsa44Signer::from_pkcs8(pkcs8)?.public_key().to_vec()), + AlgorithmId::Ed25519 => Ok(KeyPair::from_pkcs8_der_and_sign_algo(pkcs8, &PKCS_ED25519)? + .public_key_raw() + .to_vec()), + AlgorithmId::P256 => Ok(KeyPair::from_pkcs8_der_and_sign_algo( + pkcs8, + &PKCS_ECDSA_P256_SHA256, + )? + .public_key_raw() + .to_vec()), + AlgorithmId::Rsa4096 | AlgorithmId::Rsa2048 => Ok(KeyPair::from_pkcs8_der_and_sign_algo( + pkcs8, + &PKCS_RSA_SHA256, + )? + .public_key_raw() + .to_vec()), + } } impl rcgen::PublicKeyData for MlDsa44Signer { From 7effe8c0d38f5a0cc7daaa6af34563dac1fea3c3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 10:46:26 -0600 Subject: [PATCH 2/2] fix(fleet-cert): parse PKCS#8 DER for key inspection --- pkgs/fleet/crates/fleet-cert/src/engine.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/pkgs/fleet/crates/fleet-cert/src/engine.rs b/pkgs/fleet/crates/fleet-cert/src/engine.rs index 2427ea427..c1c27b8f4 100644 --- a/pkgs/fleet/crates/fleet-cert/src/engine.rs +++ b/pkgs/fleet/crates/fleet-cert/src/engine.rs @@ -89,17 +89,20 @@ impl MlDsa44Signer { pub fn inspect_key(algo: AlgorithmId, pkcs8: &[u8]) -> Result> { match algo { AlgorithmId::MlDsa44 => Ok(MlDsa44Signer::from_pkcs8(pkcs8)?.public_key().to_vec()), - AlgorithmId::Ed25519 => Ok(KeyPair::from_pkcs8_der_and_sign_algo(pkcs8, &PKCS_ED25519)? - .public_key_raw() - .to_vec()), + AlgorithmId::Ed25519 => Ok(KeyPair::from_pkcs8_der_and_sign_algo( + &rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()), + &PKCS_ED25519, + )? + .public_key_raw() + .to_vec()), AlgorithmId::P256 => Ok(KeyPair::from_pkcs8_der_and_sign_algo( - pkcs8, + &rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()), &PKCS_ECDSA_P256_SHA256, )? .public_key_raw() .to_vec()), AlgorithmId::Rsa4096 | AlgorithmId::Rsa2048 => Ok(KeyPair::from_pkcs8_der_and_sign_algo( - pkcs8, + &rustls_pki_types::PrivatePkcs8KeyDer::from(pkcs8.to_vec()), &PKCS_RSA_SHA256, )? .public_key_raw()