diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index 3798f0d..a2e06cf 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -460,6 +460,19 @@ fn unprintable(c: char) -> bool { /// an hour later (docs/SIGNING.md). It is parsed, written again in canonical form and compared byte for byte, so /// any other spelling of the same values (key order, spaces, escapes, a trailing newline) is refused. pub fn approval_check(text: &str, now_secs: u64) -> Result { + let a = approval_parse(text)?; + if a.expires <= now_secs { + return Err(Error::Approval("it has expired")); + } + if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) { + return Err(Error::Approval("it expires more than an hour from now")); + } + Ok(a) +} + +/// [`approval_check`] without the clock: the canonical form and every member's rule, not the expiry. For reading +/// what a refused or expired request said; never enough to sign. +pub fn approval_parse(text: &str) -> Result { let err = |why: &'static str| Err(Error::Approval(why)); if text.len() > MAX_APPROVAL { return err("larger than 8 KiB"); @@ -508,12 +521,6 @@ pub fn approval_check(text: &str, now_secs: u64) -> Result { if a.canonical() != text { return err("not in canonical form (key order, spaces or escaping)"); } - if a.expires <= now_secs { - return err("it has expired"); - } - if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) { - return err("it expires more than an hour from now"); - } Ok(a) } diff --git a/crates/custos-sign/tests/approval.rs b/crates/custos-sign/tests/approval.rs index 31eecd8..4d6e923 100644 --- a/crates/custos-sign/tests/approval.rs +++ b/crates/custos-sign/tests/approval.rs @@ -187,6 +187,17 @@ fn approval_signs_only_a_valid_text_for_its_own_run() { assert!(approval(&k.secret, &k.key_id, &canonical(), NOW + 600, "r-42").is_err(), "expired at signing time"); } +#[test] +fn parse_reads_the_form_without_the_clock() { + // For the audit of a refused or expired request: everything but the expiry is checked. + let a = approval_parse(&canonical()).unwrap(); + assert_eq!(a, approval_check(&canonical(), NOW).unwrap()); + assert!(approval_check(&canonical(), NOW + 10_000).is_err()); + assert_eq!(approval_parse(&canonical()).unwrap().expires, NOW + 600); + assert!(approval_parse(&canonical().replace(',', ", ")).is_err()); + assert!(approval_parse(&with("\"run\":\"r-42\"", "\"run\":\"r 42\"")).is_err()); +} + #[test] fn run_ids_follow_the_rule() { for ok in ["r-42", "setup-1", "a.b_c", &"x".repeat(64)] { diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index 08b5b0a..746c4db 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -33,6 +33,9 @@ impl Refusal { } } +/// The key that signs deploy approvals, and nothing else (docs/SIGNING.md, "approval"). +pub const APPROVE_KEY: &str = "domi-approve"; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Role { @@ -54,6 +57,8 @@ pub enum SignKind { Minisign, Manifest, Authenticode, + /// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0). + Approval, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -77,6 +82,9 @@ pub struct Context { pub file: String, pub size: u64, pub sha256: String, + /// The version being built (core 0.12.0); absent when empty, so older readers see the entry they knew. + #[serde(skip_serializing_if = "String::is_empty")] + pub version: String, } /// A signing request, from the Domi pipe or the factor service's mailbox. @@ -88,6 +96,10 @@ pub struct Request { pub digest: Vec, /// The `SHA256SUMS` text, for a manifest. pub manifest: Option, + /// The deploy approval's canonical JSON, for `SignKind::Approval` (core 0.12.0). + pub approval: Option, + /// The build's run id, `[A-Za-z0-9._-]{1,64}` (core 0.12.0). Required for an approval, and equal to its `run`. + pub run: Option, pub context: Context, pub via: Via, } @@ -128,6 +140,9 @@ pub struct AuditEntry { /// Why, for refusals the vault decided. #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option, + /// The request's run id (core 0.12.0), when it had a well-formed one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run: Option, } /// A signature handed back to the build. @@ -333,6 +348,30 @@ impl Store { } } +/// Unix seconds from the vault's milliseconds, as minisign and approvals count them. +fn seconds(now_ms: i64) -> u64 { + (now_ms.max(0) / 1000) as u64 +} + +/// A new `domi-approve`: Ed25519, a release key with the given scope. +fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key { + let ed = custos_sign::new_ed25519(); + Key { + id: APPROVE_KEY.into(), + kind: KeyKind::Ed25519, + role: Role::Release, + name: "Domi deploy approval".into(), + secret: Secret::Ed25519(ed.secret), + public: Some(ed.public), + key_id: Some(ed.key_id), + cert: None, + issuer: None, + created: now, + pipelines: pipelines.to_vec(), + repos: repos.to_vec(), + } +} + fn in_scope(list: &[String], what: &str) -> bool { list.iter().any(|x| x == "*" || x == what) } @@ -419,7 +458,30 @@ impl Vault { true, ); self.signing.keys.extend([ed_key, root_key, leaf_key]); - Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()]) + let mut ids = vec![ed_id.to_string(), root_id.into(), leaf_id.into()]; + if role == Role::Release { + self.signing.keys.push(approve_key(&pipelines, &repos, now)); + ids.push(APPROVE_KEY.into()); + } + Ok(ids) + } + + /// Adds `domi-approve` to a vault whose release keys an older core made, with `domi-release`'s scope (else the + /// first release key's). Refused without release keys, or when the key is there already. The caller saves. + pub fn signing_add_approve(&mut self, now: i64) -> Result { + if self.signing.get(APPROVE_KEY).is_some() { + return Err(Error::SigningExists("approval")); + } + let release = self.signing.keys.iter().filter(|k| k.role == Role::Release && k.kind != KeyKind::RootCa); + let model = self + .signing + .get("domi-release") + .filter(|k| k.role == Role::Release) + .or_else(|| release.clone().next()) + .ok_or_else(|| Error::Signing("there are no release keys to add an approval key to".into()))?; + let key = approve_key(&model.pipelines, &model.repos, now); + self.signing.keys.push(key); + Ok(APPROVE_KEY.into()) } /// Every signing key, public parts only. @@ -472,19 +534,44 @@ impl Vault { /// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline /// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card. + /// An approval's expiry is checked against the system clock; [`Vault::signing_check_at`] takes the time. pub fn signing_check(&self, req: &Request) -> Result { + self.signing_check_at(req, crate::now_ms()) + } + + /// [`Vault::signing_check`] at `now` (Unix milliseconds): an approval must not have expired then, and must + /// expire at most an hour later. + pub fn signing_check_at(&self, req: &Request, now: i64) -> Result { + self.check(req, now).map(|(view, _)| view) + } + + /// The check, and the approval it read (for an approval request). + fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option), Refusal> { let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?; - let fits = matches!( - (k.kind, req.kind), - (KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) - | (KeyKind::CodeSigning, SignKind::Authenticode) - ); + let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release; + let fits = match (k.kind, req.kind) { + (KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY, + (KeyKind::Ed25519, SignKind::Approval) => approver, + (KeyKind::CodeSigning, SignKind::Authenticode) => true, + _ => false, + }; if k.kind == KeyKind::RootCa { return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id))); } if !fits { - return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind))); + return Err(Refusal::Invalid(if k.id == APPROVE_KEY || req.kind == SignKind::Approval { + format!("`{APPROVE_KEY}` signs deploy approvals only, and only it signs them (asked: `{}`)", k.id) + } else { + format!("`{}` cannot make {:?} signatures", k.id, req.kind) + })); } + if req.run.as_deref().is_some_and(|r| !custos_sign::run_id_ok(r)) { + return Err(Refusal::Invalid("the run is not a run id ([A-Za-z0-9._-], 1 to 64)".into())); + } + if req.kind != SignKind::Approval && req.approval.is_some() { + return Err(Refusal::Invalid("approval text comes only with an approval request".into())); + } + let mut approval = None; match req.kind { SignKind::Minisign if req.digest.len() != 64 => { return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into())); @@ -496,31 +583,56 @@ impl Vault { let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?; custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?; } + SignKind::Approval => { + let text = req.approval.as_deref().ok_or_else(|| Refusal::Invalid("no approval text".into()))?; + let a = custos_sign::approval_check(text, seconds(now)).map_err(|e| Refusal::Invalid(e.to_string()))?; + if req.run.as_deref() != Some(a.run.as_str()) { + return Err(Refusal::Invalid("the approval's run is not the request's run".into())); + } + let c = &req.context; + for (member, ours, theirs) in [ + ("repo", &c.repo, &a.repo), + ("pipeline", &c.pipeline, &a.pipeline), + ("commit", &c.commit, &a.commit), + ("version", &c.version, &a.version), + ] { + if !ours.is_empty() && ours != theirs { + return Err(Refusal::Invalid(format!("the request's {member} is not the approval's"))); + } + } + approval = Some(a); + } _ => {} } let file = &req.context.file; - if req.kind != SignKind::Manifest + if !matches!(req.kind, SignKind::Manifest | SignKind::Approval) && (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control)) { return Err(Refusal::Invalid("the file name is missing or not a plain name".into())); } - if !in_scope(&k.pipelines, &req.context.pipeline) { - return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id))); + // An approval is scoped by what it approves. + let (pipeline, repo) = match &approval { + Some(a) => (a.pipeline.as_str(), a.repo.as_str()), + None => (req.context.pipeline.as_str(), req.context.repo.as_str()), + }; + if !in_scope(&k.pipelines, pipeline) { + return Err(Refusal::OutOfScope(format!("pipeline `{pipeline}` may not use `{}`", k.id))); } - if !in_scope(&k.repos, &req.context.repo) { - return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id))); + if !in_scope(&k.repos, repo) { + return Err(Refusal::OutOfScope(format!("repo `{repo}` may not use `{}`", k.id))); } if k.role == Role::Test && req.context.trigger == "tag" { return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id))); } - Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists")) + let view = self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"); + Ok((view, approval)) } /// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only. /// A refusal is recorded too. The caller saves. pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result { - let view = match self.signing_check(req) { - Ok(v) => v, + let view = match self.check(req, now) { + Ok((v, _)) => v, Err(r) => { self.signing_record(req, r.outcome(), Some(r.to_string()), None, now); return Err(r); @@ -532,7 +644,7 @@ impl Vault { return Err(r); } let k = self.signing.get(&req.key).expect("checked"); - let seconds = (now.max(0) / 1000) as u64; + let seconds = seconds(now); let bytes = match (&k.secret, req.kind) { (Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign( s, @@ -549,6 +661,14 @@ impl Vault { seconds, ) .map(String::into_bytes), + (Secret::Ed25519(s), SignKind::Approval) => custos_sign::approval( + s, + &k.key_id.expect("ed25519 keys have an id"), + req.approval.as_deref().unwrap_or_default(), + seconds, + req.run.as_deref().unwrap_or_default(), + ) + .map(String::into_bytes), (Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest), _ => unreachable!("signing_check matched the key to the kind"), }; @@ -584,8 +704,31 @@ impl Vault { now: i64, ) { let mut context = req.context.clone(); - if req.kind == SignKind::Manifest { - context.file = "SHA256SUMS".into(); + let run = req.run.clone().filter(|r| custos_sign::run_id_ok(r)); + match req.kind { + SignKind::Manifest => context.file = "SHA256SUMS".into(), + SignKind::Approval => { + context.file = match &run { + Some(r) => format!("approval-{r}.json"), + None => "approval.json".into(), + }; + // What the approval says, where the request left the context empty: read without the clock, so a + // refused or expired request is filled in too. A text that does not read leaves the context as is. + let read = custos_sign::approval_parse(req.approval.as_deref().unwrap_or_default()).ok(); + if let Some(a) = read { + for (ours, theirs) in [ + (&mut context.repo, a.repo), + (&mut context.pipeline, a.pipeline), + (&mut context.commit, a.commit), + (&mut context.version, a.version), + ] { + if ours.is_empty() { + *ours = theirs; + } + } + } + } + _ => {} } self.signing.audit.push(AuditEntry { at: now, @@ -596,6 +739,7 @@ impl Vault { context, signature, reason, + run, }); } @@ -622,6 +766,8 @@ mod tests { kind, digest: vec![5; digest], manifest: None, + approval: None, + run: None, context: Context { repo: "Arca".into(), pipeline: "release".into(), @@ -633,6 +779,26 @@ mod tests { } } + #[test] + fn a_vault_with_release_keys_from_an_older_core_gets_its_approval_key() { + let mut v = + Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap(); + v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap(); + // What core 0.11.0 made: the release set without `domi-approve`. + v.signing.keys.retain(|k| k.id != "domi-approve"); + assert_eq!(v.signing.keys.len(), 3); + assert_eq!(v.signing_add_approve(7).unwrap(), "domi-approve"); + let views = v.signing_keys(); + let a = views.iter().find(|k| k.id == "domi-approve").unwrap(); + assert_eq!((a.kind, a.role, a.created), (KeyKind::Ed25519, Role::Release, 7)); + assert_eq!((a.pipelines.clone(), a.repos.clone()), (s(&["release"]), s(&["Arca"]))); + assert!(a.minisign_public.is_some()); + assert!(matches!(v.signing_add_approve(8), Err(Error::SigningExists("approval")))); + // It survives a save and a reopen. + let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(back.signing_keys(), views); + } + #[test] fn no_api_path_returns_a_private_key() { let mut v = @@ -648,7 +814,7 @@ mod tests { Secret::Rsa(s) => s.expose().to_vec(), }) .collect(); - assert_eq!(secrets.len(), 6); + assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set"); // Every public way out: views (serialised and printed), certificates, minisign public keys, checks, // signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store. @@ -665,6 +831,14 @@ mod tests { vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)]; reqs.push(req("domi-root", SignKind::Authenticode, 32)); reqs.push(req("domi-test", SignKind::Minisign, 64)); + let mut approve = req("domi-approve", SignKind::Approval, 0); + approve.run = Some("r-1".into()); + approve.approval = Some(format!( + r#"{{"v":1,"run":"r-1","repo":"Arca","commit":"{}","pipeline":"release","version":"1.0.0","targets":["deploy"],"expires":600}}"#, + "a".repeat(40) + )); + reqs.push(approve); + reqs.push(req("domi-approve", SignKind::Minisign, 64)); for r in &reqs { out += &format!("{:?}", v.signing_check(r)); for approval in [Approval::Mark, Approval::Auto] { @@ -674,6 +848,10 @@ mod tests { } } } + assert!( + v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved), + "an approval was signed too" + ); out += &serde_json::to_string(v.signing_audit()).unwrap(); out += &format!("{:?}", v.signing_audit()); out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3)); diff --git a/crates/custos-vault/tests/signing.rs b/crates/custos-vault/tests/signing.rs index ed11e22..1940461 100644 --- a/crates/custos-vault/tests/signing.rs +++ b/crates/custos-vault/tests/signing.rs @@ -29,6 +29,7 @@ fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context { file: "Arca_0.2.0_x64-setup.exe".into(), size: 25_145_977, sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(), + ..Default::default() } } @@ -38,6 +39,8 @@ fn minisign_req(key: &str, c: Context) -> Request { kind: SignKind::Minisign, digest: vec![7; 64], manifest: None, + approval: None, + run: None, context: c, via: Via::Local, } @@ -49,6 +52,8 @@ fn authenticode_req(key: &str, c: Context) -> Request { kind: SignKind::Authenticode, digest: vec![9; 32], manifest: None, + approval: None, + run: None, context: c, via: Via::Remote, } @@ -61,13 +66,21 @@ fn the_release_and_test_sets_are_made_once_each() { let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect(); assert_eq!( ids, - ["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"] + [ + "domi-release", + "domi-root", + "domi-code-signing", + "domi-approve", + "domi-test", + "domi-test-root", + "domi-test-code-signing" + ] ); assert_eq!(keys[1].kind, KeyKind::RootCa); assert_eq!(keys[2].issuer.as_deref(), Some("domi-root")); - assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root")); - assert!(!keys[0].auto_approve && !keys[2].auto_approve); - assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve); + assert_eq!(keys[6].issuer.as_deref(), Some("domi-test-root")); + assert!(!keys[0].auto_approve && !keys[2].auto_approve && !keys[3].auto_approve); + assert!(keys[4].auto_approve && keys[6].auto_approve && !keys[5].auto_approve); assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key ")); assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release")))); // The root's certificate is exported; a key without one is not. @@ -205,3 +218,177 @@ fn the_audit_log_records_every_outcome_and_survives_a_reopen() { let mut reopened = reopened; assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok()); } + +// ---- deploy approvals (core 0.12.0) ---- + +const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1"; + +fn approval_text(run: &str, repo: &str, expires_in: i64) -> String { + format!( + r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#, + NOW / 1000 + expires_in + ) +} + +fn approval_req(run: &str) -> Request { + Request { + key: "domi-approve".into(), + kind: SignKind::Approval, + digest: vec![], + manifest: None, + approval: Some(approval_text(run, "Arca", 600)), + run: Some(run.into()), + context: Context { + repo: "Arca".into(), + pipeline: "release".into(), + trigger: "tag".into(), + ..Default::default() + }, + via: Via::Remote, + } +} + +#[test] +fn domi_approve_is_made_with_the_release_keys() { + let v = vault_with_keys(); + let keys = v.signing_keys(); + let a = keys.iter().find(|k| k.id == "domi-approve").expect("made with the release set"); + assert_eq!(a.kind, KeyKind::Ed25519); + assert_eq!(a.role, Role::Release); + assert_eq!(a.name, "Domi deploy approval"); + assert!(!a.auto_approve, "it always asks"); + let rel = keys.iter().find(|k| k.id == "domi-release").unwrap(); + assert_eq!((&a.pipelines, &a.repos), (&rel.pipelines, &rel.repos), "the release keys' scope"); + assert!(a.minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key ")); + assert_ne!(a.key_id, rel.key_id); + // The test set has no approval key. + assert!(!keys.iter().any(|k| k.role == Role::Test && k.id.contains("approve"))); +} + +#[test] +fn an_approval_is_signed_by_domi_approve_and_verifies_with_minisign() { + let mut v = vault_with_keys(); + let req = approval_req("r-42"); + v.signing_check_at(&req, NOW).unwrap(); + let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap(); + let text = String::from_utf8(signed.bytes.clone()).unwrap(); + let pubkey = v.signing_keys().into_iter().find(|k| k.id == "domi-approve").unwrap().minisign_public.unwrap(); + let public = minisign_verify::PublicKey::decode(&pubkey).unwrap(); + let sig = minisign_verify::Signature::decode(&text).unwrap(); + public.verify(req.approval.as_deref().unwrap().as_bytes(), &sig, false).unwrap(); + assert_eq!(sig.trusted_comment(), format!("timestamp:{}\tfile:approval-r-42.json\thashed", NOW / 1000)); + assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes)); + + let e = v.signing_audit().last().unwrap(); + assert_eq!((e.key.as_str(), e.kind, e.outcome), ("domi-approve", SignKind::Approval, Outcome::Approved)); + assert_eq!(e.run.as_deref(), Some("r-42")); + assert_eq!(e.context.file, "approval-r-42.json"); + assert_eq!((e.context.commit.as_str(), e.context.version.as_str()), (COMMIT, "0.7.0"), "filled from the JSON"); + assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str())); +} + +#[test] +fn domi_approve_signs_only_approvals_and_approvals_only_with_domi_approve() { + let mut v = vault_with_keys(); + let by_release = Request { key: "domi-release".into(), ..approval_req("r-42") }; + let by_test = Request { key: "domi-test".into(), ..approval_req("r-42") }; + let mut digest = minisign_req("domi-approve", ctx("release", "Arca", "tag")); + digest.run = Some("r-42".into()); + let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64)); + let manifest = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums), ..digest.clone() }; + let authenticode = Request { kind: SignKind::Authenticode, digest: vec![1; 32], ..digest.clone() }; + for r in [&by_release, &by_test, &digest, &manifest, &authenticode] { + assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}"); + assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}"); + } + let code_signing = Request { key: "domi-code-signing".into(), ..approval_req("r-42") }; + assert!(matches!(v.signing_check_at(&code_signing, NOW), Err(Refusal::Invalid(_)))); + // A release key: never without Mark. + assert!(matches!(v.signing_sign(&approval_req("r-42"), Approval::Auto, NOW), Err(Refusal::NeedsApproval(_)))); + assert!(v.signing_audit().iter().all(|e| e.signature.is_none()), "nothing was signed"); +} + +#[test] +fn an_approval_needs_its_run_a_canonical_unexpired_text_and_a_matching_context() { + let mut v = vault_with_keys(); + let invalid = |v: &mut Vault, r: &Request| { + assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}"); + assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}"); + }; + invalid(&mut v, &Request { run: None, ..approval_req("r-42") }); + invalid(&mut v, &Request { run: Some("r-43".into()), ..approval_req("r-42") }); + invalid(&mut v, &Request { approval: None, ..approval_req("r-42") }); + let mut spaced = approval_req("r-42"); + spaced.approval = Some(spaced.approval.unwrap().replace(',', ", ")); + invalid(&mut v, &spaced); + let mut late = approval_req("r-42"); + late.approval = Some(approval_text("r-42", "Arca", 3601)); + invalid(&mut v, &late); + let mut past = approval_req("r-42"); + past.approval = Some(approval_text("r-42", "Arca", 0)); + invalid(&mut v, &past); + let zeros = "0".repeat(40); + for (member, value) in + [("repo", "Fabrica"), ("pipeline", "nightly"), ("commit", zeros.as_str()), ("version", "0.8.0")] + { + let mut r = approval_req("r-42"); + match member { + "repo" => r.context.repo = value.into(), + "pipeline" => r.context.pipeline = value.into(), + "commit" => r.context.commit = value.into(), + _ => r.context.version = value.into(), + } + invalid(&mut v, &r); + } + // The expiry is checked against the time given: valid now, expired ten minutes later. + let ok = approval_req("r-42"); + assert!(v.signing_check_at(&ok, NOW).is_ok()); + assert!(matches!(v.signing_check_at(&ok, NOW + 600_000), Err(Refusal::Invalid(_)))); + assert!(matches!(v.signing_sign(&ok, Approval::Mark, NOW + 600_000), Err(Refusal::Invalid(_)))); +} + +#[test] +fn an_approval_for_a_repo_off_the_list_is_out_of_scope() { + let mut v = vault_with_keys(); + let mut r = approval_req("r-42"); + r.approval = Some(approval_text("r-42", "Custos", 600)); + r.context.repo = "Custos".into(); + assert!(matches!(v.signing_check_at(&r, NOW), Err(Refusal::OutOfScope(_)))); + // The JSON's repo is what counts, even when the context leaves it empty. + r.context.repo = String::new(); + assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_)))); + assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::OutOfScope); +} + +#[test] +fn any_request_may_name_its_run_and_the_audit_keeps_it() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v.custos"); + let mut v = vault_with_keys(); + let mut r = minisign_req("domi-release", ctx("release", "Arca", "tag")); + r.run = Some("r-42".into()); + r.context.version = "0.7.0".into(); + v.signing_sign(&r, Approval::Mark, NOW).unwrap(); + v.signing_refuse(&r, Outcome::Refused, None, NOW + 1); + let mut bad = r.clone(); + bad.run = Some("r 42".into()); + assert!(matches!(v.signing_check_at(&bad, NOW), Err(Refusal::Invalid(_)))); + let mut stray = r.clone(); + stray.approval = Some(approval_text("r-42", "Arca", 600)); + assert!(matches!(v.signing_check_at(&stray, NOW), Err(Refusal::Invalid(_))), "approval text on a digest request"); + v.save(&path).unwrap(); + let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap(); + let a = back.signing_audit(); + assert_eq!(a[0].run.as_deref(), Some("r-42")); + assert_eq!(a[0].context.version, "0.7.0"); + assert_eq!(a[1].run.as_deref(), Some("r-42")); + assert_eq!(back.signing_audit(), v.signing_audit()); +} + +#[test] +fn the_approval_key_is_added_only_to_release_keys_and_only_once() { + let mut empty = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + assert!(matches!(empty.signing_add_approve(NOW), Err(Error::Signing(_))), "no release keys"); + let mut v = vault_with_keys(); + assert!(matches!(v.signing_add_approve(NOW), Err(Error::SigningExists("approval")))); +} diff --git a/docs/SIGNING.md b/docs/SIGNING.md index a7ca408..71981f8 100644 --- a/docs/SIGNING.md +++ b/docs/SIGNING.md @@ -1,4 +1,4 @@ -# Signing keys (core 0.9.0) +# Signing keys (core 0.9.0; deploy approvals 0.12.0) Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and @@ -18,12 +18,16 @@ In the vault body, next to `identity` (FORMAT.md), as the optional member `signi "secret": "", "cert": "", "created": 1793750000000, "pipelines": [], "repos": [] }, { "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing", "secret": "", "cert": "", "issuer": "domi-root", "created": 1793750000000, - "pipelines": ["release"], "repos": ["Arca"] } + "pipelines": ["release"], "repos": ["Arca"] }, + { "id": "domi-approve", "kind": "ed25519", "role": "release", "name": "Domi deploy approval", + "secret": "", "public": "", "keyId": "<16 hex>", "created": 1793750000000, + "pipelines": ["release"], "repos": ["Arca", "Fabrica"] } ], "audit": [ { "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local", "repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag", - "file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "" } + "file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "", + "run": "r-42", "version": "0.1.0" } ] } ``` @@ -39,11 +43,14 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul | `kind` | Key | Signs | Created | | :-- | :-- | :-- | :-- | -| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest` | random | +| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random | | `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random | | `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random | -`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root` and `domi-code-signing`. +`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and +(since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the +release keys' scope. A vault whose release keys were made by an older core gets it with `signing_add_approve` +(*Create approval key*). *Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own `domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is never trusted by Mark's PCs. @@ -69,6 +76,11 @@ A request names a key, a kind and what to sign. Custos never receives the file. | `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) | | `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it | | `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` | +| `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it | + +Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every +request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a +request of another kind is `invalid` too. ### minisign @@ -96,6 +108,40 @@ the whole minisign text. That wrapping is the build's job. sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign` (file name `SHA256SUMS`). A text in any other form is refused, not normalised. +### approval (core 0.12.0) + +A deploy approval says "this run of this commit may deploy to these targets until then". Fabrica's hub checks it with +`domi-approve`'s public key before it runs a deploy step. What is signed is one line of JSON, no spaces, the keys in +exactly this order: + +``` +{"v":1,"run":"r-42","repo":"Arca","commit":"<40 hex>","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":1793000000} +``` + +| Key | | +| :-- | :-- | +| `v` | `1` | +| `run` | `[A-Za-z0-9._-]{1,64}`, equal to the request's `run` | +| `repo`, `pipeline`, `version` | 1–64 of `[A-Za-z0-9._+-]` | +| `commit` | 40 lower-case hex digits | +| `targets` | 1–16 strings of 1–80 characters (Unicode scalar values); no control characters, and none of the invisible ones that change how a line looks on the card (U+00AD, U+061C, U+180E, U+200B–U+200F, U+2028–U+202E, U+2060–U+2069, U+FEFF) | +| `expires` | Unix seconds, later than now and at most 3 600 s after now (checked before the card and again when signing) | + +Strings use JSON's minimal escaping: a quote is written `\"`, a backslash `\\`, every other character as +itself (no `\u` escapes, no `\/`; control characters cannot occur). There is no newline at the end. Custos +parses the text, writes it again in this form and refuses anything that is not byte-identical (`invalid`): another +key order, a space, an escape, a duplicate or unknown key, a number written as `1.0`. + +The signature is a prehashed minisign signature over those bytes, made exactly as for `minisign` with the file name +`approval-.json`, so the trusted comment is `timestamp:\tfile:approval-.json\thashed` +(the `hashed` that minisign itself writes for a prehashed signature). `minisign -V -P -m +approval.json` verifies it. + +`domi-approve` signs only `approval`, and `approval` is signed only by `domi-approve`; it is a release key, so it +always asks. The scope is checked against the JSON's `repo` and `pipeline`; a request whose context names another +`repo`, `pipeline`, `commit` or `version` than its JSON is `invalid` (an empty context member is filled from the JSON +in the audit). The audit entry's `file` is `approval-.json`. + ### authenticode The file is signed by Windows' own tools in three steps, so the key stays in Custos: @@ -124,20 +170,28 @@ one entry, whatever happened: | `refused` | Mark refused | | `expired` | nobody answered within 5 minutes | | `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) | -| `invalid` | the request was malformed (wrong digest length, a manifest not in canonical form, a kind the key cannot do) | +| `invalid` | the request was malformed (wrong digest length, a manifest or approval not in canonical form, an expired approval, a kind the key cannot do) | `signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or -`remote` (the factor service's mailbox). The entry is part of the vault, so it survives a reopen and travels with it. +`remote` (the factor service's mailbox). `run` (core 0.12.0) is the request's run, absent without one; `version` +(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen +and travels with it. + +**Compatibility.** Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind +`approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a +vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later. ## The API (custos-vault) ``` -Vault::signing_create(role, pipelines, repos, now) -> ids // release or test set +Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set +Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0 Vault::signing_keys() -> [SigningKeyView] // public parts only Vault::signing_set_scope(id, pipelines, repos) Vault::signing_export_cert(id) -> DER // a certificate, never a key Vault::signing_minisign_public(id) -> minisign.pub text -Vault::signing_check(&request) -> Ok | Refusal // before asking Mark +Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms) +Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry) Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records Vault::signing_refuse(&request, outcome, now) // records refused / expired Vault::signing_audit() -> [AuditEntry]