From 6739423f4d82921a29d5e3250f9bcb68e9ae94b6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 20:45:08 +0100 Subject: [PATCH] [sign] Approval: canonical deploy approvals (parse, rewrite, byte-compare; run, names, commit, targets, expiry within an hour) signed as prehashed minisign approval-.json --- Cargo.lock | 2 + crates/custos-sign/Cargo.toml | 3 + crates/custos-sign/src/lib.rs | 172 +++++++++++++++++++++++ crates/custos-sign/tests/approval.rs | 198 +++++++++++++++++++++++++++ 4 files changed, 375 insertions(+) create mode 100644 crates/custos-sign/tests/approval.rs diff --git a/Cargo.lock b/Cargo.lock index b0245a7..307438f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -418,6 +418,8 @@ dependencies = [ "rand 0.10.3", "rand_core 0.6.4", "rsa", + "serde", + "serde_json", "sha2 0.10.9", "thiserror", "x509-cert", diff --git a/crates/custos-sign/Cargo.toml b/crates/custos-sign/Cargo.toml index db09a50..ee7e412 100644 --- a/crates/custos-sign/Cargo.toml +++ b/crates/custos-sign/Cargo.toml @@ -10,6 +10,9 @@ repository.workspace = true thiserror.workspace = true zeroize.workspace = true data-encoding.workspace = true +# Deploy approvals: parsed, then written again in canonical form and compared. +serde.workspace = true +serde_json.workspace = true # The RustCrypto generation custos-keys already uses (digest 0.10, signature 2). ed25519-dalek = "2" rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] } diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index 156f0e4..3798f0d 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -52,6 +52,8 @@ pub enum Error { BadKey, #[error("the certificate cannot be built or read")] Certificate, + #[error("the approval cannot be signed: {0}")] + Approval(&'static str), } /// An Ed25519 seed. Wiped on drop; never printed. @@ -360,3 +362,173 @@ pub fn cert_pem(der: &[u8]) -> String { pub fn sha256_hex(bytes: &[u8]) -> String { Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() } + +// ---- deploy approvals ---- + +/// The largest approval text Custos reads (docs/SIGNING.md). +pub const MAX_APPROVAL: usize = 8 * 1024; +/// An approval expires at most this many seconds after it is checked. +pub const APPROVAL_MAX_AHEAD: u64 = 3600; + +/// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Approval { + pub run: String, + pub repo: String, + pub commit: String, + pub pipeline: String, + pub version: String, + pub targets: Vec, + /// Unix seconds. + pub expires: u64, +} + +/// The JSON as it is parsed: `v` first, the rest as [`Approval`]. +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct ApprovalJson { + v: u64, + run: String, + repo: String, + commit: String, + pipeline: String, + version: String, + targets: Vec, + expires: u64, +} + +impl Approval { + /// The canonical text (docs/SIGNING.md): one line, no spaces, keys in the fixed order, `"` and `\` escaped, + /// nothing else. Meaningful for an approval that passed [`approval_check`]. + pub fn canonical(&self) -> String { + fn string(out: &mut String, s: &str) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + c => out.push(c), + } + } + out.push('"'); + } + let mut out = String::with_capacity(256); + out.push_str("{\"v\":1,\"run\":"); + string(&mut out, &self.run); + out.push_str(",\"repo\":"); + string(&mut out, &self.repo); + out.push_str(",\"commit\":"); + string(&mut out, &self.commit); + out.push_str(",\"pipeline\":"); + string(&mut out, &self.pipeline); + out.push_str(",\"version\":"); + string(&mut out, &self.version); + out.push_str(",\"targets\":["); + for (i, t) in self.targets.iter().enumerate() { + if i > 0 { + out.push(','); + } + string(&mut out, t); + } + out.push_str("],\"expires\":"); + out.push_str(&self.expires.to_string()); + out.push('}'); + out + } +} + +/// A run id: `[A-Za-z0-9._-]{1,64}`. +pub fn run_id_ok(run: &str) -> bool { + (1..=64).contains(&run.len()) && run.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) +} + +/// `[A-Za-z0-9._+-]{1,64}`: an approval's repo, pipeline and version. +fn name_ok(s: &str) -> bool { + (1..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"._+-".contains(&c)) +} + +/// Characters a target may not hold: control characters, and the invisible ones that change how the rest of the +/// line is shown on the card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen). +fn unprintable(c: char) -> bool { + c.is_control() + || matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}') + || matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}') +} + +/// Checks that `text` is a deploy approval in canonical form that has not expired at `now_secs` and expires at most +/// 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 err = |why: &'static str| Err(Error::Approval(why)); + if text.len() > MAX_APPROVAL { + return err("larger than 8 KiB"); + } + let Ok(j) = serde_json::from_str::(text) else { + return err("not an approval in canonical form"); + }; + if j.v != 1 { + return err("v is not 1"); + } + let a = Approval { + run: j.run, + repo: j.repo, + commit: j.commit, + pipeline: j.pipeline, + version: j.version, + targets: j.targets, + expires: j.expires, + }; + if !run_id_ok(&a.run) { + return err("the run is not a run id ([A-Za-z0-9._-], 1 to 64)"); + } + if !name_ok(&a.repo) { + return err("the repo is not 1 to 64 of [A-Za-z0-9._+-]"); + } + if a.commit.len() != 40 || !a.commit.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) { + return err("the commit is not 40 lower-case hex digits"); + } + if !name_ok(&a.pipeline) { + return err("the pipeline is not 1 to 64 of [A-Za-z0-9._+-]"); + } + if !name_ok(&a.version) { + return err("the version is not 1 to 64 of [A-Za-z0-9._+-]"); + } + if !(1..=16).contains(&a.targets.len()) { + return err("there must be 1 to 16 targets"); + } + for t in &a.targets { + if !(1..=80).contains(&t.chars().count()) { + return err("a target is not 1 to 80 characters"); + } + if t.chars().any(unprintable) { + return err("a target has control or invisible characters"); + } + } + 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) +} + +/// Signs a deploy approval for `run` as prehashed minisign over the text's bytes, file name `approval-.json`. +/// The text is checked with [`approval_check`] at `timestamp` (Unix seconds) and must name `run`. +pub fn approval( + secret: &Ed25519Secret, + key_id: &[u8; 8], + text: &str, + timestamp: u64, + run: &str, +) -> Result { + let a = approval_check(text, timestamp)?; + if a.run != run { + return Err(Error::Approval("the approval's run is not the request's")); + } + minisign(secret, key_id, &blake2b512(text.as_bytes()), &format!("approval-{run}.json"), timestamp) +} diff --git a/crates/custos-sign/tests/approval.rs b/crates/custos-sign/tests/approval.rs new file mode 100644 index 0000000..31eecd8 --- /dev/null +++ b/crates/custos-sign/tests/approval.rs @@ -0,0 +1,198 @@ +//! Deploy approvals (docs/SIGNING.md, "approval"): the canonical form is checked byte for byte, and the signature is +//! a prehashed minisign over the text that minisign-verify (what Tauri and the hub's tools check with) accepts. + +use custos_sign::*; + +const NOW: u64 = 1_793_000_000; +const COMMIT: &str = "3f2a9c1d0e4b5a6978877665544332211aabbccd"; + +/// The doc's example, with an expiry 10 minutes after NOW. +fn canonical() -> String { + format!( + r#"{{"v":1,"run":"r-42","repo":"Arca","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#, + NOW + 600 + ) +} + +fn with(from: &str, to: &str) -> String { + let t = canonical(); + assert!(t.contains(from), "{from:?}"); + t.replacen(from, to, 1) +} + +fn refused(text: &str, now: u64) -> String { + match approval_check(text, now) { + Ok(a) => panic!("accepted {text:?}: {a:?}"), + Err(e) => e.to_string(), + } +} + +#[test] +fn the_canonical_approval_is_accepted_and_reads_back() { + let a = approval_check(&canonical(), NOW).unwrap(); + assert_eq!(a.run, "r-42"); + assert_eq!(a.repo, "Arca"); + assert_eq!(a.commit, COMMIT); + assert_eq!(a.pipeline, "release"); + assert_eq!(a.version, "0.7.0"); + assert_eq!(a.targets, ["deploy to nixos-vm", "publish to Aula"]); + assert_eq!(a.expires, NOW + 600); + assert_eq!(a.canonical(), canonical()); +} + +#[test] +fn reordered_keys_spaces_and_other_shapes_are_refused() { + let t = canonical(); + let reordered = with(r#""run":"r-42","repo":"Arca","#, r#""repo":"Arca","run":"r-42","#); + let bad = [ + reordered, + t.replace(',', ", "), + t.replace(':', ": "), + format!("{t}\n"), + format!(" {t}"), + t.replace("{\"v\"", "{\n\"v\""), + with(r#""v":1,"#, r#""v":1,"x":1,"#), + with(r#""v":1,"#, ""), + with(r#""v":1,"#, r#""v":1,"v":1,"#), + with(r#""v":1,"#, r#""v":2,"#), + with(r#""v":1,"#, r#""v":1.0,"#), + with(r#""v":1,"#, r#""v":"1","#), + format!("[{t}]"), + "not json".to_string(), + String::new(), + ]; + for b in &bad { + refused(b, NOW); + } +} + +#[test] +fn escaping_must_be_minimal() { + // A quote and a backslash in a target are escaped the one way JSON allows; the result is canonical. + let q = with("publish to Aula", r#"say \"hi\" \\ there"#); + assert_eq!(approval_check(&q, NOW).unwrap().targets[1], r#"say "hi" \ there"#); + // Raw non-ASCII is canonical; the same text through \u escapes is not. + let raw = with("publish to Aula", "publikovat na Aulu é"); + assert!(approval_check(&raw, NOW).is_ok()); + for b in [ + with("publish to Aula", r"publikovat na Aulu \u00e9"), + with("publish to Aula", r"publish to \u0041ula"), + with("publish to Aula", r"publish\/to Aula"), + with("r-42", r"r\u002d42"), + ] { + refused(&b, NOW); + } +} + +#[test] +fn a_bad_run_repo_pipeline_or_version_is_refused() { + for run in ["", "r 42", "r/42", "r\\\\42", "ř-42", &"r".repeat(65)] { + let e = refused(&with("\"run\":\"r-42\"", &format!("\"run\":\"{run}\"")), NOW); + assert!(e.contains("run"), "{run:?}: {e}"); + } + let ok_run = "a.B_c-9".to_string() + &"x".repeat(57); + assert_eq!(ok_run.len(), 64); + assert!(approval_check(&with("\"run\":\"r-42\"", &format!("\"run\":\"{ok_run}\"")), NOW).is_ok()); + for (member, value) in [("repo", "Arca"), ("pipeline", "release"), ("version", "0.7.0")] { + let from = format!("\"{member}\":\"{value}\""); + for bad in ["", "a b", "a/b", "a:b", &"a".repeat(65)] { + let e = refused(&with(&from, &format!("\"{member}\":\"{bad}\"")), NOW); + assert!(e.contains(member), "{member} {bad:?}: {e}"); + } + let fine = format!("\"{member}\":\"A.b_c-1+x{}\"", "z".repeat(55)); + assert!(approval_check(&with(&from, &fine), NOW).is_ok(), "{fine}"); + } +} + +#[test] +fn a_bad_commit_is_refused() { + for bad in [COMMIT.to_uppercase(), COMMIT[..39].to_string(), format!("{COMMIT}0"), COMMIT.replace('a', "g")] { + let e = refused(&with(COMMIT, &bad), NOW); + assert!(e.contains("commit"), "{bad}: {e}"); + } +} + +#[test] +fn targets_have_limits() { + let list = |ts: &[String]| ts.iter().map(|t| format!("\"{t}\"")).collect::>().join(","); + let from = r#""targets":["deploy to nixos-vm","publish to Aula"]"#; + let set = |ts: &[String]| with(from, &format!("\"targets\":[{}]", list(ts))); + let n = |k: usize| (0..k).map(|i| format!("deploy to host-{i}")).collect::>(); + + assert!(approval_check(&set(&n(1)), NOW).is_ok()); + assert!(approval_check(&set(&n(16)), NOW).is_ok()); + assert!(approval_check(&set(&["é".repeat(80)]), NOW).is_ok(), "80 characters, not bytes"); + for bad in [ + set(&[]), + set(&n(17)), + set(&[String::new()]), + set(&["x".repeat(81)]), + set(&["tab\\there".to_string()]), + set(&["line\\nbreak".to_string()]), + set(&["nul\\u0000".to_string()]), + set(&["del\u{7f}".to_string()]), + set(&["right-to-left \u{202e}evil".to_string()]), + set(&["zero\u{200b}width".to_string()]), + with(from, r#""targets":"deploy to nixos-vm""#), + with(from, r#""targets":[1]"#), + ] { + let e = refused(&bad, NOW); + assert!(e.contains("target") || e.contains("form"), "{bad}: {e}"); + } +} + +#[test] +fn the_expiry_is_after_now_and_within_an_hour() { + let at = |exp: u64| with(&format!("\"expires\":{}", NOW + 600), &format!("\"expires\":{exp}")); + assert!(approval_check(&at(NOW + 1), NOW).is_ok()); + assert!(approval_check(&at(NOW + 3600), NOW).is_ok()); + for exp in [NOW, NOW - 1, 0, NOW + 3601, u64::MAX] { + let e = refused(&at(exp), NOW); + assert!(e.contains("expire"), "{exp}: {e}"); + } + // The same text expires as time passes. + assert!(refused(&canonical(), NOW + 600).contains("expire")); + for bad in + [format!("\"expires\":{}.0", NOW + 600), format!("\"expires\":-{}", NOW + 600), "\"expires\":\"1\"".into()] + { + refused(&with(&format!("\"expires\":{}", NOW + 600), &bad), NOW); + } +} + +#[test] +fn an_oversized_text_is_refused_before_parsing() { + let huge = with("publish to Aula", &"x".repeat(MAX_APPROVAL)); + assert!(refused(&huge, NOW).contains("larger")); +} + +#[test] +fn the_approval_signature_verifies_with_minisign() { + let k = new_ed25519(); + let text = canonical(); + let sig = approval(&k.secret, &k.key_id, &text, NOW, "r-42").unwrap(); + let public = minisign_verify::PublicKey::decode(&minisign_public(&k.public, &k.key_id)).unwrap(); + let decoded = minisign_verify::Signature::decode(&sig).unwrap(); + public.verify(text.as_bytes(), &decoded, false).unwrap(); + assert!(public.verify(with("Arca", "Fabrica").as_bytes(), &decoded, false).is_err()); + assert_eq!(decoded.trusted_comment(), format!("timestamp:{NOW}\tfile:approval-r-42.json\thashed")); + assert!(sig.ends_with('\n')); +} + +#[test] +fn approval_signs_only_a_valid_text_for_its_own_run() { + let k = new_ed25519(); + let e = approval(&k.secret, &k.key_id, &canonical(), NOW, "r-43").unwrap_err(); + assert!(e.to_string().contains("run"), "{e}"); + assert!(approval(&k.secret, &k.key_id, &format!("{}\n", canonical()), NOW, "r-42").is_err()); + assert!(approval(&k.secret, &k.key_id, &canonical(), NOW + 600, "r-42").is_err(), "expired at signing time"); +} + +#[test] +fn run_ids_follow_the_rule() { + for ok in ["r-42", "setup-1", "a.b_c", &"x".repeat(64)] { + assert!(run_id_ok(ok), "{ok}"); + } + for bad in ["", "a b", "a/b", "ř", &"x".repeat(65)] { + assert!(!run_id_ok(bad), "{bad}"); + } +}