From e533a388839abd8c2f497e806269cb476acecceb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 21 Nov 2026 08:57:48 +0100 Subject: [PATCH] [vault] Signing: the Android grant, one answer for every Domi app's release APK and its key on first use; v0.19.0 signing.android: patterns owner/name or owner/*, the certificate's O and C, uses, last used and the keys it made. A request fits when it is an apk from this PC's pipe with a run, pipeline release, a covered repository, and that repository's own app key (-android, scoped to exactly it and release, role release), while card-signing is not ticked; a key's first signature fits. android_grant_make_key makes that key for a covered repository (android-key-made in the security audit). Granting and revoking write standing-granted and standing-revoked. A vault whose grant made a key needs core 0.19.0; older cores drop the grant itself. --- Cargo.lock | 26 +- Cargo.toml | 2 +- crates/custos-vault/src/security.rs | 28 ++- crates/custos-vault/src/signing.rs | 236 +++++++++++++++++- crates/custos-vault/tests/android_grant.rs | 265 +++++++++++++++++++++ docs/FORMAT.md | 6 +- docs/SIGNING.md | 59 ++++- 7 files changed, 600 insertions(+), 22 deletions(-) create mode 100644 crates/custos-vault/tests/android_grant.rs diff --git a/Cargo.lock b/Cargo.lock index 71e8112..7f3ac9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,14 +329,14 @@ dependencies = [ [[package]] name = "custos-browser" -version = "0.18.1" +version = "0.19.0" dependencies = [ "zeroize", ] [[package]] name = "custos-gen" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-vault", "data-encoding", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.18.1" +version = "0.19.0" dependencies = [ "aes", "argon2", @@ -369,7 +369,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "custos-native" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-browser", "serde_json", @@ -392,11 +392,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.18.1" +version = "0.19.0" [[package]] name = "custos-seal" -version = "0.18.1" +version = "0.19.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -409,7 +409,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.18.1" +version = "0.19.0" dependencies = [ "argon2", "chacha20poly1305", @@ -426,7 +426,7 @@ dependencies = [ [[package]] name = "custos-sign" -version = "0.18.1" +version = "0.19.0" dependencies = [ "blake2 0.10.6", "data-encoding", @@ -446,7 +446,7 @@ dependencies = [ [[package]] name = "custos-team" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-seal", "custos-sign", @@ -464,7 +464,7 @@ dependencies = [ [[package]] name = "custos-totp" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-vault", "data-encoding", @@ -477,7 +477,7 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.18.1" +version = "0.19.0" dependencies = [ "argon2", "bip39", @@ -503,7 +503,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.18.1" +version = "0.19.0" dependencies = [ "custos-qr", "custos-seal", diff --git a/Cargo.toml b/Cargo.toml index 12137c6..e56f242 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.18.1" +version = "0.19.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-vault/src/security.rs b/crates/custos-vault/src/security.rs index b36d8c6..34636ed 100644 --- a/crates/custos-vault/src/security.rs +++ b/crates/custos-vault/src/security.rs @@ -90,6 +90,9 @@ pub enum Action { /// The vault was opened with its recovery key: every factor and the key were replaced (`detail`: the used /// key's id). Written by [`Vault::recover`] only. Recovered, + /// The Android grant made an app's key (core 0.19.0; `detail`: the key's id, its repository and pipeline). + /// Written by [`Vault::android_grant_make_key`] only. + AndroidKeyMade, } /// What *Connect via SSH* needs. @@ -252,7 +255,7 @@ impl State { /// `standing-granted` or `standing-revoked`, with the rule as its detail (cut to what a note may hold). pub(crate) fn standing_note(&mut self, action: Action, detail: &str, now: i64) { - debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked)); + debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked | Action::AndroidKeyMade)); let detail: String = detail.chars().filter(|c| !c.is_control()).take(500).collect(); self.notice_expiry(now); self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail) }); @@ -829,6 +832,29 @@ mod tests { assert_eq!(full.standing_rules()[0].uses, u64::MAX); } + #[test] + fn a_broken_android_grant_makes_the_vault_refuse_to_open() { + let mut v = vault(); + v.android_grant_set(&["mnovak/*".to_string()], "Marek Novak", "CZ", NOW).unwrap(); + let json = body_json(&v); + assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok()); + let from = r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ""#; + assert!(json.contains(from), "{json}"); + for to in [ + r#""repos":["*/*"],"o":"Marek Novak","c":"CZ""#, + r#""repos":["*"],"o":"Marek Novak","c":"CZ""#, + r#""repos":[],"o":"Marek Novak","c":"CZ""#, + r#""repos":["mnovak/*","mnovak/*"],"o":"Marek Novak","c":"CZ""#, + r#""repos":["mnovak/*"],"o":"","c":"CZ""#, + r#""repos":["mnovak/*"],"o":"Marek Novak","c":"Czech""#, + r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ","made":["Not An Id"]"#, + ] { + let bad = json.replacen(from, to, 1); + let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw")); + assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}"); + } + } + #[test] fn a_broken_standing_approval_makes_the_vault_refuse_to_open() { let v = vault_with_a_standing_approval(); diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index 56307dd..0384adf 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -203,6 +203,35 @@ pub struct StandingRule { /// At most this many standing approvals in a vault. pub const STANDING_MAX: usize = 256; +/// The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): Mark's one answer for every Domi app's +/// release APK. It signs an app key's APKs from this PC's pipe, its first signature included, and makes the key when +/// the app's first release asks. Nothing in it is secret. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AndroidGrant { + /// `owner/name` or `owner/*`, 1 to [`ANDROID_PATTERNS_MAX`]. + pub repos: Vec, + /// The organisation and country in the certificates of the keys it makes. + pub o: String, + pub c: String, + /// Unix milliseconds: when Mark granted it, or last changed it. + pub granted: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_used: Option, + #[serde(default)] + pub uses: u64, + /// The ids of the keys it made, oldest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub made: Vec, +} + +/// The one pipeline the Android grant covers. +pub const ANDROID_PIPELINE: &str = "release"; +/// At most this many repository patterns in the Android grant. +pub const ANDROID_PATTERNS_MAX: usize = 64; +/// At most this many keys the Android grant remembers making. +const ANDROID_MADE_MAX: usize = 256; + /// A signature handed back to the build. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Signed { @@ -269,6 +298,7 @@ pub(crate) struct Store { pub(crate) keys: Vec, pub(crate) audit: Vec, standing: Vec, + android: Option, } #[derive(Serialize, Deserialize)] @@ -303,6 +333,9 @@ pub(crate) struct StoreJson { /// Standing approvals (core 0.16.0); absent while there are none. #[serde(default, skip_serializing_if = "Vec::is_empty")] standing: Vec, + /// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it. + #[serde(default, skip_serializing_if = "Option::is_none")] + android: Option, } fn b64(bytes: &[u8]) -> String { @@ -330,7 +363,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> { impl Store { pub(crate) fn is_empty(&self) -> bool { - self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() + self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none() } pub(crate) fn from_json(j: StoreJson) -> Option { @@ -389,7 +422,10 @@ impl Store { if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) { return None; } - Some(Store { keys, audit: j.audit, standing: j.standing }) + if j.android.as_ref().is_some_and(|g| !grant_ok(g)) { + return None; + } + Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android }) } pub(crate) fn json(&self) -> Option { @@ -418,7 +454,12 @@ impl Store { repos: k.repos.clone(), }) .collect(); - Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() }) + Some(StoreJson { + keys, + audit: self.audit.clone(), + standing: self.standing.clone(), + android: self.android.clone(), + }) } pub(crate) fn get(&self, id: &str) -> Option<&Key> { @@ -514,6 +555,64 @@ fn rule_words(r: &StandingRule) -> String { format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via)) } +/// `owner/name`, each 1 to 64 of `A-Z a-z 0-9 . _ -`: the owner and the name, or `None`. +fn repo_parts(repo: &str) -> Option<(&str, &str)> { + let part = + |x: &str| (1..=64).contains(&x.len()) && x.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)); + let (owner, name) = repo.split_once('/')?; + (part(owner) && part(name)).then_some((owner, name)) +} + +/// The app key of a repository (core 0.19.0): `mnovak/Culina` is `culina-android` (the name in lower case, `.` and +/// `_` as `-`); `None` for anything that is not `owner/name` or an id longer than 64. +pub fn android_key_id(repo: &str) -> Option { + let (_, name) = repo_parts(repo)?; + let id: String = name.chars().map(|c| if c == '.' || c == '_' { '-' } else { c.to_ascii_lowercase() }).collect(); + let id = format!("{id}-android"); + (id.len() <= 64).then_some(id) +} + +/// A pattern of the Android grant: `owner/name`, or `owner/*` for every repository of that owner. +fn grant_pattern_ok(p: &str) -> bool { + match p.strip_suffix("/*") { + Some(owner) => repo_parts(&format!("{owner}/x")).is_some(), + None => repo_parts(p).is_some(), + } +} + +fn grant_covers(g: &AndroidGrant, repo: &str) -> bool { + let Some((owner, _)) = repo_parts(repo) else { return false }; + g.repos.iter().any(|p| p == repo || p.strip_suffix("/*") == Some(owner)) +} + +/// The certificate's O (1 to 64, no control characters) and C (two ASCII capitals) for the keys the grant makes. +fn grant_subject_ok(o: &str, c: &str) -> bool { + (1..=64).contains(&o.chars().count()) + && !o.chars().any(char::is_control) + && o.trim() == o + && c.len() == 2 + && c.bytes().all(|b| b.is_ascii_uppercase()) +} + +/// A stored grant is what [`Vault::android_grant_set`] could have written; anything else makes the vault refuse to +/// open. +fn grant_ok(g: &AndroidGrant) -> bool { + let id_ok = |id: &String| { + (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }; + (1..=ANDROID_PATTERNS_MAX).contains(&g.repos.len()) + && g.repos.iter().all(|p| grant_pattern_ok(p)) + && g.repos.iter().enumerate().all(|(i, p)| !g.repos[..i].contains(p)) + && grant_subject_ok(&g.o, &g.c) + && g.made.len() <= ANDROID_MADE_MAX + && g.made.iter().all(id_ok) +} + +/// What the grant says, for the security audit: names only. +fn grant_words(g: &AndroidGrant) -> String { + format!("Android releases: {} pipeline {ANDROID_PIPELINE}, keys made on first use", g.repos.join(", ")) +} + fn in_scope(list: &[String], what: &str) -> bool { list.iter().any(|x| x == "*" || x == what) } @@ -846,7 +945,9 @@ impl Vault { return Err(r); } let rule = self.standing_rule_for(req, now).map(|r| r.id); - if approval == Approval::Standing && rule.is_none() { + // A standing approval first; the Android grant only where none fits (core 0.19.0). + let by_grant = approval == Approval::Standing && rule.is_none() && self.android_grant_fits(req, now); + if approval == Approval::Standing && rule.is_none() && !by_grant { let r = Refusal::NeedsApproval(req.key.clone()); self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now); return Err(r); @@ -902,6 +1003,10 @@ impl Vault { r.uses = r.uses.saturating_add(1); r.last_used = Some(now); } + if by_grant && let Some(g) = self.signing.android.as_mut() { + g.uses = g.uses.saturating_add(1); + g.last_used = Some(now); + } Ok(Signed { bytes, sha256 }) } @@ -1091,6 +1196,129 @@ impl Vault { true } + /// The Android grant, if Mark gave it (core 0.19.0, docs/SIGNING.md "The Android grant"). + pub fn android_grant(&self) -> Option { + self.signing.android.clone() + } + + /// Stores the Android grant, or replaces its patterns and subject (its counts and the keys it made stay), and + /// writes `standing-granted`. Refused while *Sign only with a card* is ticked. Call it only from Mark's own + /// click. The caller saves. + pub fn android_grant_set(&mut self, repos: &[String], o: &str, c: &str, now: i64) -> Result { + if self.security.is_ticked(crate::security::Item::CardSigning) { + return Err(Error::Signing("Sign only with a card is ticked".into())); + } + let mut patterns: Vec = Vec::new(); + for p in repos.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) { + if !grant_pattern_ok(p) { + return Err(Error::Signing(format!( + "`{p}` is not a repository (owner/name) or every repository of an owner (owner/*)" + ))); + } + if !patterns.iter().any(|x| x == p) { + patterns.push(p.to_string()); + } + } + if patterns.is_empty() || patterns.len() > ANDROID_PATTERNS_MAX { + return Err(Error::Signing(format!("the grant names 1 to {ANDROID_PATTERNS_MAX} repositories"))); + } + if !grant_subject_ok(o, c) { + return Err(Error::Signing( + "the certificates need an organisation (1-64 characters) and a two-letter country code".into(), + )); + } + let old = self.signing.android.clone(); + let grant = AndroidGrant { + repos: patterns, + o: o.into(), + c: c.into(), + granted: now, + last_used: old.as_ref().and_then(|g| g.last_used), + uses: old.as_ref().map_or(0, |g| g.uses), + made: old.map(|g| g.made).unwrap_or_default(), + }; + self.security.standing_note(crate::security::Action::StandingGranted, &grant_words(&grant), now); + self.signing.android = Some(grant.clone()); + Ok(grant) + } + + /// Removes the Android grant (`standing-revoked`); the keys it made stay. False when there is none. The caller + /// saves. + pub fn android_grant_revoke(&mut self, now: i64) -> bool { + let Some(g) = self.signing.android.take() else { return false }; + self.security.standing_note(crate::security::Action::StandingRevoked, &grant_words(&g), now); + true + } + + /// Whether `req` is signed by the Android grant: an `apk` from this PC's pipe with a run, in the key's scope, for + /// a repository the grant covers and pipeline `release`, by that repository's own app key (scoped to exactly it + /// and `release`, role release), while *Sign only with a card* is not ticked. A key's first signature fits. + pub fn android_grant_fits(&self, req: &Request, now: i64) -> bool { + let Some(g) = &self.signing.android else { return false }; + let Ok((view, _)) = self.check(req, now) else { return false }; + req.kind == SignKind::Apk + && req.via == Via::Local + && req.run.is_some() + && !self.security.is_ticked(crate::security::Item::CardSigning) + && view.kind == KeyKind::Android + && view.role == Role::Release + && req.context.pipeline == ANDROID_PIPELINE + && grant_covers(g, &req.context.repo) + && android_key_id(&req.context.repo).as_deref() == Some(req.key.as_str()) + && view.repos == [req.context.repo.clone()] + && view.pipelines == [ANDROID_PIPELINE.to_string()] + } + + /// Makes `repo`'s app key under the Android grant, when its first release asks (`custos-sign apk`): the grant + /// covers `repo`, `pipeline` is `release`, `via` is local, *Sign only with a card* is not ticked, and there is + /// no key under that id. RSA-4096, `CN=`, the grant's O and C, scoped to exactly `repo` and `release`. + /// Writes `android-key-made`. The caller saves. Slow: one RSA-4096 key. + pub fn android_grant_make_key(&mut self, repo: &str, pipeline: &str, via: Via, now: i64) -> Result { + let no = |why: String| Err(Error::Signing(why)); + let Some(g) = self.signing.android.clone() else { return no("there is no Android grant".into()) }; + let (Some((_, name)), Some(id)) = (repo_parts(repo), android_key_id(repo)) else { + return no(format!("`{repo}` is not a repository (owner/name)")); + }; + if via != Via::Local { + return no("the server runner never makes a key".into()); + } + if pipeline != ANDROID_PIPELINE { + return no(format!("the Android grant makes keys for the pipeline `{ANDROID_PIPELINE}` only")); + } + if self.security.is_ticked(crate::security::Item::CardSigning) { + return no("Sign only with a card is ticked".into()); + } + if !grant_covers(&g, repo) { + return no(format!("the Android grant does not cover `{repo}`")); + } + if self.signing.get(&id).is_some() { + return no(format!("there is a key `{id}` already")); + } + let mut cn = name.to_string(); + if let Some(first) = cn.get_mut(0..1) { + first.make_ascii_uppercase(); + } + let spec = AndroidKey { + id: id.clone(), + name: format!("{cn} Android"), + cn, + o: g.o.clone(), + c: g.c.clone(), + role: Role::Release, + pipelines: vec![ANDROID_PIPELINE.into()], + repos: vec![repo.into()], + }; + self.signing_create_android(&spec, now)?; + if let Some(g) = self.signing.android.as_mut() + && g.made.len() < ANDROID_MADE_MAX + { + g.made.push(id.clone()); + } + let words = format!("{id} for {repo} pipeline {ANDROID_PIPELINE}"); + self.security.standing_note(crate::security::Action::AndroidKeyMade, &words, now); + Ok(id) + } + /// Every request any key was named in, oldest first. pub fn signing_audit(&self) -> &[AuditEntry] { &self.signing.audit diff --git a/crates/custos-vault/tests/android_grant.rs b/crates/custos-vault/tests/android_grant.rs new file mode 100644 index 0000000..2bb5055 --- /dev/null +++ b/crates/custos-vault/tests/android_grant.rs @@ -0,0 +1,265 @@ +//! The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): one answer for every Domi app's release +//! APK. It signs a request for a repository's own app key (`-android`, scoped to exactly that repository and +//! `release`) from this PC's pipe, its first signature included, and makes that key when the app's first release +//! asks. Everything else still needs a card. + +use custos_vault::security::{Action, Auth, Item}; +use custos_vault::signing::{ + AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via, android_key_id, +}; +use custos_vault::{KdfParams, SecretString, Vault}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +const NOW: i64 = 1_793_750_000_000; +const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1"; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +fn vault() -> Vault { + let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + v.signing_create(Role::Release, &s(&["release"]), &s(&["mnovak/Culina"]), NOW).unwrap(); + v +} + +fn granted(repos: &[&str]) -> Vault { + let mut v = vault(); + v.android_grant_set(&s(repos), "Marek Novak", "CZ", NOW).unwrap(); + v +} + +fn apk(key: &str, repo: &str, pipeline: &str, run: Option<&str>) -> Request { + Request { + key: key.into(), + kind: SignKind::Apk, + digest: vec![5; 64], + manifest: None, + approval: None, + run: run.map(Into::into), + context: Context { + repo: repo.into(), + commit: COMMIT.into(), + pipeline: pipeline.into(), + step: "sign-apk".into(), + trigger: "tag".into(), + file: "Culina-1.2.0.apk".into(), + size: 9_400_000, + sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(), + version: "1.2.0".into(), + }, + via: Via::Local, + } +} + +fn culina(run: &str) -> Request { + apk("culina-android", "mnovak/Culina", "release", Some(run)) +} + +fn notes(v: &Vault, action: Action) -> Vec { + v.security_view(NOW + 1_000) + .audit + .into_iter() + .filter(|e| e.action == action) + .map(|e| e.detail.unwrap_or_default()) + .collect() +} + +#[test] +fn an_app_key_is_named_by_its_repository() { + assert_eq!(android_key_id("mnovak/Culina").as_deref(), Some("culina-android")); + assert_eq!(android_key_id("mnovak/domi-office").as_deref(), Some("domi-office-android")); + assert_eq!(android_key_id("mnovak/Domi.Office_2").as_deref(), Some("domi-office-2-android")); + for bad in ["Culina", "mnovak/", "/Culina", "mnovak/*", "a/b/c", "mnovak/Cu lina", "mnovak/Čulina", ""] { + assert_eq!(android_key_id(bad), None, "{bad}"); + } + assert_eq!(android_key_id(&format!("mnovak/{}", "x".repeat(57))), None, "the id would be longer than 64"); +} + +#[test] +fn the_grant_makes_an_apps_key_and_signs_its_first_apk_without_a_card() { + let mut v = granted(&["mnovak/*"]); + assert!(!v.android_grant_fits(&culina("r-1"), NOW + 1), "no key yet"); + + let id = v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 1).unwrap(); + assert_eq!(id, "culina-android"); + let k = v.signing_keys().into_iter().find(|k| k.id == id).unwrap(); + assert_eq!((k.kind, k.role, k.name.as_str()), (KeyKind::Android, Role::Release, "Culina Android")); + assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&["mnovak/Culina"]))); + let cert = String::from_utf8_lossy(k.cert.as_ref().unwrap()).into_owned(); + assert!(cert.contains("Culina") && cert.contains("Marek Novak"), "the certificate names the app and Mark"); + + // Its first signature: no card, recorded as `standing`, counted on the grant. + assert!(v.android_grant_fits(&culina("r-1"), NOW + 2)); + assert!(v.standing_rule_for(&culina("r-1"), NOW + 2).is_none(), "the grant is not a per-key rule"); + let signed = v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2); + assert!(signed.is_ok(), "{signed:?}"); + assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing); + assert_eq!(v.signing_audit().last().unwrap().context.file, "Culina-1.2.0.apk"); + v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 3).unwrap(); + let g = v.android_grant().unwrap(); + assert_eq!((g.uses, g.last_used, g.made.clone()), (2, Some(NOW + 3), s(&["culina-android"]))); + + assert_eq!(notes(&v, Action::AndroidKeyMade), ["culina-android for mnovak/Culina pipeline release"]); + let granted_note = notes(&v, Action::StandingGranted); + assert_eq!(granted_note.len(), 1); + assert!(granted_note[0].contains("Android releases") && granted_note[0].contains("mnovak/*"), "{granted_note:?}"); + // The public note call cannot write it. + assert!(v.security_note(Action::AndroidKeyMade, "x", NOW).is_err()); +} + +#[test] +fn the_grant_never_makes_a_key_it_does_not_cover() { + let mut v = granted(&["mnovak/Culina", "mnovak/Liber"]); + for (repo, pipeline, via, why) in [ + ("mnovak/Postea", "release", Via::Local, "a repository no pattern matches"), + ("someone/Culina", "release", Via::Local, "another owner"), + ("mnovak/Culina", "ci", Via::Local, "another pipeline"), + ("mnovak/Culina", "release", Via::Remote, "the server runner"), + ("Culina", "release", Via::Local, "not owner/name"), + ] { + assert!(v.android_grant_make_key(repo, pipeline, via, NOW + 1).is_err(), "{why}"); + } + assert!(v.signing_keys().iter().all(|k| k.kind != KeyKind::Android), "nothing was made"); + v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 2).unwrap(); + assert!(v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 3).is_err(), "made once"); + + v.security_tick(Item::CardSigning, NOW + 4); + assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 5).is_err(), "paused"); + v.security_untick(Item::CardSigning, Auth::Hello, NOW + 6); + assert!(v.android_grant_revoke(NOW + 7)); + assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 8).is_err(), "no grant"); + assert_eq!(v.android_grant().map(|g| g.made), None); +} + +#[test] +fn only_the_repositorys_own_app_key_in_its_own_scope_from_this_pc_with_a_run_fits() { + let mut v = granted(&["mnovak/*"]); + v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap(); + // A key of the right name with a wider scope, and one for the wrong repository, made by hand. + let wide = AndroidKey { + id: "liber-android".into(), + name: "Liber Android".into(), + cn: "Liber".into(), + o: "Marek Novak".into(), + c: "CZ".into(), + role: Role::Release, + pipelines: s(&["release"]), + repos: s(&["*"]), + }; + v.signing_create_android(&wide, NOW).unwrap(); + v.signing_create_android( + &AndroidKey { id: "other-android".into(), repos: s(&["mnovak/Rosea"]), ..wide.clone() }, + NOW, + ) + .unwrap(); + v.signing_create_android(&AndroidKey { id: "domi-test-android".into(), role: Role::Test, ..wide.clone() }, NOW) + .unwrap(); + + let mut remote = culina("r-1"); + remote.via = Via::Remote; + let mut minisign = culina("r-1"); + minisign.kind = SignKind::Minisign; + minisign.key = "domi-release".into(); + minisign.digest = vec![7; 64]; + for (req, why) in [ + (remote, "the server runner"), + (apk("culina-android", "mnovak/Culina", "release", None), "no run"), + (apk("liber-android", "mnovak/Liber", "release", Some("r-1")), "a key with a wider scope"), + (apk("other-android", "mnovak/Rosea", "release", Some("r-1")), "not the repository's app key"), + (apk("domi-test-android", "mnovak/Liber", "release", Some("r-1")), "a test key"), + (minisign, "another kind"), + ] { + assert!(!v.android_grant_fits(&req, NOW + 1), "{why}"); + assert!(v.signing_sign(&req, Approval::Standing, NOW + 1).is_err(), "{why}: never signed without a card"); + assert_ne!(v.signing_audit().last().unwrap().outcome, Outcome::Standing, "{why}"); + } + assert_eq!(v.android_grant().unwrap().uses, 0); +} + +#[test] +fn an_explicit_list_covers_only_its_repositories_and_bad_patterns_are_refused() { + let mut v = granted(&["mnovak/Culina"]); + v.signing_create_android( + &AndroidKey { + id: "liber-android".into(), + name: "Liber Android".into(), + cn: "Liber".into(), + o: "Marek Novak".into(), + c: "CZ".into(), + role: Role::Release, + pipelines: s(&["release"]), + repos: s(&["mnovak/Liber"]), + }, + NOW, + ) + .unwrap(); + let liber = apk("liber-android", "mnovak/Liber", "release", Some("r-1")); + assert!(!v.android_grant_fits(&liber, NOW + 1), "not in the list"); + // Editing the list keeps the counts and covers the new repository; a key made by hand in that shape is covered. + v.android_grant_set(&s(&["mnovak/Culina", "mnovak/Liber", "mnovak/Liber"]), "Marek Novak", "CZ", NOW + 2).unwrap(); + assert_eq!(v.android_grant().unwrap().repos, s(&["mnovak/Culina", "mnovak/Liber"])); + assert!(v.android_grant_fits(&liber, NOW + 3)); + + for bad in [&[][..], &["mnovak"], &["*/*"], &["*"], &["mnovak/*/x"], &["mn ovak/*"], &["mnovak/Cu*"]] { + assert!(v.android_grant_set(&s(bad), "Marek Novak", "CZ", NOW + 4).is_err(), "{bad:?}"); + } + let many: Vec = (0..65).map(|i| format!("mnovak/app{i}")).collect(); + assert!(v.android_grant_set(&many, "Marek Novak", "CZ", NOW + 4).is_err(), "at most 64"); + assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "Czech", NOW + 4).is_err(), "a two-letter country"); + assert!(v.android_grant_set(&s(&["mnovak/*"]), "", "CZ", NOW + 4).is_err(), "an organisation"); + assert_eq!( + v.android_grant().unwrap().repos, + s(&["mnovak/Culina", "mnovak/Liber"]), + "a refused edit changes nothing" + ); +} + +#[test] +fn sign_only_with_a_card_pauses_the_grant_and_revoking_ends_it() { + let mut v = granted(&["mnovak/*"]); + v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap(); + v.security_tick(Item::CardSigning, NOW + 1); + assert!(!v.android_grant_fits(&culina("r-1"), NOW + 2)); + assert!(matches!(v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2), Err(Refusal::NeedsApproval(_)))); + assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "CZ", NOW + 2).is_err(), "no grant while ticked"); + assert!(v.android_grant().is_some(), "kept, paused"); + v.security_untick(Item::CardSigning, Auth::Hello, NOW + 3); + assert!(v.android_grant_fits(&culina("r-1"), NOW + 4)); + + assert!(v.android_grant_revoke(NOW + 5)); + assert!(!v.android_grant_revoke(NOW + 6), "once"); + assert!(!v.android_grant_fits(&culina("r-2"), NOW + 7)); + assert!(matches!(v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 7), Err(Refusal::NeedsApproval(_)))); + // Mark still signs it on a card, and the key stays. + assert!(v.signing_sign(&culina("r-2"), Approval::Mark, NOW + 8).is_ok()); + let revoked = notes(&v, Action::StandingRevoked); + assert_eq!(revoked.len(), 1); + assert!(revoked[0].contains("Android releases"), "{revoked:?}"); +} + +#[test] +fn a_standing_rule_for_the_same_request_is_used_first() { + let mut v = granted(&["mnovak/*"]); + v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap(); + v.signing_sign(&culina("r-1"), Approval::Mark, NOW + 1).unwrap(); + v.standing_grant(&culina("r-2"), NOW + 2).unwrap(); + v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).unwrap(); + assert_eq!(v.standing_rules()[0].uses, 1); + assert_eq!(v.android_grant().unwrap().uses, 0); +} + +#[test] +fn the_grant_and_its_counts_survive_a_reopen() { + let mut v = granted(&["mnovak/*", "domi/*"]); + v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap(); + v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 1).unwrap(); + + let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(back.android_grant(), v.android_grant()); + assert!(back.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).is_ok()); + assert_eq!(back.android_grant().unwrap().uses, 2); + assert!(back.android_grant_revoke(NOW + 3)); + let again = Vault::open(&back.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(again.android_grant(), None); +} diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 5c50fe8..4e46719 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -149,7 +149,9 @@ of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault th core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions `standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a -member older cores ignore and drop. +member older cores ignore and drop. Core 0.19.0 adds the member `signing.android` (the Android grant, docs/SIGNING.md "The Android +grant"), which older cores ignore and drop (the grant is lost, never widened), and the `security` action +`android-key-made`: a vault in which the grant made a key does not open in a core before 0.19.0. ### The provision audit (core 0.11.0) @@ -213,7 +215,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos, | `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed | | `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` | | `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo | -| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`, or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters | +| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked` (also for the Android grant), or (core 0.19.0) `android-key-made`, or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters | The **level** is computed, never stored: diff --git a/docs/SIGNING.md b/docs/SIGNING.md index 30ce629..23fdb9c 100644 --- a/docs/SIGNING.md +++ b/docs/SIGNING.md @@ -1,4 +1,4 @@ -# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0) +# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0; the Android grant 0.19.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 @@ -249,6 +249,57 @@ Never covered by a rule, by construction: another repository, key, kind, pipelin key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for; a release signature the server runner asks for; creating a key. +## The Android grant (core 0.19.0) + +A standing approval is one repository's one key, and never a key's first signature. Mark has a dozen Domi apps, each +with its own Android key (`-android`), each new: that is a card to make the key's first signature and another to +store the rule, per app. **The Android grant** is one answer for all of them: "sign my apps' release APKs, and make +each app's key when its first release asks". One grant per vault, in `signing.android`: + +```json +"android": { "repos": ["mnovak/*"], "o": "Marek Novak", "c": "CZ", "granted": 1794000000000, + "lastUsed": 1794100000000, "uses": 3, "made": ["culina-android"] } +``` + +- `repos`: 1 to 64 patterns, each `owner/name` or `owner/*` (every repository of that owner, never another + owner's); owner and name are 1 to 64 of `A-Z a-z 0-9 . _ -`. +- `o`, `c`: the certificate subject's organisation and country for the keys it makes. +- `uses`, `lastUsed`: as on a standing approval. `made`: the ids of the keys it made, oldest first (at most 256). + +**An app's key** is named by its repository: `android_key_id("mnovak/Culina")` is `culina-android` (the name in +lower case, `.` and `_` as `-`). The grant only ever deals in that key, and only when its scope is exactly that +repository and the pipeline `release`, with the role `release`: a key with a wider scope (or `*`) is never the +grant's, and a key the grant did not make but that has this shape (`postea-android`) is covered too. + +**A request fits the grant** (`android_grant_fits`) when all of these hold: + +- `signing_check` passes (scope as always: the grant never widens a key's scope); +- the kind is `apk` and `via` is `local`: an APK the server runner asks for never fits; +- the request names a run; +- the pipeline is `release` and the repository matches one of the patterns; +- the key is that repository's app key, as above; +- `card-signing` (*Sign only with a card*) is not ticked. + +A key's first signature fits too: that is the point of the grant. `signing_sign(req, Approval::Standing, now)` signs +a request that fits a standing approval or the grant (a standing approval first), records the outcome `standing`, +and counts the use on whichever fitted. + +**Making a key** (`android_grant_make_key(repo, pipeline, via, now)`): the grant covers the repository, the +pipeline is `release`, `via` is `local`, `card-signing` is not ticked, and the vault has no key under that id. It +makes the RSA-4096 key with the certificate `CN=` (the repository's name, first letter upper case), `O` and `C` +from the grant, named ` Android`, scoped to exactly that repository and `release`, adds the id to `made`, and +writes `android-key-made` to the security audit (` for pipeline release`). It is a key like any other: +not exportable, removed only as any key is. + +**Granting** (`android_grant_set(repos, o, c, now)`) stores or replaces the grant (the counts and `made` stay) and +writes `standing-granted` with `Android releases: pipeline release, keys made on first use`. It is +refused while `card-signing` is ticked. `android_grant_revoke` removes it (`standing-revoked`). Neither asks +anyone: the app calls them only from Mark's own click. + +Never covered by the grant: another kind, the server runner, a pipeline other than `release`, a repository no pattern +matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card* +is ticked. + ## The audit log `audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets @@ -302,6 +353,12 @@ Vault::standing_grant(&request, now) -> StandingRule // Vault::standing_rule_for(&request, now) -> Option Vault::standing_rules() -> [StandingRule] Vault::standing_revoke(id, now) -> bool +android_key_id(repo) -> Option (core 0.19.0) +Vault::android_grant() -> Option +Vault::android_grant_set(repos, o, c, now) -> Result +Vault::android_grant_revoke(now) -> bool +Vault::android_grant_fits(req, now) -> bool +Vault::android_grant_make_key(repo, pipeline, via, now) -> Result ``` No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test. -- 2.53.0