//! Signing keys for releases and the audit log of every request (docs/SIGNING.md): the vault body member //! `signing`. A key's secret is used inside this module and never handed out: the public API returns //! public keys, certificates, signatures and audit entries only. use std::fmt; use custos_sign::{Ed25519Secret, RsaSecret}; use serde::{Deserialize, Serialize}; use crate::{Error, SecretBytes, Vault}; /// What a request may be refused with. Every refusal names why, and none carries key material. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Refusal { #[error("there is no signing key `{0}`")] NoKey(String), #[error("{0}")] OutOfScope(String), #[error("{0}")] Invalid(String), #[error("`{0}` is a release key: it signs only after Mark approves")] NeedsApproval(String), } impl Refusal { /// The audit outcome this refusal is recorded as. pub fn outcome(&self) -> Outcome { match self { Refusal::OutOfScope(_) => Outcome::OutOfScope, Refusal::NeedsApproval(_) => Outcome::Refused, Refusal::NoKey(_) | Refusal::Invalid(_) => Outcome::Invalid, } } } /// 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 { Release, Test, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum KeyKind { Ed25519, RootCa, CodeSigning, /// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only. Android, /// A team's cosign key (core 0.18.0, docs/TEAM.md): ECDSA P-256; signs `cosign` only, in a team vault only. EcdsaP256, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SignKind { Minisign, Manifest, Authenticode, /// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0). Approval, /// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only /// (core 0.14.0). Apk, /// Tauri's updater: minisign over a BLAKE2b-512 digest, wrapped in base64 (core 0.18.0, team vaults only). #[serde(rename = "tauri-updater")] TauriUpdater, /// A cosign container image signature: ECDSA P-256 over the simple-signing payload (core 0.18.0, team vaults /// only). Cosign, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Via { Local, Remote, } /// What the build says it is signing. Shown on the card and kept in the audit log; Custos cannot check it /// against the file (docs/SIGNING.md, the wrong-file risk). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct Context { pub repo: String, pub commit: String, pub pipeline: String, pub step: String, /// `manual`, `push` or `tag`. A test key never signs for `tag`. pub trigger: String, 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. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Request { pub key: String, pub kind: SignKind, /// BLAKE2b-512 of the file (minisign), signtool's 32-byte digest (authenticode), or 1 to 4 SHA-512 digests of /// an APK's signed data, concatenated (apk). Empty for a manifest or an approval. 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, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Approval { /// Mark approved this request on the card. Mark, /// Nobody was asked: allowed for test keys only. Auto, /// Nobody was asked: a standing approval Mark granted fits the request (core 0.16.0). Refused when none does. Standing, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Outcome { Approved, /// Signed without asking: a standing approval fitted (core 0.16.0). Standing, Auto, Refused, Expired, OutOfScope, Invalid, } /// One audit entry. Append-only: nothing edits or removes one. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuditEntry { pub at: i64, pub key: String, pub kind: SignKind, pub outcome: Outcome, pub via: Via, #[serde(flatten)] pub context: Context, /// SHA-256 (hex) of what was returned, for signed outcomes. #[serde(default, skip_serializing_if = "Option::is_none")] pub signature: Option, /// 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 team vault's entry (core 0.18.0, docs/TEAM.md): the member whose Custos signed or refused. #[serde(default, skip_serializing_if = "Option::is_none")] pub by: Option, /// The environment the request was for. #[serde(default, skip_serializing_if = "Option::is_none")] pub env: Option, /// The request hash (hex). #[serde(default, skip_serializing_if = "Option::is_none")] pub request: Option, /// The members whose approvals counted. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub approvers: Vec, } /// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used. /// Nothing in it is secret. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StandingRule { /// 16 hex characters: the SHA-256 of repo, key, kind, pipeline and via, joined by newlines, cut short. pub id: String, pub repo: String, pub key: String, /// The key's `created`: a key made later under the same id does not inherit the rule. pub key_created: i64, pub kind: SignKind, pub pipeline: String, pub via: Via, /// For an approval: the deploy targets the rule was granted for. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub targets: Vec, /// Unix milliseconds. pub granted: i64, #[serde(default, skip_serializing_if = "Option::is_none")] pub last_used: Option, #[serde(default)] pub uses: u64, } /// 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 { /// The `.minisig` text (minisign, manifest, approval), the raw RSA signature (authenticode) or the raw RSA /// signatures, concatenated in the order of the digests (apk). pub bytes: Vec, pub sha256: String, } /// A key as the app may see it: public parts only. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct KeyView { pub id: String, pub kind: KeyKind, pub role: Role, pub name: String, pub created: i64, pub pipelines: Vec, pub repos: Vec, /// Test keys are approved automatically (within scope, never for a `tag` trigger). pub auto_approve: bool, /// minisign's key id (hex, as minisign prints it), for Ed25519 keys. pub key_id: Option, /// The `minisign.pub` text, for Ed25519 keys. pub minisign_public: Option, /// The certificate (DER), for root, code-signing and Android keys. pub cert: Option>, pub issuer: Option, /// The `cosign.pub` PEM, for ECDSA P-256 keys (core 0.18.0). pub public_pem: Option, } pub(crate) enum Secret { Ed25519(Ed25519Secret), Rsa(RsaSecret), P256(custos_sign::P256Secret), } pub(crate) struct Key { pub(crate) id: String, pub(crate) kind: KeyKind, pub(crate) role: Role, pub(crate) name: String, pub(crate) secret: Secret, pub(crate) public: Option<[u8; 32]>, pub(crate) key_id: Option<[u8; 8]>, pub(crate) cert: Option>, pub(crate) issuer: Option, pub(crate) created: i64, pub(crate) pipelines: Vec, pub(crate) repos: Vec, } impl fmt::Debug for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Key").field("id", &self.id).field("kind", &self.kind).field("secret", &"[redacted]").finish() } } /// The keys and the log, in the vault. #[derive(Debug, Default)] pub(crate) struct Store { pub(crate) keys: Vec, pub(crate) audit: Vec, standing: Vec, android: Option, } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct KeyJson { id: String, kind: KeyKind, role: Role, name: String, secret: SecretBytes, #[serde(default, skip_serializing_if = "Option::is_none")] public: Option, #[serde(default, skip_serializing_if = "Option::is_none")] key_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] cert: Option, #[serde(default, skip_serializing_if = "Option::is_none")] issuer: Option, created: i64, #[serde(default)] pipelines: Vec, #[serde(default)] repos: Vec, } #[derive(Serialize, Deserialize)] pub(crate) struct StoreJson { #[serde(default)] keys: Vec, #[serde(default)] audit: Vec, /// 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 { data_encoding::BASE64.encode(bytes) } fn unb64(s: &str) -> Option> { data_encoding::BASE64.decode(s.as_bytes()).ok() } fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } fn unhex8(s: &str) -> Option<[u8; 8]> { if s.len() != 16 { return None; } let mut out = [0u8; 8]; for (i, o) in out.iter_mut().enumerate() { *o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?; } Some(out) } impl Store { pub(crate) fn is_empty(&self) -> bool { self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none() } pub(crate) fn from_json(j: StoreJson) -> Option { let mut keys = Vec::new(); for k in j.keys { let secret = match k.kind { KeyKind::Ed25519 => { let seed: [u8; 32] = k.secret.expose().try_into().ok()?; Secret::Ed25519(Ed25519Secret::from_bytes(seed)) } KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => { Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?) } KeyKind::EcdsaP256 => { let scalar: [u8; 32] = k.secret.expose().try_into().ok()?; Secret::P256(custos_sign::P256Secret::from_bytes(scalar).ok()?) } }; let public = match &k.public { Some(p) => Some(unb64(p)?.try_into().ok()?), None => None, }; // The stored public key must be the secret's, as for the identity root. if let (Secret::Ed25519(s), Some(p)) = (&secret, public) { if s.public() != p { return None; } } let key_id = match &k.key_id { Some(h) => Some(unhex8(h)?), None => None, }; let cert = match &k.cert { Some(c) => Some(unb64(c)?), None => None, }; // An Android key is nothing without its certificate: the app is identified by it forever. if k.kind == KeyKind::Android && cert.is_none() { return None; } keys.push(Key { id: k.id, kind: k.kind, role: k.role, name: k.name, secret, public, key_id, cert, issuer: k.issuer, created: k.created, pipelines: k.pipelines, repos: k.repos, }); } if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) { return None; } 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 { if self.is_empty() { return None; } let keys = self .keys .iter() .map(|k| KeyJson { id: k.id.clone(), kind: k.kind, role: k.role, name: k.name.clone(), secret: SecretBytes::new(match &k.secret { Secret::Ed25519(s) => s.expose().to_vec(), Secret::Rsa(s) => s.expose().to_vec(), Secret::P256(s) => s.expose().to_vec(), }), public: k.public.map(|p| b64(&p)), key_id: k.key_id.map(|i| hex(&i)), cert: k.cert.as_ref().map(|c| b64(c)), issuer: k.issuer.clone(), created: k.created, pipelines: k.pipelines.clone(), repos: k.repos.clone(), }) .collect(); Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone(), android: self.android.clone(), }) } pub(crate) fn get(&self, id: &str) -> Option<&Key> { self.keys.iter().find(|k| k.id == id) } } /// Unix seconds from the vault's milliseconds, as minisign and approvals count them. pub(crate) 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(), } } /// What [`Vault::signing_create_android`] makes: the key's id and name, the certificate's subject, its role and /// who may ask. The key is RSA-4096 and the certificate is valid [`custos_sign::ANDROID_YEARS`] years. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AndroidKey { /// `[a-z0-9-]{1,64}`, e.g. `postea-android`; not the id of a key the vault has. pub id: String, pub name: String, /// The certificate's subject: common name, organisation, two-letter country code. pub cn: String, pub o: String, pub c: String, pub role: Role, pub pipelines: Vec, pub repos: Vec, } /// A name in a rule: 1 to 100 characters, no control characters (as a key's scope lists hold them). fn name_ok(x: &str) -> bool { (1..=100).contains(&x.chars().count()) && !x.chars().any(char::is_control) } fn kind_word(kind: SignKind) -> &'static str { match kind { SignKind::Minisign => "minisign", SignKind::Manifest => "manifest", SignKind::Authenticode => "authenticode", SignKind::Approval => "approval", SignKind::Apk => "apk", SignKind::TauriUpdater => "tauri-updater", SignKind::Cosign => "cosign", } } fn via_word(via: Via) -> &'static str { match via { Via::Local => "local", Via::Remote => "remote", } } /// A rule's id: one per repository, key, kind, pipeline and origin. fn rule_id(repo: &str, key: &str, kind: SignKind, pipeline: &str, via: Via) -> String { let joined = [repo, key, kind_word(kind), pipeline, via_word(via)].join("\n"); custos_sign::sha256_hex(joined.as_bytes())[..16].to_string() } /// A stored rule is what [`Vault::standing_grant`] could have written; anything else makes the vault refuse to open. fn rule_ok(r: &StandingRule) -> bool { r.id == rule_id(&r.repo, &r.key, r.kind, &r.pipeline, r.via) && name_ok(&r.repo) && name_ok(&r.pipeline) && (1..=64).contains(&r.key.len()) && (r.via == Via::Local || r.kind == SignKind::Approval) && (r.kind == SignKind::Approval) == !r.targets.is_empty() && r.targets.len() <= 64 && r.targets.iter().all(|t| (1..=80).contains(&t.chars().count()) && !t.chars().any(char::is_control)) } /// What a rule says, for the security audit: names only. fn rule_words(r: &StandingRule) -> String { let targets = if r.targets.is_empty() { String::new() } else { format!(" ({} targets)", r.targets.len()) }; 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) } fn clean_list(list: &[String]) -> Result, Error> { let mut out: Vec = Vec::new(); for x in list.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) { if x.len() > 100 || x.chars().any(char::is_control) { return Err(Error::Signing("a pipeline or repo name is not usable".into())); } if !out.iter().any(|o| o == x) { out.push(x.to_string()); } } Ok(out) } impl Vault { /// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`, /// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys. pub fn signing_create( &mut self, role: Role, pipelines: &[String], repos: &[String], now: i64, ) -> Result, Error> { // An Android key (core 0.14.0) is a key of its own, not part of a set: it never counts as the set. if self.signing.keys.iter().any(|k| k.role == role && k.kind != KeyKind::Android) { return Err(Error::SigningExists(match role { Role::Release => "release", Role::Test => "test", })); } let pipelines = clean_list(pipelines)?; let repos = clean_list(repos)?; let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role { Role::Release => ( "domi-release", "domi-root", "domi-code-signing", "Domi release", "Domi Household Root CA", "Domi Code Signing", ), Role::Test => ( "domi-test", "domi-test-root", "domi-test-code-signing", "Domi test", "Domi Test Root (never trusted)", "Domi Test Code Signing", ), }; let ed = custos_sign::new_ed25519(); let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?; let leaf = custos_sign::new_code_signing(leaf_name, 2, &root.secret, &root.cert_der) .map_err(|e| Error::Signing(e.to_string()))?; let key = |id: &str, kind, name: &str, secret, cert, issuer: Option<&str>, scoped: bool| Key { id: id.into(), kind, role, name: name.into(), secret, public: None, key_id: None, cert, issuer: issuer.map(String::from), created: now, pipelines: if scoped { pipelines.clone() } else { Vec::new() }, repos: if scoped { repos.clone() } else { Vec::new() }, }; let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true); ed_key.public = Some(ed.public); ed_key.key_id = Some(ed.key_id); let root_key = key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false); let leaf_key = key( leaf_id, KeyKind::CodeSigning, leaf_name, Secret::Rsa(leaf.secret), Some(leaf.cert_der), Some(root_id), true, ); self.signing.keys.extend([ed_key, root_key, leaf_key]); 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 && !matches!(k.kind, KeyKind::RootCa | KeyKind::Android)); 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()) } /// Creates an Android app signing key (core 0.14.0): RSA-4096 and a self-signed certificate. A release key /// always asks; a test key signs without asking, never for a `tag`. The caller saves. Slow: one RSA-4096 key. pub fn signing_create_android(&mut self, spec: &AndroidKey, now: i64) -> Result { let id = spec.id.as_str(); if id.is_empty() || id.len() > 64 || !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') { return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into())); } if self.signing.get(id).is_some() { return Err(Error::Signing(format!("there is a key `{id}` already"))); } let name = spec.name.trim(); if name.is_empty() || name.len() > 100 || name.chars().any(char::is_control) { return Err(Error::Signing("the key's name is not usable".into())); } let (pipelines, repos) = (clean_list(&spec.pipelines)?, clean_list(&spec.repos)?); let made = custos_sign::new_android(&spec.cn, &spec.o, &spec.c).map_err(|e| match e { custos_sign::Error::Certificate => Error::Signing( "the certificate's name is not usable (1-64 characters without , + = \" \\ < > ; # and no space at \ either end, and a two-letter country code)" .into(), ), e => Error::Signing(e.to_string()), })?; self.signing.keys.push(Key { id: id.into(), kind: KeyKind::Android, role: spec.role, name: name.into(), secret: Secret::Rsa(made.secret), public: None, key_id: None, cert: Some(made.cert_der), issuer: None, created: now, pipelines, repos, }); Ok(id.into()) } /// Every signing key, public parts only. pub fn signing_keys(&self) -> Vec { self.signing .keys .iter() .map(|k| KeyView { id: k.id.clone(), kind: k.kind, role: k.role, name: k.name.clone(), created: k.created, pipelines: k.pipelines.clone(), repos: k.repos.clone(), auto_approve: k.role == Role::Test && k.kind != KeyKind::RootCa, key_id: k.key_id.map(|i| custos_sign::key_id_hex(&i)), minisign_public: match (k.public, k.key_id) { (Some(p), Some(i)) => Some(custos_sign::minisign_public(&p, &i)), _ => None, }, cert: k.cert.clone(), issuer: k.issuer.clone(), public_pem: match &k.secret { Secret::P256(s) => s.public_pem().ok(), _ => None, }, }) .collect() } /// Changes who may ask for a key. The caller saves. pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> { let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?); let k = self .signing .keys .iter_mut() .find(|k| k.id == id) .ok_or_else(|| Error::Signing(format!("no key `{id}`")))?; if k.kind == KeyKind::RootCa { return Err(Error::Signing("a root CA signs no requests, so it has no scope".into())); } k.pipelines = pipelines; k.repos = repos; Ok(()) } /// A key's certificate (DER): public, for installing the root or giving signtool the leaf. pub fn signing_export_cert(&self, id: &str) -> Result, Error> { let k = self.signing.get(id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?; k.cert.clone().ok_or_else(|| Error::Signing(format!("`{id}` has no certificate"))) } /// 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 25 hours later (`custos_sign::APPROVAL_MAX_AHEAD`). 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 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, (KeyKind::Android, SignKind::Apk) => 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(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())); } SignKind::Authenticode if req.digest.len() != 32 => { return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into())); } SignKind::Apk if req.digest.is_empty() || req.digest.len() % 64 != 0 || req.digest.len() > 64 * custos_sign::MAX_APK_DIGESTS => { return Err(Refusal::Invalid("an APK request is 1 to 4 SHA-512 digests: 64 bytes each".into())); } SignKind::Manifest => { 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 !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())); } // 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, 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))); } 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.check(req, now) { Ok((v, _)) => v, Err(r) => { self.signing_record(req, r.outcome(), Some(r.to_string()), None, now); return Err(r); } }; if approval == Approval::Auto && !view.auto_approve { let r = Refusal::NeedsApproval(req.key.clone()); self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now); return Err(r); } let rule = self.standing_rule_for(req, now).map(|r| r.id); // 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); } let k = self.signing.get(&req.key).expect("checked"); let seconds = seconds(now); let bytes = match (&k.secret, req.kind) { (Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign( s, &k.key_id.expect("ed25519 keys have an id"), &req.digest, &req.context.file, seconds, ) .map(String::into_bytes), (Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest( s, &k.key_id.expect("ed25519 keys have an id"), req.manifest.as_deref().unwrap_or_default(), 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), (Secret::Rsa(s), SignKind::Apk) => custos_sign::apk(s, &req.digest), _ => unreachable!("signing_check matched the key to the kind"), }; let bytes = match bytes { Ok(b) => b, Err(e) => { let r = Refusal::Invalid(e.to_string()); self.signing_record(req, Outcome::Invalid, Some(r.to_string()), None, now); return Err(r); } }; let sha256 = custos_sign::sha256_hex(&bytes); let outcome = match approval { Approval::Auto => Outcome::Auto, Approval::Mark => Outcome::Approved, Approval::Standing => Outcome::Standing, }; self.signing_record(req, outcome, None, Some(sha256.clone()), now); if let (Approval::Standing, Some(id)) = (approval, rule) && let Some(r) = self.signing.standing.iter_mut().find(|r| r.id == id) { 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 }) } /// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves. pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option, now: i64) { let outcome = match outcome { Outcome::Approved | Outcome::Auto | Outcome::Standing => Outcome::Refused, o => o, }; self.signing_record(req, outcome, reason, None, now); } fn signing_record( &mut self, req: &Request, outcome: Outcome, reason: Option, signature: Option, now: i64, ) { let mut context = req.context.clone(); 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, key: req.key.clone(), kind: req.kind, outcome, via: req.via, context, signature, reason, run, by: None, env: None, request: None, approvers: Vec::new(), }); } /// What a rule for `req` would name, when `req` could be signed and may be covered by one at all: the key's /// `created`, the repository and pipeline as the scope check reads them, and an approval's targets. fn standing_shape(&self, req: &Request, now: i64) -> Result<(i64, String, String, Vec), Error> { let no = |why: &str| Error::Signing(why.into()); let (view, approval) = self.check(req, now).map_err(|r| Error::Signing(r.to_string()))?; if req.run.is_none() { return Err(no("a standing approval is for requests that name a run")); } if req.via == Via::Remote && req.kind != SignKind::Approval { return Err(no("a release signature the server runner asks for always needs a card")); } if self.security.is_ticked(crate::security::Item::CardSigning) { return Err(no("Sign only with a card is ticked")); } let (repo, pipeline, targets) = match approval { Some(a) => (a.repo, a.pipeline, a.targets), None => (req.context.repo.clone(), req.context.pipeline.clone(), Vec::new()), }; if !name_ok(&repo) || !name_ok(&pipeline) { return Err(no("the repository or pipeline is not a usable name")); } Ok((view.created, repo, pipeline, targets)) } /// Whether `req`, which Mark is approving on a card, may start a standing approval (docs/SIGNING.md, "Standing /// approvals"); the error says why not, in words for the card. pub fn standing_can_grant(&self, req: &Request, now: i64) -> Result<(), Error> { self.standing_shape(req, now)?; let k = self.signing.get(&req.key).expect("checked"); if k.role != Role::Release { return Err(Error::Signing("a test key signs without asking: it needs no standing approval".into())); } // A key's first signature is never the one that starts a rule. let signed = |e: &AuditEntry| { e.key == k.id && e.at >= k.created && matches!(e.outcome, Outcome::Approved | Outcome::Standing) }; if !self.signing.audit.iter().any(signed) { return Err(Error::Signing(format!( "`{}` has never signed: its first signature needs a card of its own", k.id ))); } Ok(()) } /// Stores the standing approval for `req` (or adds an approval's targets to the one there is) and writes /// `standing-granted` to the security audit. Call it before signing the request Mark approved. The caller saves. pub fn standing_grant(&mut self, req: &Request, now: i64) -> Result { self.standing_can_grant(req, now)?; let (key_created, repo, pipeline, targets) = self.standing_shape(req, now)?; let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via); let at = self.signing.standing.iter().position(|r| r.id == id); // The same combination again keeps its rule (and its count) unless the key under that id is another one. let mut rule = match at.map(|i| self.signing.standing[i].clone()).filter(|r| r.key_created == key_created) { Some(r) => r, None => StandingRule { id, repo, key: req.key.clone(), key_created, kind: req.kind, pipeline, via: req.via, targets: Vec::new(), granted: now, last_used: None, uses: 0, }, }; // Any target Mark sees on this card joins the ones he allowed before. for t in targets { if !rule.targets.contains(&t) { rule.targets.push(t); } } // Never stored in a form this core would refuse to read back; what was there stays as it was. if !rule_ok(&rule) { return Err(Error::Signing("this request cannot be written as a standing approval".into())); } match at { Some(i) => self.signing.standing[i] = rule.clone(), None if self.signing.standing.len() >= STANDING_MAX => { return Err(Error::Signing("there are 256 standing approvals already: revoke one first".into())); } None => self.signing.standing.push(rule.clone()), } self.security.standing_note(crate::security::Action::StandingGranted, &rule_words(&rule), now); Ok(rule) } /// The standing approval `req` fits, if one does: the request passes [`Vault::signing_check_at`], names a run, /// and equals the rule in repository, pipeline, key, kind and origin (an approval: its targets are the rule's). pub fn standing_rule_for(&self, req: &Request, now: i64) -> Option { let (key_created, repo, pipeline, targets) = self.standing_shape(req, now).ok()?; let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via); self.signing .standing .iter() .find(|r| { r.id == id && r.repo == repo && r.key == req.key && r.key_created == key_created && r.kind == req.kind && r.pipeline == pipeline && r.via == req.via && targets.iter().all(|t| r.targets.contains(t)) }) .cloned() } /// The standing approvals, oldest first. pub fn standing_rules(&self) -> Vec { self.signing.standing.clone() } /// Removes a standing approval, audited `standing-revoked`. False when there is none with this id. The caller /// saves. pub fn standing_revoke(&mut self, id: &str, now: i64) -> bool { let Some(i) = self.signing.standing.iter().position(|r| r.id == id) else { return false }; let rule = self.signing.standing.remove(i); self.security.standing_note(crate::security::Action::StandingRevoked, &rule_words(&rule), now); 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 `standing-granted` with `Android grant made for pipeline release`: a value every core since /// 0.16.0 reads, so the phone and the web vault still open the vault (core 0.19.1). 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!("Android grant made {id} for {repo} pipeline {ANDROID_PIPELINE}"); self.security.standing_note(crate::security::Action::StandingGranted, &words, now); Ok(id) } /// Every request any key was named in, oldest first. pub fn signing_audit(&self) -> &[AuditEntry] { &self.signing.audit } } #[cfg(test)] mod tests { //! Mandatory test 2 for the core: no API path returns a private key. It lives here because only this module can //! see the secrets to look for. use super::*; use crate::{KdfParams, SecretString}; fn s(v: &[&str]) -> Vec { v.iter().map(|x| x.to_string()).collect() } fn req(key: &str, kind: SignKind, digest: usize) -> Request { Request { key: key.into(), kind, digest: vec![5; digest], manifest: None, approval: None, run: None, context: Context { repo: "Arca".into(), pipeline: "release".into(), trigger: "tag".into(), file: "a.exe".into(), ..Default::default() }, via: Via::Local, } } #[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 a_key_made_again_under_the_same_id_does_not_inherit_the_rule() { 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(); let r = Request { run: Some("r-1".into()), ..req("domi-release", SignKind::Minisign, 64) }; v.signing_sign(&r, Approval::Mark, 2).unwrap(); v.standing_grant(&r, 3).unwrap(); assert!(v.standing_rule_for(&r, 4).is_some()); // The same id, made at another time (no API does this; a rule must not depend on that). v.signing.keys.iter_mut().find(|k| k.id == "domi-release").unwrap().created = 10; assert!(v.standing_rule_for(&r, 11).is_none(), "the rule names the key it was granted for"); assert!(matches!(v.signing_sign(&r, Approval::Standing, 11), Err(Refusal::NeedsApproval(_)))); // The old key's signatures do not count as the new key's first one either. assert!(v.standing_grant(&r, 12).is_err()); v.signing_sign(&r, Approval::Mark, 13).unwrap(); let again = v.standing_grant(&r, 14).unwrap(); assert_eq!((again.key_created, again.granted, again.uses), (10, 14, 0)); assert_eq!(v.standing_rules().len(), 1); } #[test] fn no_api_path_returns_a_private_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(&["*"]), &s(&["*"]), 1).unwrap(); v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap(); for (id, role) in [("postea-android", Role::Release), ("domi-test-android", Role::Test)] { let spec = AndroidKey { id: id.into(), name: id.into(), cn: "Postea".into(), o: "Marek Novak".into(), c: "CZ".into(), role, pipelines: s(&["*"]), repos: s(&["*"]), }; v.signing_create_android(&spec, 1).unwrap(); } let secrets: Vec> = v .signing .keys .iter() .map(|k| match &k.secret { Secret::Ed25519(s) => s.expose().to_vec(), Secret::Rsa(s) => s.expose().to_vec(), Secret::P256(s) => s.expose().to_vec(), }) .collect(); assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys"); // 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. let mut out = String::new(); let views = v.signing_keys(); out += &serde_json::to_string(&views).unwrap(); out += &format!("{views:?}{:?}", v.signing); for k in &views { if let Ok(c) = v.signing_export_cert(&k.id) { out += &data_encoding::HEXLOWER.encode(&c); } } let mut reqs = 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)); reqs.push(req("postea-android", SignKind::Apk, 128)); reqs.push(req("domi-test-android", SignKind::Apk, 64)); reqs.push(req("postea-android", SignKind::Authenticode, 32)); reqs.push(req("domi-code-signing", SignKind::Apk, 64)); for r in &reqs { out += &format!("{:?}", v.signing_check(r)); for approval in [Approval::Mark, Approval::Auto, Approval::Standing] { match v.signing_sign(r, approval, 2) { Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)), Err(e) => out += &format!("{e:?}{e}"), } // A standing approval for the same request with a run, once the key has signed (core 0.16.0). let with_run = Request { run: r.run.clone().or(Some("r-1".into())), ..r.clone() }; out += &format!("{:?}{:?}", v.standing_can_grant(&with_run, 2), v.standing_grant(&with_run, 2)); out += &format!("{:?}", v.standing_rule_for(&with_run, 2)); } } assert!(v.standing_rules().len() >= 3, "rules were granted: {:?}", v.standing_rules()); out += &serde_json::to_string(&v.standing_rules()).unwrap(); out += &format!("{:?}{:?}", v.standing_rules(), v.security_view(3).audit); assert!( v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved), "an approval was signed too" ); assert!( v.signing_audit() .iter() .any(|e| e.kind == SignKind::Apk && e.key == "postea-android" && e.outcome == Outcome::Approved), "and an APK" ); out += &serde_json::to_string(v.signing_audit()).unwrap(); out += &format!("{:?}", v.signing_audit()); out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3)); for secret in &secrets { for enc in [ data_encoding::HEXLOWER.encode(secret), data_encoding::HEXUPPER.encode(secret), data_encoding::BASE64.encode(secret), data_encoding::BASE64URL_NOPAD.encode(secret), ] { assert!(!out.contains(&enc), "a secret appears in an output"); } } // Partial copies too: every 16-byte window of the numbers that are actually private. (A PKCS#8 RSA key // also holds the public modulus and DER headers, which the certificate rightly shows.) for private in private_parts(&secrets) { for w in private.windows(16).step_by(8) { assert!(!out.contains(&data_encoding::HEXLOWER.encode(w)), "part of a secret appears in an output"); assert!(!out.contains(&data_encoding::BASE64.encode(w)[..20]), "part of a secret appears in an output"); } } } /// Ed25519 seeds as they are; for RSA the private exponent and the primes. fn private_parts(secrets: &[Vec]) -> Vec> { use rsa::pkcs8::DecodePrivateKey; use rsa::traits::PrivateKeyParts; let mut out = Vec::new(); for s in secrets { if s.len() == 32 { out.push(s.clone()); } else { let k = rsa::RsaPrivateKey::from_pkcs8_der(s).unwrap(); out.push(k.d().to_bytes_be()); out.extend(k.primes().iter().map(|p| p.to_bytes_be())); } } assert!(out.len() >= 2 + 4 * 3, "seeds, exponents and primes"); out } }