From 94ee1c90b608b024bfb983588d0a9dfc4ab6ce1d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 11:12:50 -0600 Subject: [PATCH] feat(fleet-cert): validate and scaffold custom profiles --- pkgs/fleet/crates/fleet-cert/src/cli.rs | 59 ++++- pkgs/fleet/crates/fleet-cert/src/engine.rs | 25 +- pkgs/fleet/crates/fleet-cert/src/profile.rs | 243 ++++++++++++++++++ .../crates/fleet/tests/cert_profile_cli.rs | 139 ++++++++++ 4 files changed, 453 insertions(+), 13 deletions(-) create mode 100644 pkgs/fleet/crates/fleet/tests/cert_profile_cli.rs diff --git a/pkgs/fleet/crates/fleet-cert/src/cli.rs b/pkgs/fleet/crates/fleet-cert/src/cli.rs index 3456ea0419..50d7009f91 100644 --- a/pkgs/fleet/crates/fleet-cert/src/cli.rs +++ b/pkgs/fleet/crates/fleet-cert/src/cli.rs @@ -36,7 +36,7 @@ Groups and verbs (spec §6.1 tree; status as built): ocsp sign | inspect | test chain build | test bundle inspect - profile list | show + profile list | show | validate | scaffold algorithms list | describe explain [topic] doctor @@ -433,7 +433,7 @@ fn leaf_cmd(args: &[String], json_out: bool) -> Result { 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 prof = profile::resolve_profile(&profile_name)?; let name = p .get("name") .map(|s| s.to_string()) @@ -771,8 +771,53 @@ fn profile_cmd(args: &[String], json_out: bool) -> Result { }); Ok(emit(json_out, text, value)) } + "scaffold" => { + let p = parse_args(rest, &["name", "out"], &["json"])?; + let name = p + .get("name") + .or_else(|| p.positional(0)) + .ok_or_else(|| CertError::usage("profile scaffold needs --name "))?; + let out = p.require("out", "profile scaffold")?; + let scaffold = profile::CustomProfile::scaffold(name); + scaffold.validate()?; + let bytes = serde_json::to_vec_pretty(&scaffold) + .map_err(|e| CertError::engine(e.to_string()))?; + use std::io::Write; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&out) + .map_err(|e| CertError::engine(format!("cannot create profile {out}: {e}")))?; + file.write_all(&bytes) + .map_err(|e| CertError::engine(format!("cannot write profile {out}: {e}")))?; + Ok(emit( + json_out, + format!("Scaffolded custom profile {name} at {out}\n"), + json!({"name": name, "path": out, "profile": scaffold}), + )) + } + "validate" => { + let p = parse_args(rest, &["file"], &["json"])?; + let path = p + .get("file") + .or_else(|| p.positional(0)) + .ok_or_else(|| CertError::usage("profile validate needs "))?; + let (custom, resolved) = profile::load_custom_profile(&PathBuf::from(path))?; + let text = format!( + "Valid custom profile {} (key={}, validity={}d, ceiling={}d)\n", + custom.name, + resolved.key_algorithm.name(), + custom.default_validity_days, + custom.max_validity_days + ); + Ok(emit( + json_out, + text, + json!({"valid": true, "profile": custom}), + )) + } other => Err(CertError::usage(format!( - "unknown profile verb '{other}' (list | show)" + "unknown profile verb '{other}' (list | show | validate | scaffold)" ))), } } @@ -865,10 +910,6 @@ const NOT_BUILT: &[(&str, &str)] = &[ "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)", @@ -984,7 +1025,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, chain, bundle (inspect), profile (list/show/validate/scaffold), 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 +1033,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", "chain", "bundle-inspect", "profile-list/show/validate/scaffold", "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); diff --git a/pkgs/fleet/crates/fleet-cert/src/engine.rs b/pkgs/fleet/crates/fleet-cert/src/engine.rs index cb4fa241f7..d814fd2baf 100644 --- a/pkgs/fleet/crates/fleet-cert/src/engine.rs +++ b/pkgs/fleet/crates/fleet-cert/src/engine.rs @@ -27,7 +27,6 @@ use crate::model::{ ParentRef, RootCreateRequest, }; use crate::naming::{GenerationPartition, slugify}; -use crate::profile::leaf_profile; use crate::timeparse::Rfc3339; use rcgen::{ BasicConstraints, CertificateParams, DnType, DnValue, IsCa, Issuer, KeyPair, KeyUsagePurpose, @@ -850,7 +849,7 @@ fn clamp_window( /// `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 profile = crate::profile::resolve_profile(&req.profile)?; let issuer_bundle = load_bundle(&req.issuer_bundle)?; if issuer_bundle.manifest.bundle_type != BundleType::IssuerSet { return Err(CertError::usage(format!( @@ -859,6 +858,18 @@ pub fn issue_leaf(req: &LeafIssueRequest, out_dir: &Path) -> Result Result time::Duration::days(i64::from(profile.max_validity_days)) { + return Err(CertError::policy(format!( + "profile '{}' validity exceeds its {} day ceiling", + profile.name, profile.max_validity_days + ))); + } // Subject + SANs. let mut sans: Vec = req.dns_names.clone(); @@ -945,8 +962,8 @@ pub fn issue_leaf(req: &LeafIssueRequest, out_dir: &Path) -> Result, + pub extended_key_usages: Vec, + pub default_validity_days: u32, + pub max_validity_days: u32, + #[serde(default)] + pub san_defaults_to_cn: bool, + #[serde(default)] + pub notes: String, +} + +/// Runtime profile values used by the signing engine. Constructed only +/// after resolving a built-in or validating a custom profile file. +#[derive(Debug, Clone)] +pub struct ResolvedProfile { + pub name: String, + pub key_algorithm: AlgorithmId, + pub key_usages: Vec, + pub extended_key_usages: Vec, + pub default_validity: CalendarDuration, + pub max_validity_days: u32, + pub san_defaults_to_cn: bool, + pub ocsp_no_check: bool, + pub is_custom: bool, +} + +impl CustomProfile { + pub fn scaffold(name: &str) -> Self { + Self { + schema: "fleet-cert-profile/v1".into(), + name: name.into(), + key_algorithm: "p256".into(), + key_usages: vec!["digital-signature".into()], + extended_key_usages: vec!["server-auth".into()], + default_validity_days: 90, + max_validity_days: 365, + san_defaults_to_cn: true, + notes: "Custom TLS server profile".into(), + } + } + + pub fn validate(&self) -> Result { + if self.schema != "fleet-cert-profile/v1" { + return Err(CertError::policy(format!( + "unsupported profile schema '{}'", + self.schema + ))); + } + if self.name.trim().is_empty() + || self.name.len() > 64 + || !self + .name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + { + return Err(CertError::policy( + "profile name must be 1-64 lowercase ASCII letters, digits, or hyphens", + )); + } + if leaf_profiles().iter().any(|p| p.name == self.name) { + return Err(CertError::policy(format!( + "custom profile name '{}' shadows a built-in profile", + self.name + ))); + } + let (key_algorithm, _) = AlgorithmId::parse(&self.key_algorithm)?; + let key_usages = self + .key_usages + .iter() + .map(|s| parse_key_usage(s)) + .collect::>>()?; + let extended_key_usages = self + .extended_key_usages + .iter() + .map(|s| parse_extended_key_usage(s)) + .collect::>>()?; + if key_usages.is_empty() { + return Err(CertError::policy( + "custom profile must declare at least one key usage", + )); + } + if key_usages.iter().any(|usage| { + matches!( + usage, + rcgen::KeyUsagePurpose::KeyCertSign | rcgen::KeyUsagePurpose::CrlSign + ) + }) { + return Err(CertError::policy( + "custom leaf profiles cannot declare key-cert-sign or crl-sign", + )); + } + if self.default_validity_days == 0 || self.default_validity_days > self.max_validity_days { + return Err(CertError::policy( + "default_validity_days must be positive and no greater than max_validity_days", + )); + } + if self.max_validity_days > MAX_CUSTOM_VALIDITY_DAYS { + return Err(CertError::policy(format!( + "max_validity_days exceeds policy ceiling of {MAX_CUSTOM_VALIDITY_DAYS}" + ))); + } + Ok(ResolvedProfile { + name: self.name.clone(), + key_algorithm, + key_usages, + extended_key_usages, + default_validity: CalendarDuration::days(i64::from(self.default_validity_days)), + max_validity_days: self.max_validity_days, + san_defaults_to_cn: self.san_defaults_to_cn, + ocsp_no_check: false, + is_custom: true, + }) + } +} + +fn parse_key_usage(value: &str) -> Result { + use rcgen::KeyUsagePurpose as K; + match value { + "digital-signature" => Ok(K::DigitalSignature), + "content-commitment" => Ok(K::ContentCommitment), + "key-encipherment" => Ok(K::KeyEncipherment), + "data-encipherment" => Ok(K::DataEncipherment), + "key-agreement" => Ok(K::KeyAgreement), + "key-cert-sign" => Ok(K::KeyCertSign), + "crl-sign" => Ok(K::CrlSign), + "encipher-only" => Ok(K::EncipherOnly), + "decipher-only" => Ok(K::DecipherOnly), + _ => Err(CertError::policy(format!( + "unsupported key usage '{value}'" + ))), + } +} + +fn parse_extended_key_usage(value: &str) -> Result { + use rcgen::ExtendedKeyUsagePurpose as E; + match value { + "server-auth" => Ok(E::ServerAuth), + "client-auth" => Ok(E::ClientAuth), + "code-signing" => Ok(E::CodeSigning), + "email-protection" => Ok(E::EmailProtection), + "time-stamping" => Ok(E::TimeStamping), + "ocsp-signing" => Ok(E::OcspSigning), + _ => Err(CertError::policy(format!( + "unsupported extended key usage '{value}'" + ))), + } +} + +pub fn load_custom_profile(path: &Path) -> Result<(CustomProfile, ResolvedProfile)> { + let bytes = std::fs::read(path) + .map_err(|e| CertError::manifest(format!("cannot read profile {}: {e}", path.display())))?; + let profile: CustomProfile = serde_json::from_slice(&bytes) + .map_err(|e| CertError::manifest(format!("malformed custom profile: {e}")))?; + let resolved = profile.validate()?; + Ok((profile, resolved)) +} /// A leaf certificate profile. #[derive(Debug, Clone, PartialEq, Eq)] @@ -133,6 +302,25 @@ pub fn leaf_profile(name: &str) -> Result<&'static LeafProfile> { }) } +pub fn resolve_profile(name_or_path: &str) -> Result { + if let Ok(profile) = leaf_profile(name_or_path) { + return Ok(ResolvedProfile { + name: profile.name.into(), + key_algorithm: profile.key_algorithm, + key_usages: profile.key_usages.to_vec(), + extended_key_usages: profile.extended_key_usages.to_vec(), + default_validity: profile.default_validity, + // The custom-profile ceiling is not a new constraint on the + // established built-in profiles and their existing callers. + max_validity_days: u32::MAX, + san_defaults_to_cn: profile.san_defaults_to_cn, + ocsp_no_check: profile.ocsp_no_check, + is_custom: false, + }); + } + load_custom_profile(Path::new(name_or_path)).map(|(_, profile)| profile) +} + #[cfg(test)] mod tests { use super::*; @@ -156,4 +344,59 @@ mod tests { ); assert!(leaf_profile("web").is_err()); } + + #[test] + fn custom_profile_schema_and_policy_are_enforced() { + let profile = CustomProfile::scaffold("device-auth"); + let resolved = profile.validate().expect("scaffold is valid by policy"); + assert_eq!(resolved.key_algorithm, AlgorithmId::P256); + assert_eq!(resolved.max_validity_days, 365); + + let mut invalid = profile.clone(); + invalid.key_usages = vec!["not-a-usage".into()]; + assert!( + invalid + .validate() + .unwrap_err() + .to_string() + .contains("unsupported key usage") + ); + let mut invalid = profile.clone(); + invalid.extended_key_usages = vec!["unknown-purpose".into()]; + assert!( + invalid + .validate() + .unwrap_err() + .to_string() + .contains("unsupported extended key usage") + ); + let mut invalid = profile.clone(); + invalid.max_validity_days = MAX_CUSTOM_VALIDITY_DAYS + 1; + assert!( + invalid + .validate() + .unwrap_err() + .to_string() + .contains("policy ceiling") + ); + let mut invalid = profile; + invalid.schema = "fleet-cert-profile/v99".into(); + assert!( + invalid + .validate() + .unwrap_err() + .to_string() + .contains("unsupported profile schema") + ); + + let mut invalid = CustomProfile::scaffold("ca-usage"); + invalid.key_usages = vec!["key-cert-sign".into()]; + assert!( + invalid + .validate() + .unwrap_err() + .to_string() + .contains("leaf profiles") + ); + } } diff --git a/pkgs/fleet/crates/fleet/tests/cert_profile_cli.rs b/pkgs/fleet/crates/fleet/tests/cert_profile_cli.rs new file mode 100644 index 0000000000..9c6c2d66a4 --- /dev/null +++ b/pkgs/fleet/crates/fleet/tests/cert_profile_cli.rs @@ -0,0 +1,139 @@ +//! CLI-level coverage for custom certificate profile scaffolding. +//! +//! Oracle: `fleet cert profile validate` accepts the scaffold emitted by +//! `fleet cert profile scaffold`, and rejects malformed JSON and profiles +//! that violate the custom-profile policy. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::time::{SystemTime, UNIX_EPOCH}; + +struct TempDir(PathBuf); + +impl TempDir { + fn new() -> Self { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock") + .as_nanos(); + let path = std::env::temp_dir().join(format!( + "fleet-cert-profile-cli-{}-{nanos}", + std::process::id() + )); + std::fs::create_dir_all(&path).expect("create temp directory"); + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn fleet(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_fleet")) + .args(args) + .output() + .expect("run fleet") +} + +fn stderr(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[test] +fn scaffold_output_is_accepted_by_profile_validate() { + let temp = TempDir::new(); + let profile = temp.path().join("edge-server.json"); + let profile_arg = profile.to_str().expect("UTF-8 temp path"); + + let scaffold = fleet(&[ + "cert", + "profile", + "scaffold", + "--name", + "edge-server", + "--out", + profile_arg, + ]); + assert_eq!(scaffold.status.code(), Some(0), "{}", stderr(&scaffold)); + assert!( + profile.is_file(), + "scaffold should write the requested file" + ); + + let validate = fleet(&["cert", "profile", "validate", "--json", profile_arg]); + assert_eq!(validate.status.code(), Some(0), "{}", stderr(&validate)); + let result: serde_json::Value = + serde_json::from_slice(&validate.stdout).expect("validate --json output"); + assert_eq!(result["valid"], true); + assert_eq!(result["profile"]["name"], "edge-server"); +} + +#[test] +fn profile_validate_rejects_malformed_json() { + let temp = TempDir::new(); + let profile = temp.path().join("malformed.json"); + std::fs::write(&profile, b"{ not json").expect("write malformed profile"); + + let output = fleet(&[ + "cert", + "profile", + "validate", + profile.to_str().expect("UTF-8 temp path"), + ]); + assert_eq!(output.status.code(), Some(1), "{}", stderr(&output)); + assert!(stderr(&output).contains("malformed custom profile")); +} + +#[test] +fn profile_validate_rejects_policy_invalid_profile() { + let temp = TempDir::new(); + let profile = temp.path().join("overlong.json"); + let invalid = serde_json::json!({ + "schema": "fleet-cert-profile/v1", + "name": "edge-server", + "key_algorithm": "p256", + "key_usages": ["digital-signature"], + "extended_key_usages": ["server-auth"], + "default_validity_days": 90, + "max_validity_days": 1096, + "san_defaults_to_cn": true, + "notes": "exceeds the custom profile policy ceiling" + }); + std::fs::write(&profile, serde_json::to_vec(&invalid).unwrap()) + .expect("write policy-invalid profile"); + + let output = fleet(&[ + "cert", + "profile", + "validate", + profile.to_str().expect("UTF-8 temp path"), + ]); + assert_eq!(output.status.code(), Some(1), "{}", stderr(&output)); + assert!(stderr(&output).contains("policy ceiling")); +} + +#[test] +fn scaffold_does_not_overwrite_an_existing_file() { + let temp = TempDir::new(); + let profile = temp.path().join("existing.json"); + std::fs::write(&profile, b"keep this content").expect("write existing file"); + + let output = fleet(&[ + "cert", + "profile", + "scaffold", + "--name", + "edge-server", + "--out", + profile.to_str().expect("UTF-8 temp path"), + ]); + assert_eq!(output.status.code(), Some(1), "{}", stderr(&output)); + assert_eq!(std::fs::read(&profile).unwrap(), b"keep this content"); +}