From e3ede760bd6ede5dea7c7779440266572f36c557 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:38:41 +0100 Subject: [PATCH] [team] Team vaults: member keys, member slots (kind 6), policies per environment, the canonical sign.request, approval statements, policy proofs; cosign and Tauri updater envelopes; v0.18.0 --- CLAUDE.md | 3 + Cargo.lock | 44 +- Cargo.toml | 2 +- crates/custos-sign/Cargo.toml | 2 + crates/custos-sign/src/cosign.rs | 112 +++ crates/custos-sign/src/lib.rs | 12 +- crates/custos-sign/tests/cosign.rs | 91 ++ crates/custos-team/Cargo.toml | 22 + crates/custos-team/src/canon.rs | 54 ++ crates/custos-team/src/external.rs | 34 + crates/custos-team/src/lib.rs | 100 +++ crates/custos-team/src/member.rs | 179 ++++ crates/custos-team/src/policy.rs | 277 ++++++ crates/custos-team/src/proof.rs | 222 +++++ crates/custos-team/src/reply.rs | 46 + crates/custos-team/src/request.rs | 334 +++++++ crates/custos-team/src/statement.rs | 76 ++ crates/custos-team/src/target.rs | 66 ++ crates/custos-team/tests/policy.rs | 186 ++++ crates/custos-team/tests/request.rs | 187 ++++ crates/custos-vault/Cargo.toml | 3 + crates/custos-vault/src/format.rs | 66 ++ crates/custos-vault/src/lib.rs | 72 ++ crates/custos-vault/src/signing.rs | 75 +- crates/custos-vault/src/team.rs | 1285 +++++++++++++++++++++++++++ crates/custos-vault/tests/team.rs | 441 +++++++++ docs/FACTORS.md | 3 + docs/FORMAT.md | 4 + docs/SIGNING.md | 11 +- docs/TEAM.md | 289 ++++++ 30 files changed, 4265 insertions(+), 33 deletions(-) create mode 100644 crates/custos-sign/src/cosign.rs create mode 100644 crates/custos-sign/tests/cosign.rs create mode 100644 crates/custos-team/Cargo.toml create mode 100644 crates/custos-team/src/canon.rs create mode 100644 crates/custos-team/src/external.rs create mode 100644 crates/custos-team/src/lib.rs create mode 100644 crates/custos-team/src/member.rs create mode 100644 crates/custos-team/src/policy.rs create mode 100644 crates/custos-team/src/proof.rs create mode 100644 crates/custos-team/src/reply.rs create mode 100644 crates/custos-team/src/request.rs create mode 100644 crates/custos-team/src/statement.rs create mode 100644 crates/custos-team/src/target.rs create mode 100644 crates/custos-team/tests/policy.rs create mode 100644 crates/custos-team/tests/request.rs create mode 100644 crates/custos-vault/src/team.rs create mode 100644 crates/custos-vault/tests/team.rs create mode 100644 docs/TEAM.md diff --git a/CLAUDE.md b/CLAUDE.md index cd0e037..76686d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,7 @@ crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS# crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing +crates/custos-team team vaults' pure parts: member keys, policy evaluation, sign.request, approval statements, proofs crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli @@ -27,6 +28,8 @@ docs/THREAT_MODEL.md what is and is not protected docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs docs/KDBX.md KeePass files: reading, writing, limits, the item mapping and what does not survive docs/BROWSER.md the browser extension: pieces, matching rule, messages, registration, threat model +docs/SIGNING.md release signing keys, kinds, standing approvals, the audit log +docs/TEAM.md team vaults (member slots, kind 6), policies, sign.request, proofs, cosign and Tauri envelopes ``` ## Commands diff --git a/Cargo.lock b/Cargo.lock index ccd05f0..599793e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,14 +329,14 @@ dependencies = [ [[package]] name = "custos-browser" -version = "0.17.1" +version = "0.18.0" dependencies = [ "zeroize", ] [[package]] name = "custos-gen" -version = "0.17.1" +version = "0.18.0" dependencies = [ "custos-vault", "data-encoding", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.17.1" +version = "0.18.0" dependencies = [ "aes", "argon2", @@ -369,7 +369,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.17.1" +version = "0.18.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "custos-native" -version = "0.17.1" +version = "0.18.0" dependencies = [ "custos-browser", "serde_json", @@ -392,11 +392,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.17.1" +version = "0.18.0" [[package]] name = "custos-seal" -version = "0.17.1" +version = "0.18.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -409,7 +409,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.17.1" +version = "0.18.0" dependencies = [ "argon2", "chacha20poly1305", @@ -426,12 +426,13 @@ dependencies = [ [[package]] name = "custos-sign" -version = "0.17.1" +version = "0.18.0" dependencies = [ "blake2 0.10.6", "data-encoding", "ed25519-dalek", "minisign-verify", + "p256", "rand 0.10.3", "rand_core 0.6.4", "rsa", @@ -443,9 +444,26 @@ dependencies = [ "zeroize", ] +[[package]] +name = "custos-team" +version = "0.18.0" +dependencies = [ + "custos-seal", + "custos-sign", + "data-encoding", + "ed25519-dalek", + "minisign-verify", + "rand 0.10.3", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror", + "zeroize", +] + [[package]] name = "custos-totp" -version = "0.17.1" +version = "0.18.0" dependencies = [ "custos-vault", "data-encoding", @@ -458,12 +476,14 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.17.1" +version = "0.18.0" dependencies = [ "argon2", "bip39", "chacha20poly1305", + "custos-seal", "custos-sign", + "custos-team", "data-encoding", "ed25519-dalek", "hkdf", @@ -482,7 +502,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.17.1" +version = "0.18.0" dependencies = [ "custos-qr", "custos-seal", diff --git a/Cargo.toml b/Cargo.toml index 2e1a92c..29cdb9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.17.1" +version = "0.18.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-sign/Cargo.toml b/crates/custos-sign/Cargo.toml index ee7e412..0836d66 100644 --- a/crates/custos-sign/Cargo.toml +++ b/crates/custos-sign/Cargo.toml @@ -22,6 +22,8 @@ x509-cert = { version = "0.2.5", features = ["builder"] } # rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`). rand_core = "0.6" rand.workspace = true +# cosign container image signatures (core 0.18.0): ECDSA P-256 with SHA-256, RFC 6979 nonces. +p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] } [dev-dependencies] minisign-verify = "0.3" diff --git a/crates/custos-sign/src/cosign.rs b/crates/custos-sign/src/cosign.rs new file mode 100644 index 0000000..68915df --- /dev/null +++ b/crates/custos-sign/src/cosign.rs @@ -0,0 +1,112 @@ +//! Tauri's updater envelope and cosign container image signatures (core 0.18.0, docs/TEAM.md, "Signature +//! envelopes"). + +use std::fmt; + +use data_encoding::BASE64; +use zeroize::Zeroizing; + +use crate::{Error, OsRng06}; + +// ---- Tauri's updater ---- + +/// The content of Tauri's `.sig`: the base64 of the whole minisign signature file. Tauri's `pubkey` is, +/// likewise, the base64 of `minisign.pub`. +pub fn tauri_updater(minisig: &str) -> String { + BASE64.encode(minisig.as_bytes()) +} + +/// The minisign text inside a Tauri `.sig`, or `None` when it is not base64 of UTF-8. +pub fn tauri_updater_open(sig: &str) -> Option { + String::from_utf8(BASE64.decode(sig.trim().as_bytes()).ok()?).ok() +} + +// ---- cosign ---- + +/// An ECDSA P-256 secret scalar. Wiped on drop; never printed. +pub struct P256Secret(Zeroizing<[u8; 32]>); + +impl P256Secret { + /// Refuses bytes that are not a valid scalar (zero, or not below the group order). + pub fn from_bytes(bytes: [u8; 32]) -> Result { + let bytes = Zeroizing::new(bytes); + p256::ecdsa::SigningKey::from_bytes(&(*bytes).into()).map_err(|_| Error::BadKey)?; + Ok(P256Secret(bytes)) + } + + pub fn expose(&self) -> &[u8; 32] { + &self.0 + } + + fn key(&self) -> Result { + p256::ecdsa::SigningKey::from_bytes(&(*self.0).into()).map_err(|_| Error::BadKey) + } + + /// The public key as `cosign.pub` holds it: a PEM `PUBLIC KEY` (SubjectPublicKeyInfo). + pub fn public_pem(&self) -> Result { + use p256::pkcs8::EncodePublicKey; + self.key()?.verifying_key().to_public_key_pem(p256::pkcs8::LineEnding::LF).map_err(|_| Error::BadKey) + } +} + +impl fmt::Debug for P256Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[redacted]") + } +} + +/// A new random P-256 key, from the OS CSPRNG. +pub fn new_p256() -> P256Secret { + let key = p256::ecdsa::SigningKey::random(&mut OsRng06); + let mut bytes = Zeroizing::new([0u8; 32]); + bytes.copy_from_slice(&key.to_bytes()); + P256Secret(bytes) +} + +/// An image reference as cosign's payload names it: the repository, without a tag or digest, 1–255 of +/// `[a-z0-9._/:-]`, starting and ending with a letter or digit, no `//`. +pub fn image_ok(image: &str) -> Result<(), Error> { + let b = image.as_bytes(); + if !(1..=255).contains(&b.len()) { + return Err(Error::Image("not 1 to 255 characters")); + } + if !b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._/:-".contains(c)) { + return Err(Error::Image("only a-z 0-9 . _ / : - (a repository, without @digest)")); + } + if !b[0].is_ascii_alphanumeric() || !b[b.len() - 1].is_ascii_alphanumeric() || image.contains("//") { + return Err(Error::Image("not a repository name")); + } + Ok(()) +} + +/// cosign's simple-signing payload for `image` at the manifest whose SHA-256 is `digest`, exactly as docs/TEAM.md +/// writes it: these keys in this order, no spaces, `"optional":null`. +pub fn cosign_payload(image: &str, digest: &[u8]) -> Result { + let digest: &[u8; 32] = digest.try_into().map_err(|_| Error::DigestLength(32))?; + image_ok(image)?; + let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + Ok(format!( + "{{\"critical\":{{\"identity\":{{\"docker-reference\":\"{image}\"}},\"image\":{{\"docker-manifest-digest\":\"sha256:{hex}\"}},\"type\":\"cosign container image signature\"}},\"optional\":null}}" + )) +} + +/// The ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload`, as `cosign sign` makes it and `cosign verify +/// --key` and `openssl dgst -sha256 -verify` check it. Nonces are RFC 6979's. +pub fn cosign(secret: &P256Secret, payload: &str) -> Result, Error> { + use p256::ecdsa::signature::Signer; + let sig: p256::ecdsa::Signature = secret.key()?.sign(payload.as_bytes()); + Ok(sig.to_der().as_bytes().to_vec()) +} + +/// Checks a cosign signature (DER, as [`cosign`] makes it) over `payload` with a `cosign.pub` PEM. +pub fn cosign_verify(public_pem: &str, payload: &[u8], der: &[u8]) -> bool { + use p256::ecdsa::signature::Verifier; + use p256::pkcs8::DecodePublicKey; + let Ok(key) = p256::ecdsa::VerifyingKey::from_public_key_pem(public_pem) else { + return false; + }; + let Ok(sig) = p256::ecdsa::Signature::from_der(der) else { + return false; + }; + key.verify(payload, &sig).is_ok() +} diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index 3625580..61fac23 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -6,7 +6,10 @@ //! - Authenticode: RSA PKCS#1 v1.5 over the 32-byte digest `signtool sign /dg` writes; //! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3); //! - Android APKs: an RSA-4096 key with a self-signed certificate, signing the SHA-512 digests of the APK -//! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side). +//! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side); +//! - Tauri's updater: the base64 of a minisign signature file (core 0.18.0); +//! - cosign container image signatures (core 0.18.0): ECDSA P-256 over cosign's simple-signing payload, written +//! here from the image and its manifest digest, never taken from the request. //! //! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`. @@ -34,6 +37,11 @@ use x509_cert::spki::SubjectPublicKeyInfoOwned; use x509_cert::time::Validity; use zeroize::Zeroizing; +mod cosign; +pub use cosign::{ + P256Secret, cosign, cosign_payload, cosign_verify, image_ok, new_p256, tauri_updater, tauri_updater_open, +}; + /// Authenticode's code-signing purpose (RFC 5280 id-kp-codeSigning). const CODE_SIGNING: x509_cert::der::oid::ObjectIdentifier = x509_cert::der::oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3"); @@ -64,6 +72,8 @@ pub enum Error { Approval(&'static str), #[error("an APK request is 1 to 4 SHA-512 digests of 64 bytes each")] ApkDigests, + #[error("the image reference is not usable: {0}")] + Image(&'static str), } /// An Ed25519 seed. Wiped on drop; never printed. diff --git a/crates/custos-sign/tests/cosign.rs b/crates/custos-sign/tests/cosign.rs new file mode 100644 index 0000000..9e473da --- /dev/null +++ b/crates/custos-sign/tests/cosign.rs @@ -0,0 +1,91 @@ +//! cosign and the Tauri updater envelope (docs/TEAM.md, "Signature envelopes"; core 0.18.0). +use custos_sign::*; + +#[test] +fn the_cosign_payload_is_written_exactly_as_the_doc_says() { + let p = cosign_payload("gitea.example/team/arca", &[0xab; 32]).unwrap(); + assert_eq!( + p, + "{\"critical\":{\"identity\":{\"docker-reference\":\"gitea.example/team/arca\"},\"image\":{\"docker-manifest-digest\":\"sha256:abababababababababababababababababababababababababababababababab\"},\"type\":\"cosign container image signature\"},\"optional\":null}" + ); + let v: serde_json::Value = serde_json::from_str(&p).unwrap(); + assert_eq!(v["critical"]["type"], "cosign container image signature"); + assert!(v["optional"].is_null()); +} + +#[test] +fn image_references_are_checked() { + for bad in ["", "Arca", "a b", "x@sha256:00", "/a", "a/", "a//b", "a\"b", "a\nb"] { + assert!(cosign_payload(bad, &[0; 32]).is_err(), "{bad:?}"); + } + for good in ["arca", "registry.example:5000/team/app", "ghcr.io/mnovak/custos-share"] { + assert!(cosign_payload(good, &[0; 32]).is_ok(), "{good}"); + } + assert_eq!(cosign_payload("arca", &[0; 31]), Err(Error::DigestLength(32))); +} + +#[test] +fn a_cosign_signature_verifies_and_only_over_its_payload() { + let key = new_p256(); + let pem = key.public_pem().unwrap(); + assert!(pem.starts_with("-----BEGIN PUBLIC KEY-----\n")); + let payload = cosign_payload("arca", &[7; 32]).unwrap(); + let sig = cosign(&key, &payload).unwrap(); + assert!(cosign_verify(&pem, payload.as_bytes(), &sig)); + // RFC 6979: the same key and payload give the same signature. + assert_eq!(sig, cosign(&key, &payload).unwrap()); + let other = cosign_payload("arca", &[8; 32]).unwrap(); + assert!(!cosign_verify(&pem, other.as_bytes(), &sig)); + assert!(!cosign_verify(&new_p256().public_pem().unwrap(), payload.as_bytes(), &sig)); + let again = P256Secret::from_bytes(*key.expose()).unwrap(); + assert_eq!(again.public_pem().unwrap(), pem); + assert_eq!(format!("{key:?}"), "[redacted]"); + assert!(P256Secret::from_bytes([0; 32]).is_err()); + assert!(P256Secret::from_bytes([0xff; 32]).is_err()); +} + +/// The cosign signature against openssl, a standard tool (`openssl dgst -sha256 -verify`, what a cosign +/// signature is underneath). Skipped with a note when openssl is not on PATH. +#[test] +fn openssl_verifies_a_cosign_signature() { + if std::process::Command::new("openssl").arg("version").output().is_err() { + eprintln!("openssl not found: skipped"); + return; + } + let dir = std::env::temp_dir().join(format!("custos-cosign-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let key = new_p256(); + let payload = cosign_payload("registry.example/team/arca", &[3; 32]).unwrap(); + let sig = cosign(&key, &payload).unwrap(); + std::fs::write(dir.join("cosign.pub"), key.public_pem().unwrap()).unwrap(); + std::fs::write(dir.join("payload.json"), &payload).unwrap(); + std::fs::write(dir.join("other.json"), payload.replace("arca", "arcb")).unwrap(); + std::fs::write(dir.join("sig.der"), &sig).unwrap(); + let verify = |file: &str| { + std::process::Command::new("openssl") + .args(["dgst", "-sha256", "-verify", "cosign.pub", "-signature", "sig.der", file]) + .current_dir(&dir) + .output() + .unwrap() + }; + let ok = verify("payload.json"); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stdout)); + assert!(String::from_utf8_lossy(&ok.stdout).contains("Verified OK")); + assert!(!verify("other.json").status.success()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_tauri_envelope_is_base64_of_the_minisign_file_and_tauris_verifier_reads_it() { + let k = new_ed25519(); + let file = b"Arca_0.7.0_x64-setup.exe contents"; + let minisig = minisign(&k.secret, &k.key_id, &blake2b512(file), "Arca_0.7.0_x64-setup.exe", 1_794_000_000).unwrap(); + let sig = tauri_updater(&minisig); + let pubkey = tauri_updater(&minisign_public(&k.public, &k.key_id)); + // What tauri-plugin-updater does: base64-decode both, then minisign-verify. + let pk = minisign_verify::PublicKey::decode(&tauri_updater_open(&pubkey).unwrap()).unwrap(); + let s = minisign_verify::Signature::decode(&tauri_updater_open(&sig).unwrap()).unwrap(); + pk.verify(file, &s, true).unwrap(); + assert!(pk.verify(b"another file", &s, true).is_err()); + assert_eq!(tauri_updater_open("not base64!"), None); +} diff --git a/crates/custos-team/Cargo.toml b/crates/custos-team/Cargo.toml new file mode 100644 index 0000000..6eb63d6 --- /dev/null +++ b/crates/custos-team/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "custos-team" +description = "Custos Domi: team vaults' pure parts (member keys, policy evaluation, the canonical sign.request, approval statements, policy proofs)" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +custos-seal = { path = "../custos-seal" } +custos-sign = { path = "../custos-sign" } +ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] } +sha2.workspace = true +serde.workspace = true +serde_json.workspace = true +data-encoding.workspace = true +zeroize.workspace = true +thiserror.workspace = true +rand.workspace = true + +[dev-dependencies] +minisign-verify = "0.3" diff --git a/crates/custos-team/src/canon.rs b/crates/custos-team/src/canon.rs new file mode 100644 index 0000000..516fc54 --- /dev/null +++ b/crates/custos-team/src/canon.rs @@ -0,0 +1,54 @@ +//! The canonical JSON every signed text here uses (as deploy approvals, SIGNING.md): fixed key order, no spaces, +//! `"` and `\` escaped and nothing else, no newline. Callers only write strings that passed [`text_ok`]. + +/// Appends `s` as a JSON string with minimal escaping. +pub 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('"'); +} + +/// Appends `["a","b"]`. +pub fn strings(out: &mut String, list: &[String]) { + out.push('['); + for (i, s) in list.iter().enumerate() { + if i > 0 { + out.push(','); + } + string(out, s); + } + out.push(']'); +} + +/// Characters a shown text may not hold: control characters, and the invisible ones that change how a line looks +/// on a card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen). +pub 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}') +} + +/// 1..=`max` characters, none of them [`unprintable`]. +pub fn text_ok(s: &str, max: usize) -> bool { + (1..=max).contains(&s.chars().count()) && !s.chars().any(unprintable) +} + +/// `min..=max` bytes, every one ASCII alphanumeric or in `extra`. +pub fn ascii_ok(s: &str, min: usize, max: usize, extra: &[u8]) -> bool { + (min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || extra.contains(&c)) +} + +/// An environment name: `[a-z][a-z0-9-]{0,31}`. +pub fn env_ok(s: &str) -> bool { + let b = s.as_bytes(); + !b.is_empty() + && b.len() <= 32 + && b[0].is_ascii_lowercase() + && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-') +} diff --git a/crates/custos-team/src/external.rs b/crates/custos-team/src/external.rs new file mode 100644 index 0000000..9374c24 --- /dev/null +++ b/crates/custos-team/src/external.rs @@ -0,0 +1,34 @@ +//! The one interface an external signer is reached through (docs/TEAM.md, Authenticode). A hardware token or a +//! cloud signing service holds the private key; Custos approves, then hands the adapter the digest and the +//! credential that lets it ask. Adapters are the app's (I/O); this crate only names the shape. + +use std::fmt; + +/// The credential an adapter uses, borrowed from the team vault for one call. Prints `[redacted]` for `secret`. +pub struct SignerCredential<'a> { + pub id: &'a str, + pub name: &'a str, + /// Which adapter: `command` in this phase. + pub adapter: &'a str, + pub endpoint: &'a str, + pub account: &'a str, + pub secret: &'a str, +} + +impl fmt::Debug for SignerCredential<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SignerCredential") + .field("id", &self.id) + .field("adapter", &self.adapter) + .field("endpoint", &self.endpoint) + .field("secret", &"[redacted]") + .finish_non_exhaustive() + } +} + +/// Signs a 32-byte SHA-256 digest (signtool's `.dig`) with a key Custos never holds: returns the raw signature +/// (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo, as `signtool sign /di` wants it). An error names what failed, +/// never the credential. +pub trait ExternalSigner { + fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result, String>; +} diff --git a/crates/custos-team/src/lib.rs b/crates/custos-team/src/lib.rs new file mode 100644 index 0000000..b9ebf03 --- /dev/null +++ b/crates/custos-team/src/lib.rs @@ -0,0 +1,100 @@ +//! Custos Domi · teams (docs/TEAM.md, core 0.18.0): the pure parts of team vaults and team signing. +//! +//! - [`member`]: a person's member key (X25519 to receive the team key, Ed25519 to sign approvals), the member id, +//! the join code, and sealing the team key to a member; +//! - [`policy`]: one rule per environment, its canonical text, and [`policy::evaluate`]; +//! - [`request`]: the canonical `sign.request` and `target.request`, their hash and match code; +//! - [`statement`]: a member's signed approval of one request; +//! - [`proof`]: the team identity's policy proof, and checking it; +//! - [`reply`]: what goes back to Fabrica, sealed; [`target`]: a released target credential; +//! - [`external`]: the interface an external signer (a hardware token, a cloud signing service) is reached through. +//! +//! No I/O, no clock: every check takes `now` from the caller. Secrets print as `[redacted]`. + +pub mod canon; +pub mod external; +pub mod member; +pub mod policy; +pub mod proof; +pub mod reply; +pub mod request; +pub mod statement; +pub mod target; + +pub use member::{MemberKey, MemberPublic, TeamIdentity}; +pub use policy::{EnvRule, Evaluation, KeyRole, Policy, RosterMember, Verdict, evaluate}; +pub use proof::{Proof, Verified, verify_proof}; +pub use request::{Format, SignRequest, TargetRequest}; +pub use statement::Statement; + +/// How far ahead a request may expire: 25 hours, as deploy approvals (SIGNING.md). +pub const MAX_AHEAD_SECS: u64 = 25 * 3600; +/// How long a signed request's hash is remembered against replay: longer than any request lives. +pub const SEEN_SECS: u64 = 48 * 3600; +/// The most members a team has (member slots in one file). +pub const MAX_MEMBERS: usize = 32; + +/// Why something is refused. None of them carries a key, a credential or a signature. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TeamError { + #[error("not in canonical form: {0}")] + NotCanonical(&'static str), + #[error("{0}")] + Invalid(&'static str), + #[error("the request has expired")] + Expired, + #[error("the match code is not this request's: someone else's request may be waiting, refuse it")] + WrongMatch, + #[error("this request was already answered: a replay is refused")] + Replayed, + #[error("the request is for another team")] + WrongTeam, + #[error("not a member of this team")] + NotAMember, + #[error("a signature does not verify")] + BadSignature, + #[error("the policy has no rule for this environment")] + UnknownEnv, + #[error("the policy cannot be met: {0}")] + Unsatisfiable(&'static str), + #[error("the policy needs {0} more approval(s)")] + NeedMore(u8), + #[error("this member may not approve this request: {0}")] + NotEligible(&'static str), + #[error("the key cannot be read")] + BadKey, +} + +pub(crate) fn hex(b: &[u8]) -> String { + data_encoding::HEXLOWER.encode(b) +} + +pub(crate) fn unhex(s: &str) -> Option<[u8; N]> { + let v = data_encoding::HEXLOWER.decode(s.as_bytes()).ok()?; + v.try_into().ok() +} + +pub(crate) fn b64(b: &[u8]) -> String { + data_encoding::BASE64.encode(b) +} + +pub(crate) fn unb64(s: &str) -> Option> { + data_encoding::BASE64.decode(s.as_bytes()).ok() +} + +pub(crate) fn sha256(b: &[u8]) -> [u8; 32] { + use sha2::Digest; + sha2::Sha256::digest(b).into() +} + +/// 32 lower-case hex digits: a team, member or request id. +pub fn id_ok(s: &str) -> bool { + s.len() == 32 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +/// A random 16-byte id, hex. +pub fn new_id() -> String { + let mut b = [0u8; 16]; + rand::Rng::fill_bytes(&mut rand::rand_core::UnwrapErr(rand::rngs::SysRng), &mut b); + hex(&b) +} diff --git a/crates/custos-team/src/member.rs b/crates/custos-team/src/member.rs new file mode 100644 index 0000000..25cb8d4 --- /dev/null +++ b/crates/custos-team/src/member.rs @@ -0,0 +1,179 @@ +//! A person's member key, the team identity, and sealing the team key to a member (docs/TEAM.md, "The member key", +//! "The team vault file"). + +use std::fmt; + +use custos_seal::Recipient; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use zeroize::Zeroizing; + +use crate::{TeamError, hex, sha256}; + +/// The size of a sealed team key: custos-seal's box around 32 bytes. +pub const SEALED_KEY_LEN: usize = 4 + 32 + 24 + 32 + 16; + +/// The public half of a member key, as the roster and the service keep it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MemberPublic { + pub ed25519: [u8; 32], + pub x25519: [u8; 32], +} + +impl MemberPublic { + /// The member id: the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 ‖ x25519)`, 32 hex. + pub fn id(&self) -> String { + hex(&self.id_bytes()) + } + + pub fn id_bytes(&self) -> [u8; 16] { + let mut m = Vec::with_capacity(16 + 64); + m.extend_from_slice(b"custos member v1"); + m.extend_from_slice(&self.ed25519); + m.extend_from_slice(&self.x25519); + sha256(&m)[..16].try_into().expect("16 bytes") + } + + /// The code a joining member's screen shows and the approving member compares: `match_code(x25519)`. + pub fn join_code(&self) -> String { + custos_seal::match_code(&self.x25519) + } + + /// Both keys must be usable: an Ed25519 point and a contributory X25519 key. + pub fn check(&self) -> Result<(), TeamError> { + VerifyingKey::from_bytes(&self.ed25519).map_err(|_| TeamError::BadKey)?; + custos_seal::seal(&self.x25519, b"check", b"").map_err(|_| TeamError::BadKey)?; + Ok(()) + } + + /// Checks an Ed25519 signature by this member over `msg`. + pub fn verify(&self, msg: &[u8], sig: &[u8; 64]) -> bool { + verify(&self.ed25519, msg, sig) + } +} + +pub(crate) fn verify(public: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> bool { + let Ok(key) = VerifyingKey::from_bytes(public) else { + return false; + }; + key.verify_strict(msg, &Signature::from_bytes(sig)).is_ok() +} + +/// The context a team key is sealed under for one member slot. +pub fn key_context(team: &str, epoch: u32, member: &str) -> Vec { + format!("custos team key v1:{team}:{epoch}:{member}").into_bytes() +} + +/// Seals the 32-byte team key to a member for one team and epoch: the member slot's box ([`SEALED_KEY_LEN`] bytes). +pub fn seal_team_key(team_key: &[u8; 32], to: &MemberPublic, team: &str, epoch: u32) -> Result, TeamError> { + custos_seal::seal(&to.x25519, &key_context(team, epoch, &to.id()), team_key).map_err(|_| TeamError::BadKey) +} + +/// A person's member key. Lives in their own vault; wiped on drop; prints `[redacted]`. +pub struct MemberKey { + x: Recipient, + ed: SigningKey, +} + +impl MemberKey { + /// A new member key from the OS CSPRNG. + pub fn generate() -> MemberKey { + let ed = custos_seal::random_bytes(); + MemberKey { x: Recipient::generate(), ed: SigningKey::from_bytes(&ed) } + } + + /// The key as the member's vault keeps it. + pub fn from_secrets(x25519: Zeroizing<[u8; 32]>, ed25519: Zeroizing<[u8; 32]>) -> Result { + let x = Recipient::from_secret(x25519).map_err(|_| TeamError::BadKey)?; + Ok(MemberKey { x, ed: SigningKey::from_bytes(&ed25519) }) + } + + /// The X25519 secret, for the member's own vault only. + pub fn x25519_secret(&self) -> Zeroizing<[u8; 32]> { + self.x.secret_bytes() + } + + /// The Ed25519 seed, for the member's own vault only. + pub fn ed25519_secret(&self) -> Zeroizing<[u8; 32]> { + Zeroizing::new(self.ed.to_bytes()) + } + + pub fn public(&self) -> MemberPublic { + MemberPublic { ed25519: self.ed.verifying_key().to_bytes(), x25519: self.x.public() } + } + + pub fn id(&self) -> String { + self.public().id() + } + + /// Opens this member's slot of a team vault: the team key. + pub fn open_team_key(&self, sealed: &[u8], team: &str, epoch: u32) -> Result, TeamError> { + let k = self.x.open(sealed, &key_context(team, epoch, &self.id())).map_err(|_| TeamError::NotAMember)?; + let k: [u8; 32] = k.as_slice().try_into().map_err(|_| TeamError::NotAMember)?; + Ok(Zeroizing::new(k)) + } + + /// Signs `msg` with the member's Ed25519 key (approval statements only; the domain is the caller's prefix). + pub(crate) fn sign(&self, msg: &[u8]) -> [u8; 64] { + self.ed.sign(msg).to_bytes() + } + + /// Opens a box sealed to this member's X25519 key (for a joiner: nothing else is ever sealed to it). + pub fn recipient(&self) -> &Recipient { + &self.x + } +} + +impl fmt::Debug for MemberKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[redacted]") + } +} + +/// The team identity: an Ed25519 key in the team body that signs the policy and the proofs, and never rotates. +pub struct TeamIdentity(SigningKey); + +/// Domain prefixes, so a signature of one kind never passes for another. +pub const POLICY_DOMAIN: &[u8] = b"custos team policy v1\0"; +pub const PROOF_DOMAIN: &[u8] = b"custos team proof v1\0"; + +impl TeamIdentity { + pub fn generate() -> TeamIdentity { + TeamIdentity(SigningKey::from_bytes(&custos_seal::random_bytes())) + } + + pub fn from_secret(secret: &[u8; 32]) -> TeamIdentity { + TeamIdentity(SigningKey::from_bytes(secret)) + } + + pub fn secret(&self) -> Zeroizing<[u8; 32]> { + Zeroizing::new(self.0.to_bytes()) + } + + pub fn public(&self) -> [u8; 32] { + self.0.verifying_key().to_bytes() + } + + pub fn sign_policy(&self, text: &str) -> [u8; 64] { + self.0.sign(&[POLICY_DOMAIN, text.as_bytes()].concat()).to_bytes() + } + + pub fn sign_proof(&self, text: &str) -> [u8; 64] { + self.0.sign(&[PROOF_DOMAIN, text.as_bytes()].concat()).to_bytes() + } +} + +impl fmt::Debug for TeamIdentity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[redacted]") + } +} + +/// Checks the team identity's signature on a policy text. +pub fn verify_policy_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool { + verify(identity, &[POLICY_DOMAIN, text.as_bytes()].concat(), sig) +} + +/// Checks the team identity's signature on a proof text. +pub fn verify_proof_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool { + verify(identity, &[PROOF_DOMAIN, text.as_bytes()].concat(), sig) +} diff --git a/crates/custos-team/src/policy.rs b/crates/custos-team/src/policy.rs new file mode 100644 index 0000000..7c0b7c7 --- /dev/null +++ b/crates/custos-team/src/policy.rs @@ -0,0 +1,277 @@ +//! The approval policy: one rule per environment, its canonical text, and its evaluation (docs/TEAM.md, "Policy"). + +use serde::{Deserialize, Serialize}; + +use crate::{TeamError, canon, id_ok}; + +/// One environment's rule. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EnvRule { + pub env: String, + /// How many members must approve: 0 ..= 10. At 0 a test-role key signs without a card. + pub approvals: u8, + /// The approvers must not include the release's author, when the team has 2 or more members. + pub others: bool, + /// Member ids allowed to approve; empty = every member. + pub approvers: Vec, +} + +/// A team's policy. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Policy { + pub team: String, + pub rev: u32, + pub envs: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct PolicyJson { + v: u32, + team: String, + rev: u32, + envs: Vec, +} + +pub const MAX_APPROVALS: u8 = 10; +pub const MAX_ENVS: usize = 8; + +impl Policy { + /// The default (docs/TEAM.md): preview 0, staging 1, production 1 by someone other than the author. + pub fn default_for(team: &str) -> Policy { + let rule = |env: &str, approvals, others| EnvRule { env: env.into(), approvals, others, approvers: vec![] }; + Policy { + team: team.into(), + rev: 1, + envs: vec![rule("preview", 0, false), rule("staging", 1, false), rule("production", 1, true)], + } + } + + pub fn rule(&self, env: &str) -> Option<&EnvRule> { + self.envs.iter().find(|r| r.env == env) + } + + /// The canonical text the team identity signs. + pub fn canonical(&self) -> String { + let mut o = String::with_capacity(256); + o.push_str("{\"v\":1,\"team\":"); + canon::string(&mut o, &self.team); + o.push_str(",\"rev\":"); + o.push_str(&self.rev.to_string()); + o.push_str(",\"envs\":["); + for (i, r) in self.envs.iter().enumerate() { + if i > 0 { + o.push(','); + } + o.push_str("{\"env\":"); + canon::string(&mut o, &r.env); + o.push_str(",\"approvals\":"); + o.push_str(&r.approvals.to_string()); + o.push_str(",\"others\":"); + o.push_str(if r.others { "true" } else { "false" }); + o.push_str(",\"approvers\":"); + canon::strings(&mut o, &r.approvers); + o.push('}'); + } + o.push_str("]}"); + o + } + + /// Every rule as docs/TEAM.md allows it. + pub fn check(&self) -> Result<(), TeamError> { + let bad = |why| Err(TeamError::Invalid(why)); + if !id_ok(&self.team) { + return bad("the policy's team is not an id"); + } + if self.rev == 0 { + return bad("the policy's rev starts at 1"); + } + if self.envs.is_empty() || self.envs.len() > MAX_ENVS { + return bad("a policy has 1 to 8 environments"); + } + for (i, r) in self.envs.iter().enumerate() { + if !canon::env_ok(&r.env) { + return bad("an environment is not [a-z][a-z0-9-]{0,31}"); + } + if self.envs[..i].iter().any(|o| o.env == r.env) { + return bad("an environment is named twice"); + } + if r.approvals > MAX_APPROVALS { + return bad("at most 10 approvals"); + } + if r.approvers.len() > crate::MAX_MEMBERS || !r.approvers.iter().all(|a| id_ok(a)) { + return bad("approvers are member ids"); + } + if r.approvers.iter().enumerate().any(|(j, a)| r.approvers[..j].contains(a)) { + return bad("an approver is named twice"); + } + } + Ok(()) + } + + /// Reads a canonical policy text; anything else is refused, not normalised. + pub fn parse(text: &str) -> Result { + if text.len() > 16 * 1024 { + return Err(TeamError::NotCanonical("a policy is at most 16 KiB")); + } + let j: PolicyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a policy"))?; + if j.v != 1 { + return Err(TeamError::NotCanonical("v is not 1")); + } + let p = Policy { team: j.team, rev: j.rev, envs: j.envs }; + p.check()?; + if p.canonical() != text { + return Err(TeamError::NotCanonical("key order, spaces or escaping")); + } + Ok(p) + } + + /// Replaces (or adds) one environment's rule and raises `rev`. + pub fn set_rule(&mut self, rule: EnvRule) -> Result<(), TeamError> { + let mut next = self.clone(); + match next.envs.iter_mut().find(|r| r.env == rule.env) { + Some(r) => *r = rule, + None => next.envs.push(rule), + } + next.rev = self.rev.checked_add(1).ok_or(TeamError::Invalid("rev overflow"))?; + next.check()?; + *self = next; + Ok(()) + } +} + +/// A member as the policy sees it: who they are and the names Fabrica knows them by. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RosterMember { + pub id: String, + pub name: String, + pub handles: Vec, + pub ed25519: [u8; 32], +} + +impl RosterMember { + /// The member's id, or one of their handles (ASCII case-insensitive), names `author`. + pub fn is(&self, author: &str) -> bool { + !author.is_empty() && (self.id == author || self.handles.iter().any(|h| h.eq_ignore_ascii_case(author))) + } +} + +/// Which kind of key a verdict allows. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum KeyRole { + /// The environment asks for 1+ approvals and they are there: the release keys. + Release, + /// The environment asks for 0: a test-role key, no card. + Test, +} + +impl KeyRole { + pub fn word(self) -> &'static str { + match self { + KeyRole::Release => "release", + KeyRole::Test => "test", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Allowed(KeyRole), + /// This many more eligible approvals are needed. + Need(u8), + /// No set of approvals can ever meet the rule. + Unsatisfiable(&'static str), + UnknownEnv, +} + +/// The verdict and how it was reached. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Evaluation { + pub verdict: Verdict, + /// Members who may approve this request. + pub eligible: Vec, + /// The approvals that counted, distinct, in the order given. + pub counted: Vec, + /// Approvals that did not count: not on the roster, not eligible (the author, not an approver), a repeat. + pub ignored: Vec, +} + +impl Evaluation { + pub fn into_result(self) -> Result { + match self.verdict { + Verdict::Allowed(r) => Ok(r), + Verdict::Need(n) => Err(TeamError::NeedMore(n)), + Verdict::Unsatisfiable(w) => Err(TeamError::Unsatisfiable(w)), + Verdict::UnknownEnv => Err(TeamError::UnknownEnv), + } + } +} + +/// Who may approve a request for `env` by `author`. +pub fn eligible(policy: &Policy, roster: &[RosterMember], env: &str, author: &str) -> Option> { + let rule = policy.rule(env)?; + let others = rule.others && roster.len() >= 2; + Some( + roster + .iter() + .filter(|m| rule.approvers.is_empty() || rule.approvers.contains(&m.id)) + .filter(|m| !(others && m.is(author))) + .map(|m| m.id.clone()) + .collect(), + ) +} + +/// Evaluates the policy for one request (docs/TEAM.md, "Evaluation"). `approvers` are member ids whose approval +/// statements were already checked. +pub fn evaluate(policy: &Policy, roster: &[RosterMember], env: &str, author: &str, approvers: &[String]) -> Evaluation { + let Some(rule) = policy.rule(env) else { + return Evaluation { verdict: Verdict::UnknownEnv, eligible: vec![], counted: vec![], ignored: approvers.to_vec() }; + }; + let eligible = eligible(policy, roster, env, author).unwrap_or_default(); + let mut counted: Vec = Vec::new(); + let mut ignored = Vec::new(); + for a in approvers { + if eligible.contains(a) && !counted.contains(a) { + counted.push(a.clone()); + } else { + ignored.push(a.clone()); + } + } + let verdict = if rule.approvals == 0 { + Verdict::Allowed(KeyRole::Test) + } else if counted.len() >= rule.approvals as usize { + Verdict::Allowed(KeyRole::Release) + } else if eligible.len() < rule.approvals as usize { + Verdict::Unsatisfiable(if rule.others && roster.len() >= 2 && eligible.is_empty() { + "only the author may approve, and the rule needs someone else" + } else { + "the rule needs more approvals than there are members who may give them" + }) + } else { + Verdict::Need(rule.approvals - counted.len() as u8) + }; + Evaluation { verdict, eligible, counted, ignored } +} + +/// Why `member` may not approve this request, or `Ok`. +pub fn may_approve( + policy: &Policy, + roster: &[RosterMember], + env: &str, + author: &str, + member: &str, +) -> Result<(), TeamError> { + let rule = policy.rule(env).ok_or(TeamError::UnknownEnv)?; + let Some(me) = roster.iter().find(|m| m.id == member) else { + return Err(TeamError::NotAMember); + }; + if !rule.approvers.is_empty() && !rule.approvers.contains(&me.id) { + return Err(TeamError::NotEligible("not on this environment's approver list")); + } + if rule.others && roster.len() >= 2 && me.is(author) { + return Err(TeamError::NotEligible("the release's author may not approve it here")); + } + Ok(()) +} diff --git a/crates/custos-team/src/proof.rs b/crates/custos-team/src/proof.rs new file mode 100644 index 0000000..c84d9e7 --- /dev/null +++ b/crates/custos-team/src/proof.rs @@ -0,0 +1,222 @@ +//! The policy proof (docs/TEAM.md, "The policy proof"): signed by the team identity, it says which request was +//! signed under which policy, with whose approvals, by whom, and over which envelope. Anyone who pinned the team +//! identity checks it with [`verify_proof`], which accepts only what the signing Custos itself would have signed. + +use serde::{Deserialize, Serialize}; + +use crate::member::{TeamIdentity, verify_policy_sig, verify_proof_sig}; +use crate::policy::{KeyRole, Policy, RosterMember, evaluate}; +use crate::request::SignRequest; +use crate::statement::{Statement, verified_members}; +use crate::{TeamError, b64, canon, hex, sha256, unb64, unhex}; + +/// The proof as it travels: its canonical text and the team identity's signature over it (base64). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Proof { + pub text: String, + pub sig: String, +} + +/// A roster member as a proof lists them. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct RosterJson { + id: String, + name: String, + handles: Vec, + ed25519: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BodyJson { + v: u32, + team: String, + request: String, + env: String, + author: String, + policy: String, + policy_sig: String, + roster: Vec, + approvals: Vec, + signer: String, + role: KeyRole, + signature: String, + at: u64, +} + +/// What a proof says, as the team's Custos builds it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProofBody { + pub team: String, + /// The request hash (hex). + pub request: String, + pub env: String, + pub author: String, + pub policy: String, + pub policy_sig: [u8; 64], + pub roster: Vec, + pub approvals: Vec, + pub signer: String, + pub role: KeyRole, + /// SHA-256 (hex) of the envelope that was returned. + pub signature: String, + pub at: u64, +} + +impl ProofBody { + pub fn canonical(&self) -> String { + let mut o = String::with_capacity(1024); + o.push_str("{\"v\":1,\"team\":"); + canon::string(&mut o, &self.team); + o.push_str(",\"request\":"); + canon::string(&mut o, &self.request); + o.push_str(",\"env\":"); + canon::string(&mut o, &self.env); + o.push_str(",\"author\":"); + canon::string(&mut o, &self.author); + o.push_str(",\"policy\":"); + canon::string(&mut o, &self.policy); + o.push_str(",\"policy_sig\":"); + canon::string(&mut o, &b64(&self.policy_sig)); + o.push_str(",\"roster\":["); + for (i, m) in self.roster.iter().enumerate() { + if i > 0 { + o.push(','); + } + o.push_str("{\"id\":"); + canon::string(&mut o, &m.id); + o.push_str(",\"name\":"); + canon::string(&mut o, &m.name); + o.push_str(",\"handles\":"); + canon::strings(&mut o, &m.handles); + o.push_str(",\"ed25519\":"); + canon::string(&mut o, &hex(&m.ed25519)); + o.push('}'); + } + o.push_str("],\"approvals\":["); + for (i, s) in self.approvals.iter().enumerate() { + if i > 0 { + o.push(','); + } + o.push_str("{\"member\":"); + canon::string(&mut o, &s.member); + o.push_str(",\"code\":"); + canon::string(&mut o, &s.code); + o.push_str(",\"at\":"); + o.push_str(&s.at.to_string()); + o.push_str(",\"sig\":"); + canon::string(&mut o, &s.sig); + o.push('}'); + } + o.push_str("],\"signer\":"); + canon::string(&mut o, &self.signer); + o.push_str(",\"role\":"); + canon::string(&mut o, self.role.word()); + o.push_str(",\"signature\":"); + canon::string(&mut o, &self.signature); + o.push_str(",\"at\":"); + o.push_str(&self.at.to_string()); + o.push('}'); + o + } + + /// Signed by the team identity. + pub fn sign(&self, identity: &TeamIdentity) -> Proof { + let text = self.canonical(); + let sig = identity.sign_proof(&text); + Proof { text, sig: b64(&sig) } + } + + pub fn parse(text: &str) -> Result { + if text.len() > 64 * 1024 { + return Err(TeamError::NotCanonical("a proof is at most 64 KiB")); + } + let j: BodyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a proof"))?; + if j.v != 1 { + return Err(TeamError::NotCanonical("v is not 1")); + } + let mut roster = Vec::new(); + for m in j.roster { + let ed25519 = unhex::<32>(&m.ed25519).ok_or(TeamError::Invalid("a roster key is not 64 hex"))?; + roster.push(RosterMember { id: m.id, name: m.name, handles: m.handles, ed25519 }); + } + let body = ProofBody { + team: j.team, + request: j.request, + env: j.env, + author: j.author, + policy: j.policy, + policy_sig: unb64(&j.policy_sig) + .and_then(|s| s.try_into().ok()) + .ok_or(TeamError::Invalid("policy_sig is not base64 of 64 bytes"))?, + roster, + approvals: j.approvals, + signer: j.signer, + role: j.role, + signature: j.signature, + at: j.at, + }; + if body.canonical() != text { + return Err(TeamError::NotCanonical("key order, spaces or escaping")); + } + Ok(body) + } +} + +/// What a proof established. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verified { + pub role: KeyRole, + pub env: String, + pub signer: String, + /// The approvals that counted under the policy. + pub approvers: Vec, + pub policy_rev: u32, +} + +/// Checks a proof against the pinned team identity, the request it was made for and the envelope that came back +/// with it: both signatures, every approval (signature, roster, the request's own match code), the request and +/// envelope hashes, and the policy evaluated again. The clock is not consulted: a proof stays checkable after its +/// request expired. +pub fn verify_proof(proof: &Proof, identity: &[u8; 32], request_text: &str, envelope: &[u8]) -> Result { + let sig: [u8; 64] = unb64(&proof.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?; + if !verify_proof_sig(identity, &proof.text, &sig) { + return Err(TeamError::BadSignature); + } + let body = ProofBody::parse(&proof.text)?; + let req = SignRequest::parse(request_text)?; + if body.request != req.hash_hex() { + return Err(TeamError::Invalid("the proof is for another request")); + } + if body.team != req.team || body.env != req.env || body.author != req.author { + return Err(TeamError::Invalid("the proof does not match the request's team, env or author")); + } + if body.signature != hex(&sha256(envelope)) { + return Err(TeamError::Invalid("the proof is for another signature")); + } + if !verify_policy_sig(identity, &body.policy, &body.policy_sig) { + return Err(TeamError::BadSignature); + } + let policy = Policy::parse(&body.policy)?; + if policy.team != body.team { + return Err(TeamError::WrongTeam); + } + if !body.roster.iter().any(|m| m.id == body.signer) { + return Err(TeamError::NotAMember); + } + for s in &body.approvals { + s.verify(&req, &body.roster)?; + } + let approvers = verified_members(&body.approvals, &req, &body.roster); + let eval = evaluate(&policy, &body.roster, &req.env, &req.author, &approvers); + let role = eval.clone().into_result()?; + if role != body.role { + return Err(TeamError::Invalid("the proof's key role is not what the policy gives")); + } + if role == KeyRole::Release && !eval.counted.contains(&body.signer) { + return Err(TeamError::Invalid("the signer's own approval is not among those that counted")); + } + Ok(Verified { role, env: body.env, signer: body.signer, approvers: eval.counted, policy_rev: policy.rev }) +} diff --git a/crates/custos-team/src/reply.rs b/crates/custos-team/src/reply.rs new file mode 100644 index 0000000..1ad0bf9 --- /dev/null +++ b/crates/custos-team/src/reply.rs @@ -0,0 +1,46 @@ +//! What goes back to Fabrica, sealed to the request's `pub` (docs/TEAM.md, "The reply"). + +use serde::{Deserialize, Serialize}; + +use crate::proof::Proof; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReplyKey { + pub id: String, + /// `minisign.pub` text, `cosign.pub` PEM, or a certificate PEM. + pub public: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReplySigner { + pub member: String, + pub name: String, +} + +/// `sign.reply` v1. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignReply { + pub v: u32, + pub op: String, + /// The request hash (hex). + pub request: String, + pub format: String, + /// The envelope (docs/TEAM.md, "Signature envelopes"). + pub signature: String, + /// cosign only: the payload that was signed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub payload: Option, + pub key: ReplyKey, + pub signer: ReplySigner, + pub proof: Proof, +} + +impl SignReply { + /// The bytes the proof's `signature` hashes: the envelope as text. + pub fn envelope(&self) -> &[u8] { + self.signature.as_bytes() + } +} diff --git a/crates/custos-team/src/request.rs b/crates/custos-team/src/request.rs new file mode 100644 index 0000000..f8f2bc0 --- /dev/null +++ b/crates/custos-team/src/request.rs @@ -0,0 +1,334 @@ +//! The canonical `sign.request` and `target.request` (docs/TEAM.md, "The signing request"). Parsed, written again +//! in canonical form and compared byte for byte: any other spelling is refused, not normalised. + +use serde::Deserialize; + +use crate::{MAX_AHEAD_SECS, TeamError, b64, canon, hex, id_ok, sha256, unb64}; + +/// The largest request text read. +pub const MAX_REQUEST: usize = 4 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Format { + Minisign, + TauriUpdater, + Apk, + Cosign, + Authenticode, +} + +impl Format { + pub fn word(self) -> &'static str { + match self { + Format::Minisign => "minisign", + Format::TauriUpdater => "tauri-updater", + Format::Apk => "apk", + Format::Cosign => "cosign", + Format::Authenticode => "authenticode", + } + } + + pub fn from_word(w: &str) -> Option { + Some(match w { + "minisign" => Format::Minisign, + "tauri-updater" => Format::TauriUpdater, + "apk" => Format::Apk, + "cosign" => Format::Cosign, + "authenticode" => Format::Authenticode, + _ => return None, + }) + } + + /// Whether `digest` has this format's length (docs/TEAM.md, `artifact_digest`). + pub fn digest_ok(self, digest: &[u8]) -> bool { + match self { + Format::Minisign | Format::TauriUpdater => digest.len() == 64, + Format::Apk => !digest.is_empty() && digest.len() % 64 == 0 && digest.len() <= 64 * 4, + Format::Cosign | Format::Authenticode => digest.len() == 32, + } + } +} + +/// What the build claims about the file; shown on the card. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Artifact { + pub name: String, + pub size: u64, + pub sha256: String, +} + +/// A checked `sign.request`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SignRequest { + pub team: String, + pub id: String, + pub project: String, + pub release: String, + pub env: String, + pub author: String, + pub format: Format, + pub artifact: Artifact, + pub artifact_digest: Vec, + pub image: String, + pub public: [u8; 32], + pub expires: u64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SignJson { + v: u32, + op: String, + team: String, + id: String, + project: String, + release: String, + env: String, + author: String, + format: String, + artifact: Artifact, + artifact_digest: String, + image: String, + #[serde(rename = "pub")] + public: String, + expires: u64, +} + +fn lower_hex(s: &str, len: usize) -> bool { + s.len() == len && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +pub(crate) fn pub_key(s: &str) -> Result<[u8; 32], TeamError> { + let k: [u8; 32] = unb64(s) + .and_then(|v| v.try_into().ok()) + .ok_or(TeamError::Invalid("pub is not base64 of 32 bytes"))?; + if k == [0; 32] { + return Err(TeamError::Invalid("pub is all zeros")); + } + Ok(k) +} + +fn name_ok(name: &str) -> bool { + canon::text_ok(name, 200) && !name.contains(['/', '\\']) +} + +impl SignRequest { + pub fn canonical(&self) -> String { + let mut o = String::with_capacity(640); + o.push_str("{\"v\":1,\"op\":\"sign.request\",\"team\":"); + canon::string(&mut o, &self.team); + o.push_str(",\"id\":"); + canon::string(&mut o, &self.id); + o.push_str(",\"project\":"); + canon::string(&mut o, &self.project); + o.push_str(",\"release\":"); + canon::string(&mut o, &self.release); + o.push_str(",\"env\":"); + canon::string(&mut o, &self.env); + o.push_str(",\"author\":"); + canon::string(&mut o, &self.author); + o.push_str(",\"format\":"); + canon::string(&mut o, self.format.word()); + o.push_str(",\"artifact\":{\"name\":"); + canon::string(&mut o, &self.artifact.name); + o.push_str(",\"size\":"); + o.push_str(&self.artifact.size.to_string()); + o.push_str(",\"sha256\":"); + canon::string(&mut o, &self.artifact.sha256); + o.push_str("},\"artifact_digest\":"); + canon::string(&mut o, &b64(&self.artifact_digest)); + o.push_str(",\"image\":"); + canon::string(&mut o, &self.image); + o.push_str(",\"pub\":"); + canon::string(&mut o, &b64(&self.public)); + o.push_str(",\"expires\":"); + o.push_str(&self.expires.to_string()); + o.push('}'); + o + } + + /// Every field as docs/TEAM.md allows it, without the clock. + pub fn check_fields(&self) -> Result<(), TeamError> { + let bad = |w| Err(TeamError::Invalid(w)); + if !id_ok(&self.team) || !id_ok(&self.id) { + return bad("team and id are 32 lower-case hex digits"); + } + if !canon::ascii_ok(&self.project, 1, 128, b"._/-") { + return bad("project is 1 to 128 of [A-Za-z0-9._/-]"); + } + if !canon::ascii_ok(&self.release, 1, 64, b"._+-") { + return bad("release is 1 to 64 of [A-Za-z0-9._+-]"); + } + if !canon::env_ok(&self.env) { + return bad("env is [a-z][a-z0-9-]{0,31}"); + } + if !canon::ascii_ok(&self.author, 0, 64, b"._@-") { + return bad("author is 0 to 64 of [A-Za-z0-9._@-]"); + } + if !name_ok(&self.artifact.name) { + return bad("the artifact's name is 1 to 200 characters, no path, no control characters"); + } + if !lower_hex(&self.artifact.sha256, 64) { + return bad("the artifact's sha256 is 64 lower-case hex digits"); + } + if !self.format.digest_ok(&self.artifact_digest) { + return bad("artifact_digest has the wrong length for its format"); + } + match self.format { + Format::Cosign => custos_sign::image_ok(&self.image).map_err(|_| TeamError::Invalid("image is not a repository"))?, + _ if !self.image.is_empty() => return bad("image is for cosign only"), + _ => {} + } + Ok(()) + } + + /// Reads a canonical request, without the clock: for showing what an expired request said. Never enough to sign. + pub fn parse(text: &str) -> Result { + if text.len() > MAX_REQUEST { + return Err(TeamError::NotCanonical("a request is at most 4 KiB")); + } + let j: SignJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a sign.request"))?; + if j.v != 1 || j.op != "sign.request" { + return Err(TeamError::NotCanonical("not a sign.request v1")); + } + let format = Format::from_word(&j.format).ok_or(TeamError::Invalid("an unknown format"))?; + let digest = unb64(&j.artifact_digest).ok_or(TeamError::Invalid("artifact_digest is not base64"))?; + let r = SignRequest { + team: j.team, + id: j.id, + project: j.project, + release: j.release, + env: j.env, + author: j.author, + format, + artifact: j.artifact, + artifact_digest: digest, + image: j.image, + public: pub_key(&j.public)?, + expires: j.expires, + }; + r.check_fields()?; + if r.canonical() != text { + return Err(TeamError::NotCanonical("key order, spaces or escaping")); + } + Ok(r) + } + + /// [`SignRequest::parse`] and the clock: not expired at `now` (Unix seconds), at most 25 hours ahead. + pub fn check(text: &str, now: u64) -> Result { + let r = SignRequest::parse(text)?; + if r.expires <= now { + return Err(TeamError::Expired); + } + if r.expires > now.saturating_add(MAX_AHEAD_SECS) { + return Err(TeamError::Invalid("it expires more than 25 hours from now")); + } + Ok(r) + } + + /// SHA-256 of the canonical text. + pub fn hash(&self) -> [u8; 32] { + sha256(self.canonical().as_bytes()) + } + + pub fn hash_hex(&self) -> String { + hex(&self.hash()) + } + + /// The match code Fabrica shows and every card shows: `match_code(pub)`. + pub fn match_code(&self) -> String { + custos_seal::match_code(&self.public) + } + + /// The context the reply is sealed under. + pub fn reply_context(&self) -> Vec { + format!("team-sign:{}", self.id).into_bytes() + } +} + +/// Fabrica asks for a target credential for one deployment (docs/TEAM.md, "Target credentials"). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TargetRequest { + pub team: String, + pub id: String, + pub target: String, + /// The hash of the `sign.request` whose signature this deployment deploys. + pub deployment: String, + pub public: [u8; 32], + pub expires: u64, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TargetJson { + v: u32, + op: String, + team: String, + id: String, + target: String, + deployment: String, + #[serde(rename = "pub")] + public: String, + expires: u64, +} + +impl TargetRequest { + pub fn canonical(&self) -> String { + let mut o = String::with_capacity(256); + o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":"); + canon::string(&mut o, &self.team); + o.push_str(",\"id\":"); + canon::string(&mut o, &self.id); + o.push_str(",\"target\":"); + canon::string(&mut o, &self.target); + o.push_str(",\"deployment\":"); + canon::string(&mut o, &self.deployment); + o.push_str(",\"pub\":"); + canon::string(&mut o, &b64(&self.public)); + o.push_str(",\"expires\":"); + o.push_str(&self.expires.to_string()); + o.push('}'); + o + } + + /// Reads and checks a canonical target request at `now`; it lives at most 25 hours. + pub fn check(text: &str, now: u64) -> Result { + if text.len() > MAX_REQUEST { + return Err(TeamError::NotCanonical("a request is at most 4 KiB")); + } + let j: TargetJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a target.request"))?; + if j.v != 1 || j.op != "target.request" { + return Err(TeamError::NotCanonical("not a target.request v1")); + } + let r = TargetRequest { + team: j.team, + id: j.id, + target: j.target, + deployment: j.deployment, + public: pub_key(&j.public)?, + expires: j.expires, + }; + if !id_ok(&r.team) || !id_ok(&r.id) || !lower_hex(&r.target, 16) || !lower_hex(&r.deployment, 64) { + return Err(TeamError::Invalid("team, id, target and deployment are hex ids")); + } + if r.canonical() != text { + return Err(TeamError::NotCanonical("key order, spaces or escaping")); + } + if r.expires <= now { + return Err(TeamError::Expired); + } + if r.expires > now.saturating_add(MAX_AHEAD_SECS) { + return Err(TeamError::Invalid("it expires more than 25 hours from now")); + } + Ok(r) + } + + pub fn match_code(&self) -> String { + custos_seal::match_code(&self.public) + } + + pub fn reply_context(&self) -> Vec { + format!("team-target:{}", self.id).into_bytes() + } +} diff --git a/crates/custos-team/src/statement.rs b/crates/custos-team/src/statement.rs new file mode 100644 index 0000000..0606692 --- /dev/null +++ b/crates/custos-team/src/statement.rs @@ -0,0 +1,76 @@ +//! A member's approval of one request (docs/TEAM.md, "Approval statements"). + +use serde::{Deserialize, Serialize}; + +use crate::member::MemberKey; +use crate::policy::RosterMember; +use crate::request::SignRequest; +use crate::{TeamError, b64, unb64, unhex}; + +pub const APPROVAL_DOMAIN: &[u8] = b"custos team approval v1\0"; + +/// `{"member", "code", "at", "sig"}`: who approved which request (by its hash, outside), with which code, when. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Statement { + pub member: String, + pub code: String, + pub at: u64, + /// Base64 of the 64-byte Ed25519 signature. + pub sig: String, +} + +/// What a statement signs. +pub fn message(request_hash: &[u8; 32], code: &str, member: &[u8; 16], at: u64) -> Vec { + let mut m = Vec::with_capacity(APPROVAL_DOMAIN.len() + 32 + 6 + 16 + 8); + m.extend_from_slice(APPROVAL_DOMAIN); + m.extend_from_slice(request_hash); + m.extend_from_slice(code.as_bytes()); + m.extend_from_slice(member); + m.extend_from_slice(&at.to_be_bytes()); + m +} + +fn code_ok(code: &str) -> bool { + code.len() == 6 && code.bytes().all(|c| c.is_ascii_digit()) +} + +/// A member approves `req`. `shown_code` is the code the card showed: when it is not the request's own match code, +/// the request changed after the card was drawn, or it is someone else's, and nothing is signed (`WrongMatch`). +pub fn approve(key: &MemberKey, req: &SignRequest, shown_code: &str, now: u64) -> Result { + if shown_code != req.match_code() { + return Err(TeamError::WrongMatch); + } + let id = key.public().id_bytes(); + let sig = key.sign(&message(&req.hash(), shown_code, &id, now)); + Ok(Statement { member: key.id(), code: shown_code.into(), at: now, sig: b64(&sig) }) +} + +impl Statement { + /// Checks this statement for `req` against the roster: the member is on it, the code is the request's own, + /// the signature is the member's. + pub fn verify(&self, req: &SignRequest, roster: &[RosterMember]) -> Result<(), TeamError> { + if !code_ok(&self.code) || self.code != req.match_code() { + return Err(TeamError::WrongMatch); + } + let m = roster.iter().find(|m| m.id == self.member).ok_or(TeamError::NotAMember)?; + let id: [u8; 16] = unhex(&self.member).ok_or(TeamError::NotAMember)?; + let sig: [u8; 64] = + unb64(&self.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?; + if !crate::member::verify(&m.ed25519, &message(&req.hash(), &self.code, &id, self.at), &sig) { + return Err(TeamError::BadSignature); + } + Ok(()) + } +} + +/// The member ids of the statements that verify for `req`, each once, in order; the others are dropped. +pub fn verified_members(statements: &[Statement], req: &SignRequest, roster: &[RosterMember]) -> Vec { + let mut out: Vec = Vec::new(); + for s in statements { + if s.verify(req, roster).is_ok() && !out.contains(&s.member) { + out.push(s.member.clone()); + } + } + out +} diff --git a/crates/custos-team/src/target.rs b/crates/custos-team/src/target.rs new file mode 100644 index 0000000..dfc0b32 --- /dev/null +++ b/crates/custos-team/src/target.rs @@ -0,0 +1,66 @@ +//! Target credentials (docs/TEAM.md, "Target credentials"): what they are, and the plaintext a released one is +//! sealed as. + +use std::fmt; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TargetKind { + /// An OpenSSH private key. + SshKey, + /// A WinRM user and password. + Winrm, + /// An OpenSSH user and password. + Openssh, + /// A Docker registry token. + Registry, + /// A kubeconfig. + Kubeconfig, +} + +impl TargetKind { + pub fn word(self) -> &'static str { + match self { + TargetKind::SshKey => "ssh-key", + TargetKind::Winrm => "winrm", + TargetKind::Openssh => "openssh", + TargetKind::Registry => "registry", + TargetKind::Kubeconfig => "kubeconfig", + } + } +} + +/// The largest target credential. +pub const MAX_SECRET: usize = 64 * 1024; + +/// A released credential, as sealed to the Fabrica server's one-time key (`team-target:`). +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TargetRelease { + pub v: u32, + pub op: String, + pub team: String, + pub target: String, + pub kind: TargetKind, + pub name: String, + pub host: String, + pub user: String, + pub secret: String, + /// The deployment's request hash. + pub deployment: String, + pub project: String, + pub env: String, +} + +impl fmt::Debug for TargetRelease { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TargetRelease") + .field("target", &self.target) + .field("kind", &self.kind) + .field("deployment", &self.deployment) + .field("secret", &"[redacted]") + .finish_non_exhaustive() + } +} diff --git a/crates/custos-team/tests/policy.rs b/crates/custos-team/tests/policy.rs new file mode 100644 index 0000000..399a5e9 --- /dev/null +++ b/crates/custos-team/tests/policy.rs @@ -0,0 +1,186 @@ +//! Mandatory: policy evaluation, every combination of team size, environment and the author/approver rule +//! (docs/TEAM.md, "Evaluation"). + +use custos_team::policy::{EnvRule, may_approve}; +use custos_team::*; + +const TEAM: &str = "0123456789abcdef0123456789abcdef"; + +fn roster(n: usize) -> Vec { + (0..n) + .map(|i| RosterMember { + id: format!("{i:032x}"), + name: format!("Member {i}"), + // Member 0 is the author; Fabrica names them by handle, in another case. + handles: if i == 0 { vec!["MNovak".into()] } else { vec![format!("dev{i}")] }, + ed25519: [i as u8; 32], + }) + .collect() +} + +fn id(i: usize) -> String { + format!("{i:032x}") +} + +const OUTSIDER: &str = "ffffffffffffffffffffffffffffffff"; + +/// The approver sets every size is tried with. +fn approver_sets(n: usize) -> Vec<(&'static str, Vec)> { + let mut v = vec![("nobody", vec![]), ("the author", vec![id(0)]), ("an outsider", vec![OUTSIDER.into()])]; + if n >= 2 { + v.push(("one other", vec![id(1)])); + v.push(("the author and one other", vec![id(0), id(1)])); + v.push(("one other twice", vec![id(1), id(1)])); + } + if n >= 3 { + v.push(("two others", vec![id(1), id(2)])); + } + v +} + +/// The rule in the doc's own words, for the default policy. +fn expected(n: usize, env: &str, author_is_member: bool, set: &[String]) -> Verdict { + let members: Vec<&String> = set.iter().filter(|a| a.as_str() != OUTSIDER).collect(); + let mut distinct: Vec<&String> = Vec::new(); + for m in members { + if !distinct.contains(&m) { + distinct.push(m); + } + } + match env { + "preview" => Verdict::Allowed(KeyRole::Test), + "staging" => { + if distinct.is_empty() { + Verdict::Need(1) + } else { + Verdict::Allowed(KeyRole::Release) + } + } + "production" => { + // "1 by someone other than the release author when the team has 2+ members" + let author_excluded = n >= 2 && author_is_member; + let counted = distinct.iter().filter(|m| !(author_excluded && m.as_str() == id(0))).count(); + if counted >= 1 { Verdict::Allowed(KeyRole::Release) } else { Verdict::Need(1) } + } + _ => Verdict::UnknownEnv, + } +} + +#[test] +fn every_size_environment_author_and_approver_under_the_default_policy() { + let policy = Policy::default_for(TEAM); + let mut cases = 0; + for n in [1usize, 2, 3, 4, 10] { + let r = roster(n); + for env in ["preview", "staging", "production", "qa"] { + // The author by handle (any case), by member id, someone outside the team, or nobody named. + for (author, is_member) in [("mnovak", true), ("MNOVAK", true), (id(0).as_str(), true), ("stranger", false), ("", false)] { + for (what, set) in approver_sets(n) { + let got = evaluate(&policy, &r, env, author, &set); + let want = expected(n, env, is_member, &set); + assert_eq!(got.verdict, want, "size {n}, {env}, author {author:?}, approved by {what}"); + cases += 1; + } + } + } + } + assert!(cases > 400, "{cases}"); +} + +#[test] +fn a_team_of_one_approves_its_own_production_release_and_a_second_member_ends_that() { + let p = Policy::default_for(TEAM); + let solo = roster(1); + assert_eq!(evaluate(&p, &solo, "production", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release)); + assert!(may_approve(&p, &solo, "production", "mnovak", &id(0)).is_ok()); + let two = roster(2); + let e = evaluate(&p, &two, "production", "mnovak", &[id(0)]); + assert_eq!(e.verdict, Verdict::Need(1)); + assert_eq!(e.ignored, vec![id(0)]); + assert_eq!(e.eligible, vec![id(1)]); + assert_eq!( + may_approve(&p, &two, "production", "mnovak", &id(0)), + Err(TeamError::NotEligible("the release's author may not approve it here")) + ); + assert!(may_approve(&p, &two, "production", "mnovak", &id(1)).is_ok()); + assert_eq!(may_approve(&p, &two, "production", "mnovak", OUTSIDER), Err(TeamError::NotAMember)); + assert_eq!(may_approve(&p, &two, "qa", "mnovak", &id(1)), Err(TeamError::UnknownEnv)); +} + +#[test] +fn several_approvals_others_and_approver_lists() { + let mut p = Policy::default_for(TEAM); + p.set_rule(EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] }).unwrap(); + assert_eq!(p.rev, 2); + // Two members, the author excluded: one left for two approvals, which can never be met. + assert!(matches!(evaluate(&p, &roster(2), "production", "mnovak", &[]).verdict, Verdict::Unsatisfiable(_))); + // A team of one: `others` does not apply, but two approvals from one person cannot be. + assert!(matches!(evaluate(&p, &roster(1), "production", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_))); + let three = roster(3); + assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(1)]).verdict, Verdict::Need(1)); + assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(0), id(1)]).verdict, Verdict::Need(1)); + assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(1), id(2)]).verdict, Verdict::Allowed(KeyRole::Release)); + // Someone not named as the author (a release by a non-member): every member counts. + assert_eq!(evaluate(&p, &three, "production", "stranger", &[id(0), id(1)]).verdict, Verdict::Allowed(KeyRole::Release)); + + // Only member 1 may approve staging. + p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: false, approvers: vec![id(1)] }).unwrap(); + let four = roster(4); + assert_eq!(evaluate(&p, &four, "staging", "", &[id(2)]).verdict, Verdict::Need(1)); + assert_eq!(evaluate(&p, &four, "staging", "", &[id(2), id(1)]).verdict, Verdict::Allowed(KeyRole::Release)); + assert!(matches!(may_approve(&p, &four, "staging", "", &id(2)), Err(TeamError::NotEligible(_)))); + // The only listed approver is the author, and the rule wants someone else. + p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap(); + assert!(matches!(evaluate(&p, &four, "staging", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_))); + // ... but in a team of one the author is the only member and approves. + let solo_policy = { + let mut q = Policy::default_for(TEAM); + q.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap(); + q + }; + assert_eq!(evaluate(&solo_policy, &roster(1), "staging", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release)); + // A preview made strict. + p.set_rule(EnvRule { env: "preview".into(), approvals: 1, others: false, approvers: vec![] }).unwrap(); + assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[]).verdict, Verdict::Need(1)); + assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release)); +} + +#[test] +fn the_policy_text_is_canonical_and_its_rules_are_checked() { + let p = Policy::default_for(TEAM); + let text = p.canonical(); + assert_eq!( + text, + "{\"v\":1,\"team\":\"0123456789abcdef0123456789abcdef\",\"rev\":1,\"envs\":[{\"env\":\"preview\",\"approvals\":0,\"others\":false,\"approvers\":[]},{\"env\":\"staging\",\"approvals\":1,\"others\":false,\"approvers\":[]},{\"env\":\"production\",\"approvals\":1,\"others\":true,\"approvers\":[]}]}" + ); + assert_eq!(Policy::parse(&text).unwrap(), p); + for bad in [ + text.replace("{\"v\":1,", "{ \"v\":1,"), + text.replace("\"rev\":1", "\"rev\":0"), + text.replace("\"approvals\":0", "\"approvals\":11"), + text.replace("\"staging\"", "\"preview\""), + text.replace("\"staging\"", "\"Staging\""), + text.replace("\"approvers\":[]}]", "\"approvers\":[\"nope\"]}]"), + text.replace("{\"v\":1,", "{\"v\":2,"), + text.clone() + "\n", + text.replace("\"others\":false,\"approvers\":[]},{\"env\":\"staging\"", "\"others\":false,\"approvers\":[],\"x\":1},{\"env\":\"staging\""), + ] { + assert!(Policy::parse(&bad).is_err(), "{bad}"); + } + let mut q = p.clone(); + assert!(q.set_rule(EnvRule { env: "prod uction".into(), approvals: 1, others: true, approvers: vec![] }).is_err()); + assert_eq!(q, p, "a refused change leaves the policy as it was"); +} + +#[test] +fn the_identity_signs_the_policy_and_nothing_else_passes_for_it() { + let identity = TeamIdentity::generate(); + let text = Policy::default_for(TEAM).canonical(); + let sig = identity.sign_policy(&text); + assert!(custos_team::member::verify_policy_sig(&identity.public(), &text, &sig)); + assert!(!custos_team::member::verify_policy_sig(&identity.public(), &text.replace("\"approvals\":1,\"others\":true", "\"approvals\":0,\"others\":true"), &sig)); + // A proof signature is not a policy signature. + let proof_sig = identity.sign_proof(&text); + assert!(!custos_team::member::verify_policy_sig(&identity.public(), &text, &proof_sig)); + assert_eq!(format!("{identity:?}"), "[redacted]"); +} diff --git a/crates/custos-team/tests/request.rs b/crates/custos-team/tests/request.rs new file mode 100644 index 0000000..a764744 --- /dev/null +++ b/crates/custos-team/tests/request.rs @@ -0,0 +1,187 @@ +//! The canonical sign.request, match codes, approval statements and the policy proof (docs/TEAM.md). + +use custos_team::policy::Policy; +use custos_team::proof::ProofBody; +use custos_team::statement::{approve, verified_members}; +use custos_team::*; + +const NOW: u64 = 1_794_000_000; + +pub fn request(team: &str, env: &str, author: &str, public: [u8; 32]) -> SignRequest { + SignRequest { + team: team.into(), + id: "aa".repeat(16), + project: "mnovak/Arca".into(), + release: "0.7.0".into(), + env: env.into(), + author: author.into(), + format: Format::Minisign, + artifact: custos_team::request::Artifact { + name: "Arca_0.7.0_x64-setup.exe".into(), + size: 25_145_977, + sha256: "c4".repeat(32), + }, + artifact_digest: vec![9; 64], + image: String::new(), + public, + expires: NOW + 3600, + } +} + +#[test] +fn a_request_is_read_only_in_canonical_form() { + let fabrica = custos_seal::Recipient::generate(); + let r = request(&"01".repeat(16), "production", "mnovak", fabrica.public()); + let text = r.canonical(); + assert!(text.starts_with("{\"v\":1,\"op\":\"sign.request\",\"team\":\"0101")); + assert_eq!(SignRequest::check(&text, NOW).unwrap(), r); + assert_eq!(r.match_code(), fabrica.match_code()); + for bad in [ + text.replace(",\"id\"", ", \"id\""), + text.replace("\"op\":\"sign.request\"", "\"op\":\"sign.reply\""), + text.replace("\"format\":\"minisign\"", "\"format\":\"gpg\""), + text.replace("mnovak/Arca", "mnovak/Arca\\u0041"), + text.replace("Arca_0.7.0_x64-setup.exe", "../Arca.exe"), + text.replace("\"env\":\"production\"", "\"env\":\"Production\""), + format!("{text}\n"), + text.replace("\"image\":\"\"", "\"image\":\"arca\""), + ] { + assert!(SignRequest::check(&bad, NOW).is_err(), "{bad}"); + } + assert_eq!(SignRequest::check(&text, r.expires), Err(TeamError::Expired)); + let mut far = r.clone(); + far.expires = NOW + 25 * 3600 + 1; + assert!(SignRequest::check(&far.canonical(), NOW).is_err()); + // Digest lengths per format. + let mut apk = r.clone(); + apk.format = Format::Apk; + apk.artifact_digest = vec![1; 128]; + assert!(SignRequest::check(&apk.canonical(), NOW).is_ok()); + apk.artifact_digest = vec![1; 64 * 5]; + assert!(SignRequest::check(&apk.canonical(), NOW).is_err()); + let mut cosign = r.clone(); + cosign.format = Format::Cosign; + cosign.artifact_digest = vec![1; 32]; + assert!(SignRequest::check(&cosign.canonical(), NOW).is_err(), "cosign needs an image"); + cosign.image = "registry.example/team/arca".into(); + assert!(SignRequest::check(&cosign.canonical(), NOW).is_ok()); +} + +fn roster_of(keys: &[&MemberKey]) -> Vec { + keys.iter() + .enumerate() + .map(|(i, k)| RosterMember { + id: k.id(), + name: format!("M{i}"), + handles: if i == 0 { vec!["mnovak".into()] } else { vec![] }, + ed25519: k.public().ed25519, + }) + .collect() +} + +#[test] +fn a_wrong_match_code_is_refused_and_never_counts() { + let (a, b) = (MemberKey::generate(), MemberKey::generate()); + let roster = roster_of(&[&a, &b]); + let fabrica = custos_seal::Recipient::generate(); + let req = request(&"01".repeat(16), "production", "mnovak", fabrica.public()); + // B's card showed another code: B approves nothing. + let wrong = if req.match_code() == "000000" { "000001" } else { "000000" }; + assert_eq!(approve(&b, &req, wrong, NOW), Err(TeamError::WrongMatch)); + // A request whose pub was swapped after B's card was drawn: the code B saw is the old request's. + let shown = req.match_code(); + let mut swapped = req.clone(); + swapped.public = custos_seal::Recipient::generate().public(); + assert_eq!(approve(&b, &swapped, &shown, NOW), Err(TeamError::WrongMatch)); + // A statement made for one request does not count for the swapped one. + let s = approve(&b, &req, &shown, NOW).unwrap(); + s.verify(&req, &roster).unwrap(); + assert_eq!(s.verify(&swapped, &roster), Err(TeamError::WrongMatch)); + assert!(verified_members(&[s.clone()], &swapped, &roster).is_empty()); + // A forged code inside a statement fails its signature or its code. + let mut forged = s.clone(); + forged.code = wrong.into(); + assert_eq!(forged.verify(&req, &roster), Err(TeamError::WrongMatch)); + let mut other_member = s.clone(); + other_member.member = a.id(); + assert_eq!(other_member.verify(&req, &roster), Err(TeamError::BadSignature)); + // Not on the roster. + let c = MemberKey::generate(); + let sc = approve(&c, &req, &shown, NOW).unwrap(); + assert_eq!(sc.verify(&req, &roster), Err(TeamError::NotAMember)); + assert_eq!(verified_members(&[s.clone(), s.clone(), sc], &req, &roster), vec![b.id()]); +} + +#[test] +fn member_keys_seal_the_team_key_to_one_member_team_and_epoch() { + let (a, b) = (MemberKey::generate(), MemberKey::generate()); + let team = "02".repeat(16); + let key = [7u8; 32]; + let sealed = custos_team::member::seal_team_key(&key, &a.public(), &team, 3).unwrap(); + assert_eq!(sealed.len(), custos_team::member::SEALED_KEY_LEN); + assert_eq!(*a.open_team_key(&sealed, &team, 3).unwrap(), key); + assert_eq!(a.open_team_key(&sealed, &team, 4), Err(TeamError::NotAMember)); + assert_eq!(a.open_team_key(&sealed, &"03".repeat(16), 3), Err(TeamError::NotAMember)); + assert_eq!(b.open_team_key(&sealed, &team, 3), Err(TeamError::NotAMember)); + // The key round-trips through its secrets; ids and codes are stable. + let again = MemberKey::from_secrets(a.x25519_secret(), a.ed25519_secret()).unwrap(); + assert_eq!(again.public(), a.public()); + assert_eq!(a.public().join_code(), custos_seal::match_code(&a.public().x25519)); + assert_eq!(a.id().len(), 32); + assert_ne!(a.id(), b.id()); + assert_eq!(format!("{a:?}"), "[redacted]"); + a.public().check().unwrap(); +} + +#[test] +fn a_proof_verifies_only_for_its_request_signature_policy_and_identity() { + let identity = TeamIdentity::generate(); + let team = "04".repeat(16); + let (a, b) = (MemberKey::generate(), MemberKey::generate()); + let roster = roster_of(&[&a, &b]); + let policy = Policy::default_for(&team); + let policy_text = policy.canonical(); + let fabrica = custos_seal::Recipient::generate(); + let req = request(&team, "production", "mnovak", fabrica.public()); + let req_text = req.canonical(); + let s = approve(&b, &req, &req.match_code(), NOW).unwrap(); + let envelope = b"untrusted comment: ...".to_vec(); + let body = |approvals: Vec, signer: String, role: KeyRole| ProofBody { + team: team.clone(), + request: req.hash_hex(), + env: req.env.clone(), + author: req.author.clone(), + policy: policy_text.clone(), + policy_sig: identity.sign_policy(&policy_text), + roster: roster.clone(), + approvals, + signer, + role, + signature: custos_sign::sha256_hex(&envelope), + at: NOW, + }; + let good = body(vec![s.clone()], b.id(), KeyRole::Release).sign(&identity); + assert_eq!(ProofBody::parse(&good.text).unwrap(), body(vec![s.clone()], b.id(), KeyRole::Release)); + let v = verify_proof(&good, &identity.public(), &req_text, &envelope).unwrap(); + assert_eq!((v.role, v.signer.as_str(), v.approvers.clone()), (KeyRole::Release, b.id().as_str(), vec![b.id()])); + + // Another identity, another envelope, another request. + assert_eq!(verify_proof(&good, &TeamIdentity::generate().public(), &req_text, &envelope), Err(TeamError::BadSignature)); + assert!(verify_proof(&good, &identity.public(), &req_text, b"another signature").is_err()); + let mut other = req.clone(); + other.release = "0.7.1".into(); + assert!(verify_proof(&good, &identity.public(), &other.canonical(), &envelope).is_err()); + // The author's own approval does not make a production proof. + let sa = approve(&a, &req, &req.match_code(), NOW).unwrap(); + let selfish = body(vec![sa], a.id(), KeyRole::Release).sign(&identity); + assert_eq!(verify_proof(&selfish, &identity.public(), &req_text, &envelope), Err(TeamError::NeedMore(1))); + // A proof claiming the test role for production, or signed by someone who did not approve. + let wrong_role = body(vec![s.clone()], b.id(), KeyRole::Test).sign(&identity); + assert!(verify_proof(&wrong_role, &identity.public(), &req_text, &envelope).is_err()); + let not_approver = body(vec![s.clone()], a.id(), KeyRole::Release).sign(&identity); + assert!(verify_proof(¬_approver, &identity.public(), &req_text, &envelope).is_err()); + // An edited text breaks the identity's signature. + let mut edited = good.clone(); + edited.text = edited.text.replace("\"production\"", "\"staging\""); + assert_eq!(verify_proof(&edited, &identity.public(), &req_text, &envelope), Err(TeamError::BadSignature)); +} diff --git a/crates/custos-vault/Cargo.toml b/crates/custos-vault/Cargo.toml index 4a2fdc9..5c88325 100644 --- a/crates/custos-vault/Cargo.toml +++ b/crates/custos-vault/Cargo.toml @@ -22,9 +22,12 @@ bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] } # Signing keys for releases (docs/SIGNING.md). custos-sign = { path = "../custos-sign" } +# Team vaults (docs/TEAM.md, core 0.18.0). +custos-team = { path = "../custos-team" } [dev-dependencies] tempfile = "3" +custos-seal = { path = "../custos-seal" } minisign-verify = "0.3" rsa = { version = "0.9", features = ["sha2"] } sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] } diff --git a/crates/custos-vault/src/format.rs b/crates/custos-vault/src/format.rs index 3fe4309..871f105 100644 --- a/crates/custos-vault/src/format.rs +++ b/crates/custos-vault/src/format.rs @@ -18,6 +18,12 @@ pub const SLOT_SINGLE: u8 = 4; /// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key"). pub const SLOT_RECOVERY: u8 = 5; pub const RECOVERY_ID_LEN: usize = 4; +/// A team vault's member slot (core 0.18.0; docs/TEAM.md): the team key sealed to one member. +pub const SLOT_MEMBER: u8 = 6; +/// team id (16) ‖ member id (16) ‖ epoch (4) ‖ sealed team key (108). +pub const MEMBER_SLOT_LEN: usize = 16 + 16 + 4 + 108; +/// A team has at most this many members. +pub const MAX_MEMBER_SLOTS: usize = 32; const KDF_ARGON2ID: u8 = 1; pub const SALT_LEN: usize = 32; pub const ID_LEN: usize = 16; @@ -289,6 +295,38 @@ impl RecoverySlot { } } +/// A team vault's member slot (kind 6): the box carries its own binding (its context names team, epoch and member). +#[derive(Clone)] +pub struct MemberSlot { + pub team: [u8; ID_LEN], + pub member: [u8; ID_LEN], + pub epoch: u32, + pub sealed: Vec, +} + +impl MemberSlot { + pub fn raw(&self) -> RawSlot { + let mut p = Vec::with_capacity(MEMBER_SLOT_LEN); + p.extend_from_slice(&self.team); + p.extend_from_slice(&self.member); + p.extend_from_slice(&self.epoch.to_le_bytes()); + p.extend_from_slice(&self.sealed); + RawSlot { kind: SLOT_MEMBER, payload: p } + } + + pub fn parse(payload: &[u8]) -> Result { + if payload.len() != MEMBER_SLOT_LEN { + return Err(Error::Malformed); + } + Ok(MemberSlot { + team: payload[..16].try_into().unwrap(), + member: payload[16..32].try_into().unwrap(), + epoch: u32::from_le_bytes(payload[32..36].try_into().unwrap()), + sealed: payload[36..].to_vec(), + }) + } +} + pub struct Header { pub version: u16, pub slots: Vec, @@ -348,6 +386,9 @@ impl Header { /// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces"). fn check_v2(&self) -> Result<(), Error> { + if self.slots.iter().any(|s| s.kind == SLOT_MEMBER) { + return self.check_team(); + } let mut ids = Vec::new(); for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) { ids.push(FactorSlot::parse(&s.payload)?.id); @@ -398,6 +439,31 @@ impl Header { Ok(()) } + /// A team vault (docs/TEAM.md): 1 ..= 32 member slots and nothing else, one team id and epoch, distinct members. + fn check_team(&self) -> Result<(), Error> { + if self.slots.len() > MAX_MEMBER_SLOTS || self.slots.iter().any(|s| s.kind != SLOT_MEMBER) { + return Err(Error::Malformed); + } + let slots = self.slots.iter().map(|s| MemberSlot::parse(&s.payload)).collect::, _>>()?; + let first = &slots[0]; + let mut members: Vec<[u8; ID_LEN]> = Vec::with_capacity(slots.len()); + for s in &slots { + if s.team != first.team || s.epoch != first.epoch || members.contains(&s.member) { + return Err(Error::Malformed); + } + members.push(s.member); + } + Ok(()) + } + + pub fn is_team(&self) -> bool { + self.slots.iter().any(|s| s.kind == SLOT_MEMBER) + } + + pub fn member_slots(&self) -> Vec { + self.slots.iter().filter(|s| s.kind == SLOT_MEMBER).filter_map(|s| MemberSlot::parse(&s.payload).ok()).collect() + } + pub fn factor_slots(&self) -> Vec { self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect() } diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index 0cc59cb..4f93661 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -27,11 +27,16 @@ mod save; mod secret; pub mod security; pub mod signing; +pub mod team; pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms}; pub use recovery::RecoveryKey; pub use save::{CrashPoint, save_atomic, save_atomic_crashing}; pub use secret::{SecretBytes, SecretString}; +pub use team::{ + KnownTeam, NewSigner, NewTarget, Removal, RemovedMember, SignerView, TargetView, TeamAction, TeamAuditEntry, + TeamMember, TeamView, +}; use crypto::KEY_LEN; use format::{ @@ -97,6 +102,15 @@ pub enum Error { Security(&'static str), #[error("signing keys: {0}")] Signing(String), + /// A team vault operation was refused (docs/TEAM.md); names why, never a value. + #[error("team: {0}")] + Team(String), + #[error("this is not a team vault")] + NotATeam, + #[error("this member key does not open this team vault: not a member, or removed")] + NotAMember, + #[error("this team vault is older than the one this member has seen, or another team's under the same id")] + TeamRollback, #[error("{0}")] Io(#[from] std::io::Error), } @@ -295,6 +309,14 @@ struct Body { provision: Option, #[serde(default)] security: Option, + /// `"team"` for a team vault (core 0.18.0, docs/TEAM.md). + #[serde(default)] + kind: Option, + #[serde(default)] + team: Option, + /// A person's member key (core 0.18.0). + #[serde(default)] + member: Option, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. @@ -312,6 +334,12 @@ struct BodyRef<'a> { provision: Option, #[serde(skip_serializing_if = "Option::is_none")] security: Option, + #[serde(skip_serializing_if = "Option::is_none")] + kind: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + team: Option, + #[serde(skip_serializing_if = "Option::is_none")] + member: Option, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. @@ -332,6 +360,10 @@ pub struct Vault { provision: Vec, /// The security level's Setup window, the checklist and their audit (docs/FORMAT.md). security: security::State, + /// A team vault's own state (docs/TEAM.md); `None` for every other vault. + team: Option, + /// A person's member key and the teams it has opened (docs/TEAM.md); never in a team vault. + member: Option, } impl fmt::Debug for Vault { @@ -419,6 +451,24 @@ fn unwrap_factor(header: &Header, u: &Unlock) -> Result { } impl Vault { + /// An empty version-2 vault with `key` and no slots yet: a team vault writes its member slots itself. + pub(crate) fn empty_v2(key: Zeroizing<[u8; KEY_LEN]>) -> Vault { + Vault { + key, + version: VERSION_2, + slots: Vec::new(), + items: Vec::new(), + factors: Vec::new(), + kdf_new: KdfParams::DEFAULT, + identity: None, + signing: signing::Store::default(), + provision: Vec::new(), + security: security::State::default(), + team: None, + member: None, + } + } + /// A new, empty version-1 vault with a fresh random vault key wrapped by `password`. pub fn create(password: &SecretString, kdf: KdfParams) -> Result { let key = crypto::random_key(); @@ -434,6 +484,8 @@ impl Vault { signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), + team: None, + member: None, }) } @@ -453,6 +505,8 @@ impl Vault { signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), + team: None, + member: None, }; v.add_factor(a, label_a)?; v.add_factor(b, label_b)?; @@ -488,6 +542,8 @@ impl Vault { signing: signing::Store::default(), provision: Vec::new(), security: security::State::default(), + team: None, + member: None, }) } @@ -614,6 +670,17 @@ impl Vault { None => signing::Store::default(), }; let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?; + // A team vault (member slots) has a team body and nothing of a person's; every other vault has none. + let team = match (header.is_team(), body.kind.as_deref(), body.team) { + (true, Some("team"), Some(j)) => Some(team::TeamState::from_json(j).ok_or(Error::Corrupted)?), + (false, None, None) => None, + _ => return Err(Error::Corrupted), + }; + let member = match body.member { + Some(_) if team.is_some() => return Err(Error::Corrupted), + Some(j) => Some(team::MemberState::from_json(j).ok_or(Error::Corrupted)?), + None => None, + }; Ok(Vault { key, version: header.version, @@ -625,6 +692,8 @@ impl Vault { signing, provision: provision::from_json(body.provision), security, + team, + member, }) } @@ -662,6 +731,9 @@ impl Vault { signing: self.signing.json(), provision: provision::json(&self.provision), security: self.security.json(), + kind: self.team.is_some().then_some("team"), + team: self.team.as_ref().map(team::TeamState::json), + member: self.member.as_ref().map(team::MemberState::json), }; serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?; let sealed = crypto::seal(&self.key, &body_nonce, &json, &out); diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index d085cac..56307dd 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -51,6 +51,8 @@ pub enum KeyKind { 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)] @@ -64,6 +66,12 @@ pub enum SignKind { /// 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)] @@ -153,6 +161,18 @@ pub struct AuditEntry { /// 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. @@ -212,26 +232,29 @@ pub struct KeyView { /// 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, } -enum Secret { +pub(crate) enum Secret { Ed25519(Ed25519Secret), Rsa(RsaSecret), + P256(custos_sign::P256Secret), } -struct Key { - id: String, - kind: KeyKind, - role: Role, - name: String, - secret: Secret, - public: Option<[u8; 32]>, - key_id: Option<[u8; 8]>, - cert: Option>, - issuer: Option, - created: i64, - pipelines: Vec, - repos: Vec, +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 { @@ -243,8 +266,8 @@ impl fmt::Debug for Key { /// The keys and the log, in the vault. #[derive(Debug, Default)] pub(crate) struct Store { - keys: Vec, - audit: Vec, + pub(crate) keys: Vec, + pub(crate) audit: Vec, standing: Vec, } @@ -321,6 +344,10 @@ impl Store { 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()?), @@ -380,6 +407,7 @@ impl Store { 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)), @@ -393,13 +421,13 @@ impl Store { Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() }) } - fn get(&self, id: &str) -> Option<&Key> { + 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. -fn seconds(now_ms: i64) -> u64 { +pub(crate) fn seconds(now_ms: i64) -> u64 { (now_ms.max(0) / 1000) as u64 } @@ -450,6 +478,8 @@ fn kind_word(kind: SignKind) -> &'static str { SignKind::Authenticode => "authenticode", SignKind::Approval => "approval", SignKind::Apk => "apk", + SignKind::TauriUpdater => "tauri-updater", + SignKind::Cosign => "cosign", } } @@ -665,6 +695,10 @@ impl Vault { }, cert: k.cert.clone(), issuer: k.issuer.clone(), + public_pem: match &k.secret { + Secret::P256(s) => s.public_pem().ok(), + _ => None, + }, }) .collect() } @@ -925,6 +959,10 @@ impl Vault { signature, reason, run, + by: None, + env: None, + request: None, + approvers: Vec::new(), }); } @@ -1156,6 +1194,7 @@ mod tests { .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"); diff --git a/crates/custos-vault/src/team.rs b/crates/custos-vault/src/team.rs new file mode 100644 index 0000000..f27f6df --- /dev/null +++ b/crates/custos-vault/src/team.rs @@ -0,0 +1,1285 @@ +//! Team vaults (core 0.18.0, docs/TEAM.md): the `team` body member of a team vault, the `member` body member of a +//! person's own vault, and every operation on them. Keys, credentials and the team identity are used here and +//! never handed out; views carry public parts and names only. + +use std::fmt; + +use custos_team::external::{ExternalSigner, SignerCredential}; +use custos_team::member::{seal_team_key, verify_policy_sig}; +use custos_team::policy::{EnvRule, Evaluation, KeyRole, Policy, RosterMember, evaluate, may_approve}; +use custos_team::proof::ProofBody; +use custos_team::reply::{ReplyKey, ReplySigner, SignReply}; +use custos_team::request::{Format, SignRequest, TargetRequest}; +use custos_team::statement::{Statement, approve, verified_members}; +use custos_team::target::{MAX_SECRET, TargetKind, TargetRelease}; +use custos_team::{MAX_AHEAD_SECS, MemberKey, MemberPublic, SEEN_SECS, TeamError, TeamIdentity, canon}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +use crate::format::{MemberSlot, VERSION_2}; +use crate::signing::{AuditEntry, Context, KeyKind, Outcome, Role, Secret, SignKind, Via, seconds}; +use crate::{Error, SecretString, Vault, crypto, hex, unhex}; + +/// The team audit keeps this many entries. +const AUDIT_MAX: usize = 5000; +const TEAM_RELEASE: &str = "team-release"; +const TEAM_PREVIEW: &str = "team-preview"; +const TEAM_COSIGN: &str = "team-cosign"; +const TEAM_COSIGN_PREVIEW: &str = "team-cosign-preview"; + +// ---- what the body holds ---- + +#[derive(Serialize, Deserialize)] +pub(crate) struct IdentityJson { + secret: SecretString, + public: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeamMember { + pub id: String, + pub name: String, + #[serde(default)] + pub handles: Vec, + pub ed25519: String, + pub x25519: String, + pub added: i64, + /// The member who approved the join; empty for the founder. + #[serde(default)] + pub by: String, + /// The join code that was compared. + #[serde(default)] + pub code: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemovedMember { + pub id: String, + pub name: String, + pub at: i64, + pub by: String, + /// The epoch the removal started. + pub epoch: u32, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct PolicyJson { + text: String, + sig: String, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct TargetJson { + id: String, + kind: TargetKind, + name: String, + project: String, + env: String, + #[serde(default)] + host: String, + #[serde(default)] + user: String, + secret: SecretString, + created: i64, + by: String, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct SignerJson { + id: String, + name: String, + adapter: String, + #[serde(default)] + endpoint: String, + #[serde(default)] + account: String, + secret: SecretString, + /// Base64 DER of the signer's certificate, or empty. + #[serde(default)] + certificate: String, + created: i64, + by: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) struct Seen { + request: String, + at: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TeamAction { + TeamCreated, + MemberAdded, + MemberRemoved, + PolicySet, + TargetAdded, + TargetRemoved, + TargetReleased, + SignerAdded, + SignerRemoved, + KeysCreated, +} + +/// One team action. `detail` names, never holds a value. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TeamAuditEntry { + pub at: i64, + pub action: TeamAction, + pub by: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct TeamJson { + id: String, + name: String, + created: i64, + epoch: u32, + identity: IdentityJson, + members: Vec, + #[serde(default)] + removed: Vec, + policy: PolicyJson, + #[serde(default)] + targets: Vec, + #[serde(default)] + signers: Vec, + #[serde(default)] + seen: Vec, + #[serde(default)] + audit: Vec, +} + +struct Target { + id: String, + kind: TargetKind, + name: String, + project: String, + env: String, + host: String, + user: String, + secret: SecretString, + created: i64, + by: String, +} + +struct Signer { + id: String, + name: String, + adapter: String, + endpoint: String, + account: String, + secret: SecretString, + certificate: Vec, + created: i64, + by: String, +} + +/// A team vault's own state. +pub(crate) struct TeamState { + id: String, + name: String, + created: i64, + epoch: u32, + identity: TeamIdentity, + members: Vec, + removed: Vec, + policy: Policy, + policy_sig: [u8; 64], + targets: Vec, + signers: Vec, + seen: Vec, + audit: Vec, +} + +impl fmt::Debug for TeamState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TeamState").field("id", &self.id).field("epoch", &self.epoch).finish_non_exhaustive() + } +} + +fn b64(b: &[u8]) -> String { + data_encoding::BASE64.encode(b) +} + +fn unb64(s: &str) -> Option> { + data_encoding::BASE64.decode(s.as_bytes()).ok() +} + +fn member_public(m: &TeamMember) -> Option { + Some(MemberPublic { ed25519: unhex(&m.ed25519)?, x25519: unhex(&m.x25519)? }) +} + +fn handles_ok(h: &[String]) -> bool { + h.len() <= 8 && h.iter().all(|x| canon::ascii_ok(x, 1, 64, b"._-")) +} + +fn short_id() -> String { + let mut b = [0u8; 8]; + crypto::fill_random(&mut b); + hex(&b) +} + +impl TeamState { + pub(crate) fn from_json(j: TeamJson) -> Option { + let secret: [u8; 32] = unhex(j.identity.secret.expose())?; + let identity = TeamIdentity::from_secret(&secret); + if hex(&identity.public()) != j.identity.public || !custos_team::id_ok(&j.id) || j.epoch == 0 { + return None; + } + if j.members.is_empty() || j.members.len() > custos_team::MAX_MEMBERS { + return None; + } + for m in &j.members { + if member_public(m)?.id() != m.id || !canon::text_ok(&m.name, 64) || !handles_ok(&m.handles) { + return None; + } + } + let policy = Policy::parse(&j.policy.text).ok()?; + let policy_sig: [u8; 64] = unb64(&j.policy.sig)?.try_into().ok()?; + if policy.team != j.id || !verify_policy_sig(&identity.public(), &j.policy.text, &policy_sig) { + return None; + } + let targets = j + .targets + .into_iter() + .map(|t| Target { + id: t.id, + kind: t.kind, + name: t.name, + project: t.project, + env: t.env, + host: t.host, + user: t.user, + secret: t.secret, + created: t.created, + by: t.by, + }) + .collect(); + let mut signers = Vec::new(); + for s in j.signers { + let certificate = if s.certificate.is_empty() { Vec::new() } else { unb64(&s.certificate)? }; + signers.push(Signer { + id: s.id, + name: s.name, + adapter: s.adapter, + endpoint: s.endpoint, + account: s.account, + secret: s.secret, + certificate, + created: s.created, + by: s.by, + }); + } + Some(TeamState { + id: j.id, + name: j.name, + created: j.created, + epoch: j.epoch, + identity, + members: j.members, + removed: j.removed, + policy, + policy_sig, + targets, + signers, + seen: j.seen, + audit: j.audit, + }) + } + + pub(crate) fn json(&self) -> TeamJson { + TeamJson { + id: self.id.clone(), + name: self.name.clone(), + created: self.created, + epoch: self.epoch, + identity: IdentityJson { + secret: SecretString::new(hex(self.identity.secret().as_ref())), + public: hex(&self.identity.public()), + }, + members: self.members.clone(), + removed: self.removed.clone(), + policy: PolicyJson { text: self.policy.canonical(), sig: b64(&self.policy_sig) }, + targets: self + .targets + .iter() + .map(|t| TargetJson { + id: t.id.clone(), + kind: t.kind, + name: t.name.clone(), + project: t.project.clone(), + env: t.env.clone(), + host: t.host.clone(), + user: t.user.clone(), + secret: SecretString::new(t.secret.expose().to_owned()), + created: t.created, + by: t.by.clone(), + }) + .collect(), + signers: self + .signers + .iter() + .map(|s| SignerJson { + id: s.id.clone(), + name: s.name.clone(), + adapter: s.adapter.clone(), + endpoint: s.endpoint.clone(), + account: s.account.clone(), + secret: SecretString::new(s.secret.expose().to_owned()), + certificate: if s.certificate.is_empty() { String::new() } else { b64(&s.certificate) }, + created: s.created, + by: s.by.clone(), + }) + .collect(), + seen: self.seen.clone(), + audit: self.audit.clone(), + } + } + + fn roster(&self) -> Vec { + self.members + .iter() + .map(|m| RosterMember { + id: m.id.clone(), + name: m.name.clone(), + handles: m.handles.clone(), + ed25519: unhex(&m.ed25519).expect("checked when read"), + }) + .collect() + } + + fn log(&mut self, now: i64, action: TeamAction, by: &str, detail: Option) { + self.audit.push(TeamAuditEntry { at: now, action, by: by.to_owned(), detail }); + if self.audit.len() > AUDIT_MAX { + let drop = self.audit.len() - AUDIT_MAX; + self.audit.drain(..drop); + } + } + + fn is_seen(&self, key: &str) -> bool { + self.seen.iter().any(|s| s.request == key) + } + + fn mark_seen(&mut self, key: String, now_secs: u64) { + self.seen.retain(|s| s.at + SEEN_SECS > now_secs); + if !self.is_seen(&key) { + self.seen.push(Seen { request: key, at: now_secs }); + } + } + + fn sign_policy(&mut self) { + self.policy_sig = self.identity.sign_policy(&self.policy.canonical()); + } +} + +// ---- the member key in a person's own vault ---- + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct KnownTeam { + pub id: String, + pub name: String, + pub epoch: u32, + /// The team identity's public key, hex. + pub identity: String, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct MemberJson { + x25519: SecretString, + ed25519: SecretString, + created: i64, + #[serde(default)] + teams: Vec, +} + +pub(crate) struct MemberState { + key: MemberKey, + created: i64, + teams: Vec, +} + +impl MemberState { + pub(crate) fn from_json(j: MemberJson) -> Option { + let key = MemberKey::from_secrets( + Zeroizing::new(unhex(j.x25519.expose())?), + Zeroizing::new(unhex(j.ed25519.expose())?), + ) + .ok()?; + Some(MemberState { key, created: j.created, teams: j.teams }) + } + + pub(crate) fn json(&self) -> MemberJson { + MemberJson { + x25519: SecretString::new(hex(self.key.x25519_secret().as_ref())), + ed25519: SecretString::new(hex(self.key.ed25519_secret().as_ref())), + created: self.created, + teams: self.teams.clone(), + } + } +} + +// ---- views ---- + +/// A team as the app shows it. No secret. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TeamView { + pub id: String, + pub name: String, + pub created: i64, + pub epoch: u32, + /// The team identity's public key, hex: what Fabrica pins. + pub identity: String, + pub members: Vec, + pub removed: Vec, + pub policy_rev: u32, + pub policy: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TargetView { + pub id: String, + pub kind: TargetKind, + pub name: String, + pub project: String, + pub env: String, + pub host: String, + pub user: String, + pub created: i64, + pub by: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignerView { + pub id: String, + pub name: String, + pub adapter: String, + pub endpoint: String, + pub account: String, + pub has_certificate: bool, + pub created: i64, + pub by: String, +} + +/// A target credential to add. `secret` is wiped on drop. +pub struct NewTarget { + pub kind: TargetKind, + pub name: String, + pub project: String, + pub env: String, + pub host: String, + pub user: String, + pub secret: SecretString, +} + +/// An external signer's credential to add (docs/TEAM.md, Authenticode). +pub struct NewSigner { + pub name: String, + pub adapter: String, + pub endpoint: String, + pub account: String, + pub secret: SecretString, + pub certificate: Vec, +} + +/// What removing a member leaves to do by hand: the credentials they could have seen. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Removal { + pub epoch: u32, + pub rotate: Vec, +} + +fn team_err(e: TeamError) -> Error { + Error::Team(e.to_string()) +} + +impl Vault { + fn team(&self) -> Result<&TeamState, Error> { + self.team.as_ref().ok_or(Error::NotATeam) + } + + fn team_mut(&mut self) -> Result<&mut TeamState, Error> { + self.team.as_mut().ok_or(Error::NotATeam) + } + + // ---- the member key, in a person's own vault ---- + + /// This vault's member key, if it has one. + pub fn member_key(&self) -> Option { + let m = self.member.as_ref()?; + MemberKey::from_secrets(m.key.x25519_secret(), m.key.ed25519_secret()).ok() + } + + /// This vault's member key, made now when it has none (a team vault never has one). The caller saves. + pub fn member_key_create(&mut self, now: i64) -> Result { + if self.team.is_some() { + return Err(Error::Team("a team vault holds no member key".into())); + } + if self.member.is_none() { + self.member = Some(MemberState { key: MemberKey::generate(), created: now, teams: Vec::new() }); + } + Ok(self.member.as_ref().expect("made").key.public()) + } + + /// The teams this member has opened, with the highest epoch seen. + pub fn member_teams(&self) -> Vec { + self.member.as_ref().map(|m| m.teams.clone()).unwrap_or_default() + } + + /// Records a team vault this member opened, and refuses one that is older than what was seen (a lower epoch) + /// or from another identity under the same id (`TeamRollback`). The caller saves this (own) vault. + pub fn member_note_team(&mut self, team: &Vault) -> Result<(), Error> { + let t = team.team()?; + let m = self.member.as_mut().ok_or(Error::Team("this vault has no member key".into()))?; + let identity = hex(&t.identity.public()); + match m.teams.iter_mut().find(|k| k.id == t.id) { + Some(k) if k.identity != identity || t.epoch < k.epoch => return Err(Error::TeamRollback), + Some(k) => { + k.epoch = t.epoch; + k.name = t.name.clone(); + } + None => m.teams.push(KnownTeam { id: t.id.clone(), name: t.name.clone(), epoch: t.epoch, identity }), + } + Ok(()) + } + + /// Forgets a team this member left or was removed from. + pub fn member_forget_team(&mut self, id: &str) -> bool { + let Some(m) = self.member.as_mut() else { return false }; + let before = m.teams.len(); + m.teams.retain(|k| k.id != id); + before != m.teams.len() + } + + // ---- creating and opening a team vault ---- + + /// A new team vault with `founder` as its only member, the default policy, and no keys yet + /// ([`Vault::team_create_keys`]). The caller saves it where the team keeps it. + pub fn create_team(name: &str, founder: &MemberKey, founder_name: &str, handles: &[String], now: i64) -> Result { + let name = name.trim(); + if !canon::text_ok(name, 64) || !canon::text_ok(founder_name.trim(), 64) || !handles_ok(handles) { + return Err(Error::Team("a team or member name is 1 to 64 printable characters".into())); + } + let id = custos_team::new_id(); + let identity = TeamIdentity::generate(); + let policy = Policy::default_for(&id); + let policy_sig = identity.sign_policy(&policy.canonical()); + let me = founder.public(); + let member = TeamMember { + id: me.id(), + name: founder_name.trim().into(), + handles: handles.to_vec(), + ed25519: hex(&me.ed25519), + x25519: hex(&me.x25519), + added: now, + by: String::new(), + code: String::new(), + }; + let mut state = TeamState { + id, + name: name.into(), + created: now, + epoch: 1, + identity, + members: vec![member], + removed: Vec::new(), + policy, + policy_sig, + targets: Vec::new(), + signers: Vec::new(), + seen: Vec::new(), + audit: Vec::new(), + }; + state.log(now, TeamAction::TeamCreated, &me.id(), Some(name.into())); + let mut v = Vault::empty_v2(crypto::random_key()); + v.team = Some(state); + v.team_write_slots()?; + Ok(v) + } + + /// Rewrites every member slot for the current key and epoch. + fn team_write_slots(&mut self) -> Result<(), Error> { + let t = self.team.as_ref().ok_or(Error::NotATeam)?; + let team: [u8; 16] = unhex(&t.id).ok_or(Error::Corrupted)?; + let mut slots = Vec::with_capacity(t.members.len()); + for m in &t.members { + let public = member_public(m).ok_or(Error::Corrupted)?; + let sealed = seal_team_key(&self.key, &public, &t.id, t.epoch).map_err(team_err)?; + slots.push(MemberSlot { team, member: public.id_bytes(), epoch: t.epoch, sealed }.raw()); + } + self.slots = slots; + Ok(()) + } + + /// The team id, epoch and member ids of a team vault file, from its header alone. + pub fn team_peek(bytes: &[u8]) -> Result<(String, u32, Vec), Error> { + let (header, _) = crate::format::Header::parse(bytes)?; + let slots = header.member_slots(); + let first = slots.first().ok_or(Error::NotATeam)?; + Ok((hex(&first.team), first.epoch, slots.iter().map(|s| hex(&s.member)).collect())) + } + + /// Opens a team vault with this member's key (docs/TEAM.md, "Opening"). `NotAMember` when it has no slot for + /// this member (never added, or removed before this file was written). + pub fn open_team(bytes: &[u8], key: &MemberKey) -> Result { + let (header, body_at) = crate::format::Header::parse(bytes)?; + if header.version != VERSION_2 || !header.is_team() { + return Err(Error::NotATeam); + } + let me = key.public().id_bytes(); + let slot = header.member_slots().into_iter().find(|s| s.member == me).ok_or(Error::NotAMember)?; + let team = hex(&slot.team); + let k = key.open_team_key(&slot.sealed, &team, slot.epoch).map_err(|_| Error::NotAMember)?; + let v = Vault::open_body(bytes, header, body_at, k)?; + let t = v.team.as_ref().ok_or(Error::Corrupted)?; + if t.id != team || t.epoch != slot.epoch || !t.members.iter().any(|m| m.id == key.id()) { + return Err(Error::Corrupted); + } + Ok(v) + } + + pub fn is_team(&self) -> bool { + self.team.is_some() + } + + pub fn team_view(&self) -> Option { + let t = self.team.as_ref()?; + Some(TeamView { + id: t.id.clone(), + name: t.name.clone(), + created: t.created, + epoch: t.epoch, + identity: hex(&t.identity.public()), + members: t.members.clone(), + removed: t.removed.clone(), + policy_rev: t.policy.rev, + policy: t.policy.envs.clone(), + }) + } + + /// The team identity's public key: what Fabrica and every target pin. + pub fn team_identity(&self) -> Result<[u8; 32], Error> { + Ok(self.team()?.identity.public()) + } + + pub fn team_roster(&self) -> Result, Error> { + Ok(self.team()?.roster()) + } + + pub fn team_audit(&self) -> Result, Error> { + Ok(self.team()?.audit.clone()) + } + + /// Renames the team. The caller saves. + pub fn team_rename(&mut self, name: &str) -> Result<(), Error> { + let name = name.trim(); + if !canon::text_ok(name, 64) { + return Err(Error::Team("a team name is 1 to 64 printable characters".into())); + } + self.team_mut()?.name = name.into(); + Ok(()) + } + + // ---- members ---- + + /// Adds a member whose join code (`match_code(x25519)`) the approving member `by` compared: `shown_code` is the + /// code their card showed; another code is `WrongMatch` and nothing changes. The caller saves and uploads. + pub fn team_add_member( + &mut self, + public: &MemberPublic, + name: &str, + handles: &[String], + by: &str, + shown_code: &str, + now: i64, + ) -> Result { + public.check().map_err(team_err)?; + if shown_code != public.join_code() { + return Err(team_err(TeamError::WrongMatch)); + } + let (name, id) = (name.trim(), public.id()); + if !canon::text_ok(name, 64) || !handles_ok(handles) { + return Err(Error::Team("a member's name is 1 to 64 printable characters".into())); + } + let t = self.team_mut()?; + if !t.members.iter().any(|m| m.id == by) { + return Err(team_err(TeamError::NotAMember)); + } + if t.members.iter().any(|m| m.id == id) { + return Err(Error::Team("already a member".into())); + } + if t.members.len() >= custos_team::MAX_MEMBERS { + return Err(Error::Team("a team has at most 32 members".into())); + } + t.members.push(TeamMember { + id: id.clone(), + name: name.into(), + handles: handles.to_vec(), + ed25519: hex(&public.ed25519), + x25519: hex(&public.x25519), + added: now, + by: by.into(), + code: shown_code.into(), + }); + t.log(now, TeamAction::MemberAdded, by, Some(name.into())); + self.team_write_slots()?; + Ok(id) + } + + /// Removes a member: a new team key and epoch, slots for the others only, the member taken off every + /// approver list. Returns the credentials to rotate at their source. The caller saves and uploads. + pub fn team_remove_member(&mut self, id: &str, by: &str, now: i64) -> Result { + let t = self.team_mut()?; + let at = t.members.iter().position(|m| m.id == id).ok_or(team_err(TeamError::NotAMember))?; + if !t.members.iter().any(|m| m.id == by) { + return Err(team_err(TeamError::NotAMember)); + } + if t.members.len() == 1 { + return Err(Error::Team("the last member cannot be removed".into())); + } + let gone = t.members.remove(at); + t.epoch = t.epoch.checked_add(1).ok_or(Error::Corrupted)?; + t.removed.push(RemovedMember { id: gone.id.clone(), name: gone.name.clone(), at: now, by: by.into(), epoch: t.epoch }); + if t.policy.envs.iter().any(|r| r.approvers.contains(&gone.id)) { + for r in t.policy.envs.iter_mut() { + r.approvers.retain(|a| *a != gone.id); + } + t.policy.rev += 1; + t.sign_policy(); + } + t.log(now, TeamAction::MemberRemoved, by, Some(gone.name.clone())); + let rotate = t + .targets + .iter() + .map(|x| format!("target {}", x.name)) + .chain(t.signers.iter().map(|s| format!("signer {}", s.name))) + .collect(); + let epoch = t.epoch; + // The new key: nothing written from here on opens with the old one. + self.key = crypto::random_key(); + self.team_write_slots()?; + Ok(Removal { epoch, rotate }) + } + + // ---- policy ---- + + pub fn team_policy(&self) -> Result { + Ok(self.team()?.policy.clone()) + } + + /// The policy's canonical text and the identity's signature over it. + pub fn team_policy_signed(&self) -> Result<(String, [u8; 64]), Error> { + let t = self.team()?; + Ok((t.policy.canonical(), t.policy_sig)) + } + + /// Sets one environment's rule; the approvers must be members. Re-signed, `rev` + 1. The caller saves. + pub fn team_set_rule(&mut self, rule: EnvRule, by: &str, now: i64) -> Result { + let t = self.team_mut()?; + if !t.members.iter().any(|m| m.id == by) { + return Err(team_err(TeamError::NotAMember)); + } + if !rule.approvers.iter().all(|a| t.members.iter().any(|m| m.id == *a)) { + return Err(Error::Team("an approver is not a member".into())); + } + let env = rule.env.clone(); + let detail = format!("{env}: {} approval(s){}", rule.approvals, if rule.others { ", not the author" } else { "" }); + t.policy.set_rule(rule).map_err(team_err)?; + t.sign_policy(); + t.log(now, TeamAction::PolicySet, by, Some(detail)); + Ok(t.policy.clone()) + } + + // ---- keys ---- + + /// Makes the team's keys once: `team-release` and `team-preview` (Ed25519), `team-cosign` and + /// `team-cosign-preview` (ECDSA P-256). The caller saves. + pub fn team_create_keys(&mut self, by: &str, now: i64) -> Result, Error> { + self.team()?; + if self.signing.get(TEAM_RELEASE).is_some() { + return Err(Error::SigningExists("team")); + } + let all = vec!["*".to_string()]; + let ed = |id: &str, name: &str, role| { + let k = custos_sign::new_ed25519(); + crate::signing::Key { + id: id.into(), + kind: KeyKind::Ed25519, + role, + name: name.into(), + secret: Secret::Ed25519(k.secret), + public: Some(k.public), + key_id: Some(k.key_id), + cert: None, + issuer: None, + created: now, + pipelines: all.clone(), + repos: all.clone(), + } + }; + let p256 = |id: &str, name: &str, role| crate::signing::Key { + id: id.into(), + kind: KeyKind::EcdsaP256, + role, + name: name.into(), + secret: Secret::P256(custos_sign::new_p256()), + public: None, + key_id: None, + cert: None, + issuer: None, + created: now, + pipelines: all.clone(), + repos: all.clone(), + }; + let keys = [ + ed(TEAM_RELEASE, "Team release", Role::Release), + ed(TEAM_PREVIEW, "Team preview (never trusted for releases)", Role::Test), + p256(TEAM_COSIGN, "Team container images", Role::Release), + p256(TEAM_COSIGN_PREVIEW, "Team container previews (never trusted for releases)", Role::Test), + ]; + let ids: Vec = keys.iter().map(|k| k.id.clone()).collect(); + self.signing.keys.extend(keys); + self.team_mut()?.log(now, TeamAction::KeysCreated, by, Some(ids.join(", "))); + Ok(ids) + } + + /// An Android key for one project (`apk`), scoped to it. Slow: RSA-4096. The caller saves. + pub fn team_create_android(&mut self, spec: &crate::signing::AndroidKey, by: &str, now: i64) -> Result { + self.team()?; + let id = self.signing_create_android(spec, now)?; + self.team_mut()?.log(now, TeamAction::KeysCreated, by, Some(id.clone())); + Ok(id) + } + + // ---- target credentials ---- + + pub fn team_add_target(&mut self, new: NewTarget, by: &str, now: i64) -> Result { + let t = self.team_mut()?; + if !t.members.iter().any(|m| m.id == by) { + return Err(team_err(TeamError::NotAMember)); + } + if !canon::text_ok(new.name.trim(), 64) + || !canon::ascii_ok(&new.project, 1, 128, b"._/-") + || !canon::env_ok(&new.env) + || (!new.host.is_empty() && !canon::text_ok(&new.host, 253)) + || (!new.user.is_empty() && !canon::text_ok(&new.user, 128)) + || new.secret.is_empty() + || new.secret.expose().len() > MAX_SECRET + { + return Err(Error::Team("a target needs a name, a project, an environment and a credential (≤ 64 KiB)".into())); + } + let id = short_id(); + let name = new.name.trim().to_owned(); + t.targets.push(Target { + id: id.clone(), + kind: new.kind, + name: name.clone(), + project: new.project, + env: new.env, + host: new.host, + user: new.user, + secret: new.secret, + created: now, + by: by.into(), + }); + t.log(now, TeamAction::TargetAdded, by, Some(name)); + Ok(id) + } + + pub fn team_targets(&self) -> Result, Error> { + Ok(self + .team()? + .targets + .iter() + .map(|t| TargetView { + id: t.id.clone(), + kind: t.kind, + name: t.name.clone(), + project: t.project.clone(), + env: t.env.clone(), + host: t.host.clone(), + user: t.user.clone(), + created: t.created, + by: t.by.clone(), + }) + .collect()) + } + + pub fn team_remove_target(&mut self, id: &str, by: &str, now: i64) -> Result<(), Error> { + let t = self.team_mut()?; + let at = t.targets.iter().position(|x| x.id == id).ok_or(Error::Team("no such target".into()))?; + let gone = t.targets.remove(at); + t.log(now, TeamAction::TargetRemoved, by, Some(gone.name)); + Ok(()) + } + + /// Releases a target credential for one deployment (docs/TEAM.md, "Target credentials"): the deployment is a + /// request this team vault signed for the target's project and environment within 25 hours, and this + /// (target, deployment) was never released before. Returns the plaintext to seal to the request's key. + /// The caller saves. + pub fn team_target_release(&mut self, request: &str, by: &str, now: i64) -> Result<(Zeroizing, TargetRequest), Error> { + let now_s = seconds(now); + let req = TargetRequest::check(request, now_s).map_err(team_err)?; + let signed: Vec<(String, String, i64)> = self + .signing + .audit + .iter() + .filter(|e| e.request.as_deref() == Some(req.deployment.as_str())) + .filter(|e| matches!(e.outcome, Outcome::Approved | Outcome::Auto)) + .map(|e| (e.context.repo.clone(), e.env.clone().unwrap_or_default(), e.at)) + .collect(); + let t = self.team_mut()?; + if req.team != t.id { + return Err(team_err(TeamError::WrongTeam)); + } + let target = t.targets.iter().find(|x| x.id == req.target).ok_or(Error::Team("no such target".into()))?; + let fits = signed.iter().any(|(project, env, at)| { + *project == target.project && *env == target.env && seconds(*at) + MAX_AHEAD_SECS > now_s + }); + if !fits { + return Err(Error::Team(format!( + "no release of {} to {} was signed here in the last 25 hours for this deployment", + target.project, target.env + ))); + } + let key = format!("target:{}:{}", target.id, req.deployment); + if t.is_seen(&key) { + return Err(team_err(TeamError::Replayed)); + } + let release = TargetRelease { + v: 1, + op: "target.release".into(), + team: t.id.clone(), + target: target.id.clone(), + kind: target.kind, + name: target.name.clone(), + host: target.host.clone(), + user: target.user.clone(), + secret: target.secret.expose().to_owned(), + deployment: req.deployment.clone(), + project: target.project.clone(), + env: target.env.clone(), + }; + let detail = format!("{} for deployment {}", target.name, &req.deployment[..12]); + let json = Zeroizing::new(serde_json::to_string(&release).map_err(|_| Error::Corrupted)?); + drop(release); + t.mark_seen(key, now_s); + t.log(now, TeamAction::TargetReleased, by, Some(detail)); + Ok((json, req)) + } + + // ---- external signers ---- + + pub fn team_add_signer(&mut self, new: NewSigner, by: &str, now: i64) -> Result { + let t = self.team_mut()?; + if !t.members.iter().any(|m| m.id == by) { + return Err(team_err(TeamError::NotAMember)); + } + if !canon::text_ok(new.name.trim(), 64) + || !canon::ascii_ok(&new.adapter, 1, 32, b"-") + || (!new.endpoint.is_empty() && !canon::text_ok(&new.endpoint, 500)) + || (!new.account.is_empty() && !canon::text_ok(&new.account, 200)) + || new.secret.expose().len() > MAX_SECRET + || new.certificate.len() > 16 * 1024 + { + return Err(Error::Team("an external signer needs a name and an adapter".into())); + } + let id = short_id(); + let name = new.name.trim().to_owned(); + t.signers.push(Signer { + id: id.clone(), + name: name.clone(), + adapter: new.adapter, + endpoint: new.endpoint, + account: new.account, + secret: new.secret, + certificate: new.certificate, + created: now, + by: by.into(), + }); + t.log(now, TeamAction::SignerAdded, by, Some(name)); + Ok(id) + } + + pub fn team_signers(&self) -> Result, Error> { + Ok(self + .team()? + .signers + .iter() + .map(|s| SignerView { + id: s.id.clone(), + name: s.name.clone(), + adapter: s.adapter.clone(), + endpoint: s.endpoint.clone(), + account: s.account.clone(), + has_certificate: !s.certificate.is_empty(), + created: s.created, + by: s.by.clone(), + }) + .collect()) + } + + pub fn team_remove_signer(&mut self, id: &str, by: &str, now: i64) -> Result<(), Error> { + let t = self.team_mut()?; + let at = t.signers.iter().position(|x| x.id == id).ok_or(Error::Team("no such signer".into()))?; + let gone = t.signers.remove(at); + t.log(now, TeamAction::SignerRemoved, by, Some(gone.name)); + Ok(()) + } + + // ---- signing ---- + + /// The request, checked for this team at `now`: canonical, not expired, not signed or refused here before. + pub fn team_check_request(&self, text: &str, now: i64) -> Result { + let t = self.team.as_ref().ok_or(TeamError::WrongTeam)?; + let req = SignRequest::check(text, seconds(now))?; + if req.team != t.id { + return Err(TeamError::WrongTeam); + } + if t.is_seen(&req.hash_hex()) { + return Err(TeamError::Replayed); + } + Ok(req) + } + + /// The policy evaluated for `req` with the statements that verify. + pub fn team_evaluate(&self, req: &SignRequest, statements: &[Statement]) -> Result { + let t = self.team()?; + let roster = t.roster(); + let approvers = verified_members(statements, req, &roster); + Ok(evaluate(&t.policy, &roster, &req.env, &req.author, &approvers)) + } + + /// Whether this member may approve `req` (for the card: greyed, with why). + pub fn team_may_approve(&self, req: &SignRequest, member: &str) -> Result<(), TeamError> { + let t = self.team.as_ref().ok_or(TeamError::WrongTeam)?; + may_approve(&t.policy, &t.roster(), &req.env, &req.author, member) + } + + /// A member approves without signing (the policy needs more): the statement to post. `shown_code` is the code + /// the card showed. + pub fn team_approve(&self, text: &str, key: &MemberKey, shown_code: &str, now: i64) -> Result { + let req = self.team_check_request(text, now)?; + self.team_may_approve(&req, &key.id())?; + approve(key, &req, shown_code, seconds(now)) + } + + /// Records a refusal by `by`; the request is never signed here afterwards. The caller saves. + pub fn team_refuse(&mut self, text: &str, by: &str, reason: &str, now: i64) -> Result<(), Error> { + let req = SignRequest::parse(text).map_err(team_err)?; + let entry = self.team_audit_entry(&req, Outcome::Refused, by, Some(reason.chars().take(200).collect()), None, &[], now); + self.signing.audit.push(entry); + let hash = req.hash_hex(); + self.team_mut()?.mark_seen(hash, seconds(now)); + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn team_audit_entry( + &self, + req: &SignRequest, + outcome: Outcome, + by: &str, + reason: Option, + signature: Option, + approvers: &[String], + now: i64, + ) -> AuditEntry { + let (key, kind) = match req.format { + Format::Minisign => (TEAM_RELEASE, SignKind::Minisign), + Format::TauriUpdater => (TEAM_RELEASE, SignKind::TauriUpdater), + Format::Cosign => (TEAM_COSIGN, SignKind::Cosign), + Format::Apk => ("android", SignKind::Apk), + Format::Authenticode => ("external", SignKind::Authenticode), + }; + AuditEntry { + at: now, + key: key.into(), + kind, + outcome, + via: Via::Remote, + context: Context { + repo: req.project.clone(), + commit: String::new(), + pipeline: req.env.clone(), + step: req.format.word().into(), + trigger: "team".into(), + file: req.artifact.name.clone(), + size: req.artifact.size, + sha256: req.artifact.sha256.clone(), + version: req.release.clone(), + }, + signature, + reason, + run: None, + by: Some(by.into()), + env: Some(req.env.clone()), + request: Some(req.hash_hex()), + approvers: approvers.to_vec(), + } + } + + /// Signs a request inside this member's Custos (docs/TEAM.md, "Signing"): the other members' statements, plus + /// this member's own approval (its `shown_code` must be the request's), must meet the policy; at 0 approvals + /// the test-role key signs and no code is needed. Records the request as seen and an audit entry, and returns + /// the reply to seal. A refusal changes nothing. The caller saves. + pub fn team_sign( + &mut self, + text: &str, + statements: &[Statement], + key: &MemberKey, + shown_code: Option<&str>, + external: Option<&dyn ExternalSigner>, + now: i64, + ) -> Result { + let now_s = seconds(now); + let req = self.team_check_request(text, now)?; + let t = self.team.as_ref().ok_or(TeamError::WrongTeam)?; + let roster = t.roster(); + let me = key.id(); + let me_member = roster.iter().find(|m| m.id == me).ok_or(TeamError::NotAMember)?; + let rule = t.policy.rule(&req.env).ok_or(TeamError::UnknownEnv)?; + let mut approvals: Vec = statements + .iter() + .filter(|s| s.member != me && s.verify(&req, &roster).is_ok()) + .cloned() + .collect(); + if rule.approvals > 0 { + let code = shown_code.ok_or(TeamError::WrongMatch)?; + may_approve(&t.policy, &roster, &req.env, &req.author, &me)?; + approvals.push(approve(key, &req, code, now_s)?); + } + let approvers = verified_members(&approvals, &req, &roster); + let eval = evaluate(&t.policy, &roster, &req.env, &req.author, &approvers); + let role = eval.clone().into_result()?; + let (key_id, envelope, payload, public) = self.team_envelope(&req, role, external, now_s)?; + let t = self.team.as_ref().expect("checked"); + let (policy_text, policy_sig) = (t.policy.canonical(), t.policy_sig); + let proof = ProofBody { + team: t.id.clone(), + request: req.hash_hex(), + env: req.env.clone(), + author: req.author.clone(), + policy: policy_text, + policy_sig, + roster: roster.clone(), + approvals: if role == KeyRole::Release { approvals } else { Vec::new() }, + signer: me.clone(), + role, + signature: custos_sign::sha256_hex(envelope.as_bytes()), + at: now_s, + } + .sign(&t.identity); + let reply = SignReply { + v: 1, + op: "sign.reply".into(), + request: req.hash_hex(), + format: req.format.word().into(), + signature: envelope.clone(), + payload, + key: ReplyKey { id: key_id.clone(), public }, + signer: ReplySigner { member: me.clone(), name: me_member.name.clone() }, + proof, + }; + let outcome = if role == KeyRole::Release { Outcome::Approved } else { Outcome::Auto }; + let mut entry = self.team_audit_entry( + &req, + outcome, + &me, + None, + Some(custos_sign::sha256_hex(envelope.as_bytes())), + &eval.counted, + now, + ); + entry.key = key_id; + self.signing.audit.push(entry); + let hash = req.hash_hex(); + self.team.as_mut().expect("checked").mark_seen(hash, now_s); + Ok(reply) + } + + /// The key that signs `req` under `role`, and what it makes: (key id, envelope, cosign payload, public part). + fn team_envelope( + &self, + req: &SignRequest, + role: KeyRole, + external: Option<&dyn ExternalSigner>, + now_s: u64, + ) -> Result<(String, String, Option, String), TeamError> { + let no_key = |what: &'static str| TeamError::Invalid(what); + let want = if role == KeyRole::Release { Role::Release } else { Role::Test }; + match req.format { + Format::Minisign | Format::TauriUpdater => { + let id = if role == KeyRole::Release { TEAM_RELEASE } else { TEAM_PREVIEW }; + let k = self.signing.get(id).ok_or(no_key("the team has no signing keys yet"))?; + let (Secret::Ed25519(s), Some(kid), Some(public)) = (&k.secret, k.key_id, k.public) else { + return Err(no_key("the team's minisign key is not Ed25519")); + }; + let minisig = custos_sign::minisign(s, &kid, &req.artifact_digest, &req.artifact.name, now_s) + .map_err(|_| TeamError::Invalid("the digest or file name cannot be signed"))?; + let envelope = + if req.format == Format::TauriUpdater { custos_sign::tauri_updater(&minisig) } else { minisig }; + Ok((id.into(), envelope, None, custos_sign::minisign_public(&public, &kid))) + } + Format::Cosign => { + let id = if role == KeyRole::Release { TEAM_COSIGN } else { TEAM_COSIGN_PREVIEW }; + let k = self.signing.get(id).ok_or(no_key("the team has no cosign key yet"))?; + let Secret::P256(s) = &k.secret else { + return Err(no_key("the team's cosign key is not P-256")); + }; + let payload = custos_sign::cosign_payload(&req.image, &req.artifact_digest) + .map_err(|_| TeamError::Invalid("the image or digest cannot be signed"))?; + let sig = custos_sign::cosign(s, &payload).map_err(|_| TeamError::BadKey)?; + let public = s.public_pem().map_err(|_| TeamError::BadKey)?; + Ok((id.into(), b64(&sig), Some(payload), public)) + } + Format::Apk => { + let k = self + .signing + .keys + .iter() + .find(|k| k.kind == KeyKind::Android && k.role == want && k.repos.iter().any(|r| *r == req.project)) + .ok_or(no_key("the team has no Android key for this project and role"))?; + let Secret::Rsa(s) = &k.secret else { + return Err(no_key("an Android key is RSA")); + }; + let sig = custos_sign::apk(s, &req.artifact_digest).map_err(|_| TeamError::Invalid("APK digests"))?; + Ok((k.id.clone(), b64(&sig), None, custos_sign::cert_pem(k.cert.as_deref().unwrap_or_default()))) + } + Format::Authenticode => { + if role != KeyRole::Release { + return Err(TeamError::Invalid("Authenticode is never signed without an approval")); + } + let t = self.team.as_ref().ok_or(TeamError::WrongTeam)?; + let s = t.signers.first().ok_or(no_key("the team has no external signer"))?; + let external = external.ok_or(no_key("no adapter for the team's external signer"))?; + let digest: [u8; 32] = + req.artifact_digest.as_slice().try_into().map_err(|_| TeamError::Invalid("digest"))?; + let cred = SignerCredential { + id: &s.id, + name: &s.name, + adapter: &s.adapter, + endpoint: &s.endpoint, + account: &s.account, + secret: s.secret.expose(), + }; + let sig = external + .sign_digest(&cred, &digest) + .map_err(|_| TeamError::Invalid("the external signer did not sign"))?; + let public = + if s.certificate.is_empty() { String::new() } else { custos_sign::cert_pem(&s.certificate) }; + Ok((format!("signer:{}", s.id), b64(&sig), None, public)) + } + } + } +} diff --git a/crates/custos-vault/tests/team.rs b/crates/custos-vault/tests/team.rs new file mode 100644 index 0000000..6d0202e --- /dev/null +++ b/crates/custos-vault/tests/team.rs @@ -0,0 +1,441 @@ +//! Team vaults (docs/TEAM.md, core 0.18.0): opening, adding and removing members, the policy, signing every +//! format, replays, target credentials. + +use custos_team::external::{ExternalSigner, SignerCredential}; +use custos_team::policy::{EnvRule, KeyRole}; +use custos_team::request::{Artifact, Format, SignRequest, TargetRequest}; +use custos_team::target::{TargetKind, TargetRelease}; +use custos_team::{MemberKey, TeamError, verify_proof}; +use custos_vault::{Error, NewSigner, NewTarget, SecretString, Vault}; + +const NOW: i64 = 1_794_000_000_000; +const NOW_S: u64 = 1_794_000_000; + +struct Team { + vault: Vault, + a: MemberKey, + b: MemberKey, +} + +/// Mark founds a team, makes its keys and adds Petra (comparing her join code). +fn team() -> Team { + let a = MemberKey::generate(); + let b = MemberKey::generate(); + let mut vault = Vault::create_team("Domi", &a, "Mark", &["mnovak".into()], NOW).unwrap(); + vault.team_create_keys(&a.id(), NOW).unwrap(); + let code = b.public().join_code(); + vault.team_add_member(&b.public(), "Petra", &["petra".into()], &a.id(), &code, NOW).unwrap(); + Team { vault, a, b } +} + +fn request(vault: &Vault, env: &str, author: &str, format: Format, fabrica: &custos_seal::Recipient) -> String { + let (digest, image) = match format { + Format::Minisign | Format::TauriUpdater => (custos_sign::blake2b512(b"the installer").to_vec(), ""), + Format::Apk => (vec![5u8; 128], ""), + Format::Cosign => (vec![6u8; 32], "registry.example/domi/arca"), + Format::Authenticode => (vec![7u8; 32], ""), + }; + SignRequest { + team: vault.team_view().unwrap().id, + id: custos_team::new_id(), + project: "mnovak/Arca".into(), + release: "0.7.0".into(), + env: env.into(), + author: author.into(), + format, + artifact: Artifact { name: "Arca_0.7.0_x64-setup.exe".into(), size: 13, sha256: custos_sign::sha256_hex(b"the installer") }, + artifact_digest: digest.to_vec(), + image: image.into(), + public: fabrica.public(), + expires: NOW_S + 3600, + } + .canonical() +} + +#[test] +fn members_open_the_team_vault_and_outsiders_do_not() { + let t = team(); + let bytes = t.vault.to_bytes().unwrap(); + let (id, epoch, members) = Vault::team_peek(&bytes).unwrap(); + assert_eq!((id.as_str(), epoch, members.len()), (t.vault.team_view().unwrap().id.as_str(), 1, 2)); + for k in [&t.a, &t.b] { + let v = Vault::open_team(&bytes, k).unwrap(); + assert!(v.is_team()); + assert_eq!(v.team_view().unwrap().members.len(), 2); + assert_eq!(v.signing_keys().len(), 4); + } + assert!(matches!(Vault::open_team(&bytes, &MemberKey::generate()), Err(Error::NotAMember))); + // A team vault is not a two-factor vault, and a personal vault is not a team vault. + assert!(Vault::factor_kinds(&bytes).unwrap().is_empty()); + let mut personal = Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 }).unwrap(); + assert!(matches!(Vault::open_team(&personal.to_bytes().unwrap(), &t.a), Err(Error::NotATeam))); + // A changed header byte (a member slot moved to another epoch) does not open. + let mut moved = bytes.clone(); + moved[9 + 3 + 32] ^= 1; + assert!(Vault::open_team(&moved, &t.a).is_err()); + // The member key lives in the member's own vault and survives a save. + personal.member_key_create(NOW).unwrap(); + let again = Vault::open(&personal.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(again.member_key().unwrap().id(), personal.member_key().unwrap().id()); +} + +#[test] +fn a_wrong_join_code_adds_nobody() { + let mut t = team(); + let c = MemberKey::generate(); + let wrong = if c.public().join_code() == "111111" { "222222" } else { "111111" }; + let e = t.vault.team_add_member(&c.public(), "Eve", &[], &t.a.id(), wrong, NOW).unwrap_err(); + assert!(e.to_string().contains("match code"), "{e}"); + assert_eq!(t.vault.team_view().unwrap().members.len(), 2); + // An outsider cannot add anyone either. + let code = c.public().join_code(); + assert!(t.vault.team_add_member(&c.public(), "Eve", &[], &c.id(), &code, NOW).is_err()); +} + +/// Mandatory: removing a member rotates the team key; the old member cannot unwrap anything created after. +#[test] +fn a_removed_member_cannot_open_anything_written_after() { + let mut t = team(); + let before = t.vault.to_bytes().unwrap(); + assert!(Vault::open_team(&before, &t.b).is_ok()); + t.vault + .team_add_target( + NewTarget { + kind: TargetKind::SshKey, + name: "web-1".into(), + project: "mnovak/Arca".into(), + env: "production".into(), + host: "web-1.example".into(), + user: "deploy".into(), + secret: SecretString::from("-----BEGIN OPENSSH PRIVATE KEY-----\nold\n"), + }, + &t.a.id(), + NOW, + ) + .unwrap(); + let removal = t.vault.team_remove_member(&t.b.id(), &t.a.id(), NOW + 1).unwrap(); + assert_eq!(removal.epoch, 2); + assert_eq!(removal.rotate, vec!["target web-1".to_string()]); + // Something created after the removal. + t.vault + .team_add_target( + NewTarget { + kind: TargetKind::Registry, + name: "registry".into(), + project: "mnovak/Arca".into(), + env: "production".into(), + host: String::new(), + user: String::new(), + secret: SecretString::from("new-registry-token-after-removal"), + }, + &t.a.id(), + NOW + 2, + ) + .unwrap(); + let after = t.vault.to_bytes().unwrap(); + // B has no slot, and B's old slot (from the earlier file) does not open the new body. + assert!(matches!(Vault::open_team(&after, &t.b), Err(Error::NotAMember))); + let (_, epoch, members) = Vault::team_peek(&after).unwrap(); + assert_eq!((epoch, members), (2, vec![t.a.id()])); + let mut spliced = Vec::new(); + let (hb, _) = header_len(&before); + let (ha, _) = header_len(&after); + spliced.extend_from_slice(&before[..hb]); + spliced.extend_from_slice(&after[ha..]); + assert!(Vault::open_team(&spliced, &t.b).is_err(), "the old key does not open the new body"); + // The new token is in no byte of the file B can read. + assert!(!contains(&after, b"new-registry-token")); + // A still opens it, at epoch 2, and B is listed as removed. + let v = Vault::open_team(&after, &t.a).unwrap(); + let view = v.team_view().unwrap(); + assert_eq!((view.epoch, view.members.len(), view.removed[0].name.as_str()), (2, 1, "Petra")); + // The last member cannot be removed. + let mut v = v; + assert!(v.team_remove_member(&t.a.id(), &t.a.id(), NOW).is_err()); +} + +fn header_len(bytes: &[u8]) -> (usize, ()) { + let count = bytes[8] as usize; + let mut at = 9; + for _ in 0..count { + let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize; + at += 3 + len; + } + (at + 24, ()) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + hay.windows(needle.len()).any(|w| w == needle) +} + +#[test] +fn a_member_refuses_an_older_copy_or_another_identity() { + let mut t = team(); + let mut own = Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 }).unwrap(); + // Mark's own vault holds his member key; the team was made with the same key. + let c = MemberKey::generate(); + let code = c.public().join_code(); + t.vault.team_add_member(&c.public(), "Third", &[], &t.a.id(), &code, NOW).unwrap(); + own.member_key_create(NOW).unwrap(); + let old = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap(); + t.vault.team_remove_member(&c.id(), &t.a.id(), NOW).unwrap(); + let new = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap(); + own.member_note_team(&new).unwrap(); + assert!(matches!(own.member_note_team(&old), Err(Error::TeamRollback))); + let impostor = Vault::create_team("Domi", &t.a, "Mark", &[], NOW).unwrap(); + own.member_note_team(&impostor).unwrap(); // another id: a team of its own + assert_eq!(own.member_teams().len(), 2); +} + +#[test] +fn the_policy_is_set_per_environment_signed_and_kept() { + let mut t = team(); + let p = t + .vault + .team_set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![t.b.id()] }, &t.a.id(), NOW) + .unwrap(); + assert_eq!(p.rev, 2); + assert!(t.vault.team_set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec!["ab".repeat(16)] }, &t.a.id(), NOW).is_err()); + let v = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.b).unwrap(); + let (text, sig) = v.team_policy_signed().unwrap(); + assert!(custos_team::member::verify_policy_sig(&v.team_identity().unwrap(), &text, &sig)); + assert_eq!(v.team_policy().unwrap().rule("staging").unwrap().approvers, vec![t.b.id()]); + assert!(v.team_audit().unwrap().iter().any(|e| e.detail.as_deref() == Some("staging: 1 approval(s), not the author"))); +} + +/// Mandatory: a signing request with a wrong or replayed match code is refused. +#[test] +fn wrong_and_replayed_match_codes_are_refused() { + let mut t = team(); + let fabrica = custos_seal::Recipient::generate(); + let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica); + let code = fabrica.match_code(); + let wrong = if code == "000000" { "000001" } else { "000000" }; + // Petra's card showed another code: nothing is signed, nothing recorded as seen. + assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(wrong), None, NOW).unwrap_err(), TeamError::WrongMatch); + assert_eq!(t.vault.team_approve(&text, &t.b, wrong, NOW).unwrap_err(), TeamError::WrongMatch); + // The author may not approve production in a team of two. + assert!(matches!(t.vault.team_sign(&text, &[], &t.a, Some(&code), None, NOW), Err(TeamError::NotEligible(_)))); + // Petra with the right code signs. + let reply = t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap(); + // The same request again (a replay): refused, by this vault, whoever asks. + assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::Replayed); + assert_eq!(t.vault.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed); + // ... also after a save and reopen, and in Mark's copy once he has the saved file. + let reopened = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap(); + assert_eq!(reopened.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed); + // Petra's approval statement from this request does not count for another one. + let other = request(&t.vault, "production", "mnovak", Format::Minisign, &custos_seal::Recipient::generate()); + let statements: Vec<_> = custos_team::proof::ProofBody::parse(&reply.proof.text).unwrap().approvals; + let req = SignRequest::parse(&other).unwrap(); + let eval = t.vault.team_evaluate(&req, &statements).unwrap(); + assert!(eval.counted.is_empty()); + // An expired request. + let late = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica); + assert_eq!(t.vault.team_sign(&late, &[], &t.a, Some(&code), None, NOW + 3_601_000).unwrap_err(), TeamError::Expired); +} + +#[test] +fn two_approvals_collect_statements_and_the_last_approver_signs() { + let mut t = team(); + let c = MemberKey::generate(); + let code = c.public().join_code(); + t.vault.team_add_member(&c.public(), "Jan", &[], &t.a.id(), &code, NOW).unwrap(); + t.vault.team_set_rule(EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] }, &t.a.id(), NOW).unwrap(); + let fabrica = custos_seal::Recipient::generate(); + let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica); + let code = fabrica.match_code(); + // Petra alone is not enough: she approves (a statement), she does not sign. + assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::NeedMore(1)); + let petra = t.vault.team_approve(&text, &t.b, &code, NOW).unwrap(); + // Mark's statement (the author) does not count; Jan's does, and Jan signs. + let reply = t.vault.team_sign(&text, &[petra.clone()], &c, Some(&code), None, NOW).unwrap(); + let v = verify_proof(&reply.proof, &t.vault.team_identity().unwrap(), &text, reply.envelope()).unwrap(); + assert_eq!(v.approvers.len(), 2); + assert_eq!(v.signer, c.id()); + let audit = t.vault.signing_audit().last().unwrap().clone(); + assert_eq!(audit.by.as_deref(), Some(c.id().as_str())); + assert_eq!(audit.approvers.len(), 2); + assert_eq!(audit.env.as_deref(), Some("production")); +} + +struct FakeHsm(custos_sign::RsaSecret); + +impl ExternalSigner for FakeHsm { + fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result, String> { + if signer.secret != "hsm-pin" { + return Err("wrong credential".into()); + } + custos_sign::authenticode(&self.0, digest).map_err(|e| e.to_string()) + } +} + +/// Every format signs and the proof checks; the signatures verify (minisign-verify is minisign's and Tauri's own +/// verifier; cosign with p256 here and openssl in custos-sign's tests). +#[test] +fn every_format_signs_with_the_right_key_and_verifies() { + let mut t = team(); + let identity = t.vault.team_identity().unwrap(); + t.vault + .team_create_android( + &custos_vault::signing::AndroidKey { + id: "arca-android".into(), + name: "Arca Android".into(), + cn: "Arca".into(), + o: "Domi".into(), + c: "CZ".into(), + role: custos_vault::signing::Role::Release, + pipelines: vec!["*".into()], + repos: vec!["mnovak/Arca".into()], + }, + &t.a.id(), + NOW, + ) + .unwrap(); + let hsm = custos_sign::new_root("Fake HSM", 1).unwrap(); + t.vault + .team_add_signer( + NewSigner { + name: "Fake cloud signer".into(), + adapter: "command".into(), + endpoint: "https://signer.example".into(), + account: "domi".into(), + secret: SecretString::from("hsm-pin"), + certificate: hsm.cert_der.clone(), + }, + &t.a.id(), + NOW, + ) + .unwrap(); + let ext = FakeHsm(hsm.secret); + for format in [Format::Minisign, Format::TauriUpdater, Format::Cosign, Format::Apk, Format::Authenticode] { + let fabrica = custos_seal::Recipient::generate(); + let text = request(&t.vault, "production", "mnovak", format, &fabrica); + let reply = t.vault.team_sign(&text, &[], &t.b, Some(&fabrica.match_code()), Some(&ext), NOW).unwrap(); + let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap(); + assert_eq!(v.role, KeyRole::Release, "{format:?}"); + assert_eq!(reply.signer.name, "Petra"); + match format { + Format::Minisign | Format::TauriUpdater => { + assert_eq!(reply.key.id, "team-release"); + let minisig = if format == Format::TauriUpdater { + custos_sign::tauri_updater_open(&reply.signature).unwrap() + } else { + reply.signature.clone() + }; + let pk = minisign_verify::PublicKey::decode(&reply.key.public).unwrap(); + pk.verify(b"the installer", &minisign_verify::Signature::decode(&minisig).unwrap(), true).unwrap(); + } + Format::Cosign => { + assert_eq!(reply.key.id, "team-cosign"); + let payload = reply.payload.as_deref().unwrap(); + assert!(payload.contains("\"docker-reference\":\"registry.example/domi/arca\"")); + let der = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap(); + assert!(custos_sign::cosign_verify(&reply.key.public, payload.as_bytes(), &der)); + } + Format::Apk => { + assert_eq!(reply.key.id, "arca-android"); + let sig = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap(); + assert_eq!(sig.len(), 2 * 512); + assert!(reply.key.public.starts_with("-----BEGIN CERTIFICATE-----")); + } + Format::Authenticode => { + assert!(reply.key.id.starts_with("signer:")); + assert_eq!(data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap().len(), 384); + } + } + } + // Preview: 0 approvals, the test key, no code needed; a release key never signs it. + let fabrica = custos_seal::Recipient::generate(); + let text = request(&t.vault, "preview", "mnovak", Format::Minisign, &fabrica); + let reply = t.vault.team_sign(&text, &[], &t.a, None, None, NOW).unwrap(); + assert_eq!(reply.key.id, "team-preview"); + let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap(); + assert_eq!(v.role, KeyRole::Test); + // Authenticode is never signed without an approval, and not without the adapter. + let text = request(&t.vault, "preview", "mnovak", Format::Authenticode, &fabrica); + assert!(t.vault.team_sign(&text, &[], &t.a, None, Some(&ext), NOW).is_err()); + let text = request(&t.vault, "production", "mnovak", Format::Authenticode, &custos_seal::Recipient::generate()); + let code = SignRequest::parse(&text).unwrap().match_code(); + assert!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).is_err()); +} + +#[test] +fn a_target_credential_is_released_once_for_a_signed_deployment_of_its_project_and_environment() { + let mut t = team(); + let target = t + .vault + .team_add_target( + NewTarget { + kind: TargetKind::Kubeconfig, + name: "prod cluster".into(), + project: "mnovak/Arca".into(), + env: "production".into(), + host: "k8s.example".into(), + user: "fabrica".into(), + secret: SecretString::from("apiVersion: v1\nkind: Config\n"), + }, + &t.a.id(), + NOW, + ) + .unwrap(); + assert!(!format!("{:?}", t.vault.team_targets().unwrap()).contains("apiVersion")); + let team_id = t.vault.team_view().unwrap().id; + let fabrica = custos_seal::Recipient::generate(); + let ask = |deployment: &str| TargetRequest { + team: team_id.clone(), + id: custos_team::new_id(), + target: target.clone(), + deployment: deployment.into(), + public: fabrica.public(), + expires: NOW_S + 600, + } + .canonical(); + // No signed deployment yet. + let unsigned = "ab".repeat(32); + assert!(t.vault.team_target_release(&ask(&unsigned), &t.b.id(), NOW).is_err()); + // A staging deployment is not a production one. + let staging = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica); + let r = t.vault.team_sign(&staging, &[], &t.a, Some(&fabrica.match_code()), None, NOW).unwrap(); + assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).is_err()); + let prod = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica); + let r = t.vault.team_sign(&prod, &[], &t.b, Some(&fabrica.match_code()), None, NOW).unwrap(); + let (json, req) = t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap(); + let released: TargetRelease = serde_json::from_str(&json).unwrap(); + assert_eq!((released.secret.as_str(), released.env.as_str()), ("apiVersion: v1\nkind: Config\n", "production")); + assert!(!format!("{released:?}").contains("apiVersion")); + assert_eq!(req.reply_context(), format!("team-target:{}", req.id).into_bytes()); + // Once per deployment. + assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap_err().to_string().contains("replay")); + // Too late: a deployment signed more than 25 hours ago. + assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW + 26 * 3_600_000).is_err()); + assert!(t.vault.team_audit().unwrap().iter().any(|e| e.action == custos_vault::TeamAction::TargetReleased)); +} + +#[test] +fn nothing_secret_prints_or_reaches_a_view() { + let mut t = team(); + t.vault + .team_add_signer( + NewSigner { + name: "HSM".into(), + adapter: "command".into(), + endpoint: String::new(), + account: String::new(), + secret: SecretString::from("very-secret-pin-123"), + certificate: vec![], + }, + &t.a.id(), + NOW, + ) + .unwrap(); + let shown = format!( + "{:?} {:?} {:?} {:?}", + t.vault, + t.vault.team_view(), + t.vault.team_signers().unwrap(), + serde_json::to_string(&t.vault.team_view()).unwrap() + ); + assert!(!shown.contains("very-secret-pin-123")); + assert!(!contains(&t.vault.to_bytes().unwrap(), b"very-secret-pin-123")); +} diff --git a/docs/FACTORS.md b/docs/FACTORS.md index 9162567..537cbdc 100644 --- a/docs/FACTORS.md +++ b/docs/FACTORS.md @@ -80,6 +80,9 @@ is the whole header, as in v1. - 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed. - At most one recovery slot (kind 5, core 0.17.0), of exactly 108 bytes, and none in a machine store. +- A **team vault** (core 0.18.0, docs/TEAM.md) has 1 ..= 32 member slots (kind 6, 144 bytes) and no other slot; + a file that mixes member slots with any other kind is malformed. It is opened with `Vault::open_team` and a + member key, never with factors. - A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed. - Argon2 limits as in v1, checked before any work. - Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work. diff --git a/docs/FORMAT.md b/docs/FORMAT.md index fe4775a..5c50fe8 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -132,6 +132,10 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - `provision` (optional, core 0.11.0): the Provisio audit, every outcome of a server's *ask* or *offer* (the app's docs/10_provisio.md). An older Custos ignores it when it reads and drops it when it saves, so every Custos that saves the vault must be 0.11.0 or later. See "The provision audit" below. +- `kind`, `team` (core 0.18.0): a team vault's body is `"kind": "team"` with the `team` member (docs/TEAM.md); no + other vault has either, and a team vault has no `factors`, `identity` or `member`. +- `member` (optional, core 0.18.0): a person's member key and the teams it opened (docs/TEAM.md). An older Custos + drops it when it saves, so every Custos that saves a member's vault must be 0.18.0 or later. - `security` (optional, core 0.12.0): the security level, the hardening checklist and their audit (the app's docs/11_runs_and_levels.md). An older Custos ignores it when it reads and drops it when it saves (the level falls back to Standard, the checklist to unticked), so every Custos that saves the vault must be 0.12.0 or later. See diff --git a/docs/SIGNING.md b/docs/SIGNING.md index b5f53be..30ce629 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) +# 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) 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 @@ -46,6 +46,7 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul | `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random | | `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random | | `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random | +| `ecdsa-p256` (core 0.18.0) | ECDSA P-256; `secret` is the 32-byte scalar; a team vault's cosign key (docs/TEAM.md) | only `cosign`, only through `team_sign` | random | | `android` (core 0.14.0) | RSA-4096; `secret` PKCS#8 DER; `cert` a self-signed X.509 v3 certificate, valid 100 years, no EKU, under no root | only `apk` | random | `role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and @@ -195,6 +196,14 @@ the digests and answers with placeholder signatures (the signed data does not de Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did not record. It verifies the result with apksig's verifier before it writes the APK. +### Team kinds (core 0.18.0) + +`tauri-updater` (the base64 of a `minisign` file) and `cosign` (ECDSA P-256 over cosign's simple-signing payload) +exist only in team vaults and are signed only by `Vault::team_sign` (docs/TEAM.md); `signing_sign` refuses them +(`invalid`). A team audit entry carries `by`, `env`, `request` and `approvers`; its context's `repo` is the project, +`pipeline` the environment, `version` the release, `trigger` `team`. A core before 0.18.0 refuses a vault holding +any of these values (`Corrupted`); only team vaults do. + ## Standing approvals (core 0.16.0) A release key always asks. A **standing approval** is Mark's answer kept: "always allow this, for this repository". diff --git a/docs/TEAM.md b/docs/TEAM.md new file mode 100644 index 0000000..98ed813 --- /dev/null +++ b/docs/TEAM.md @@ -0,0 +1,289 @@ +# Team vaults, policies and team signing (core 0.18.0) + +A **team vault** is a `.custos` file that a small team (1 to 32 people) shares: the team's release-signing keys, +its target credentials, its external-signer credentials and its approval policy. Each member opens it with the +**member key** kept in their own vault, so any member's Custos can open it and no server ever can. The pure parts +live here: the member key, the member slot, the team body, policy evaluation, the `sign.request` canonical form, +approval statements, the policy proof and the signature envelopes. Transport, prompts and storage are the app's +(Custos `docs/27_team_vault.md`). + +``` +member's own vault (two factors) ──► member key (X25519 + Ed25519) + │ opens its member slot +team vault ── member slots: team key sealed to each member's X25519 key + └─ body (XChaCha20-Poly1305 under the team key): roster, policy, signing keys, targets, signers, audit +``` + +## The member key + +Every person who is in a team has one member key, made at random the first time they create or join a team, and +kept in their own vault (body member `member`, below). It never leaves that vault. + +| Part | | +| :-- | :-- | +| `x25519` | 32-byte X25519 secret: the team key is sealed to its public half (custos-seal) | +| `ed25519` | 32-byte Ed25519 seed: signs the member's approvals | +| member id | the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 public ‖ x25519 public)`, 32 hex | + +The **join code** a joining member's screen shows is `custos_seal::match_code(x25519 public)` (SEAL.md): the member +who approves the join compares it with the code on their own card. + +In the member's own vault: + +```json +"member": { + "x25519": "<64 hex>", "ed25519": "<64 hex>", "created": 1794000000000, + "teams": [ { "id": "<32 hex>", "name": "Domi", "epoch": 3, "identity": "<64 hex: the team identity's public key>" } ] +} +``` + +`teams` is what this member has seen: a team vault whose identity differs, or whose epoch is lower than the one +recorded, is refused (`TeamRollback`): an old copy of the file, or a fork made with an old team key, does not open +as current. An older Custos drops `member` when it saves: every Custos that saves a member's vault must be 0.18.0 +or later (the member would have to be invited again). + +## The team vault file + +Version 2 (FACTORS.md) with one new slot kind and no factor slots: + +``` +kind 6, member slot (144 bytes) +16 team id +16 member id +4 epoch u32 +108 sealed team key custos-seal box of the 32-byte team key, to the member's X25519 key, + context "custos team key v1:::" +``` + +- A team vault has 1 ..= 32 member slots and **only** member slots; a file that mixes member slots with factor, + pair, single or recovery slots is malformed. All member slots carry the same team id and epoch. +- The slot is authenticated by its box: the context binds team, epoch and member, so a slot moved to another + member, team or epoch does not open. The body AAD is the whole header, as for every vault. +- **Opening** (`Vault::open_team(bytes, &member_key)`): the slot with this member's id, its box opened, the body + decrypted with the team key. The body must be `"kind": "team"` with the same team id and epoch, and the member + must be on its roster; else `NotAMember` (no slot, a removed member) or `Corrupted`. +- A core before 0.18.0 skips kind 6, finds no factor slot and refuses the file: it never misreads a team vault. + +### Rotation: removing a member + +`team_remove_member` makes a **new random team key**, raises the epoch and writes member slots for the remaining +members only. The body (every key, credential and policy) is encrypted under the new key at the next save, so the +removed member cannot open anything written after. What they could read before stays read: Custos never hands out +a signing key, but the target and signer credentials they could reveal should be rotated at their source (the +app's card says which). + +The **team identity** (an Ed25519 key in the body) does not rotate: it is what Fabrica and every target pin, and a +removed member never held it outside Custos. Rotating it is a new team. + +## The team body + +```json +{ "format": 2, "kind": "team", "items": [], + "team": { + "id": "<32 hex>", "name": "Domi", "created": 1794000000000, "epoch": 1, + "identity": { "secret": "<64 hex>", "public": "<64 hex>" }, + "members": [ { "id": "<32 hex>", "name": "Mark", "handles": ["mnovak"], "ed25519": "<64 hex>", + "x25519": "<64 hex>", "added": 1794000000000, "by": "", + "code": "684361" } ], + "removed": [ { "id": "<32 hex>", "name": "Old", "at": 1794100000000, "by": "", "epoch": 2 } ], + "policy": { "text": "", "sig": "" }, + "targets": [ { "id": "<16 hex>", "kind": "ssh-key", "name": "web-1", "project": "mnovak/Arca", "env": "production", + "host": "web-1.example", "user": "deploy", "secret": "", "created": 1794000000000, + "by": "" } ], + "signers": [ { "id": "<16 hex>", "name": "Cloud signing", "adapter": "command", "endpoint": "…", + "account": "…", "secret": "", "certificate": "", + "created": 1794000000000, "by": "" } ], + "seen": [ { "request": "<64 hex>", "at": 1794000000 } ], + "audit": [ { "at": 1794000000000, "action": "member-added", "by": "", "detail": "Petra" } ] }, + "signing": { "keys": [ … ], "audit": [ … ] } } +``` + +- `handles`: the names Fabrica knows the member by (git host user names), 0 ..= 8 of `[A-Za-z0-9._-]{1,64}`. The + policy's author rule matches a request's `author` against them (ASCII case-insensitive) and against the member id. +- `targets` and `signers` are **not items**: an item can be revealed, copied, shared and exported, and these are + reached only through `team_target_*` and `team_signer_*`. `secret` is never in a view, a `Debug` or an error. +- `seen`: every request a member of this vault signed or refused as replayed, kept 48 hours (longer than any + request lives, 25 hours). A request whose hash is in it is refused (`Replayed`). +- `audit` (team actions; signatures are in `signing.audit`): `team-created`, `member-added`, `member-removed`, + `policy-set`, `target-added`, `target-removed`, `target-released`, `signer-added`, `signer-removed`, + `keys-created`. `detail` names, never holds a value. Append-only, newest 5 000. +- `signing` is the store of SIGNING.md, with the team's keys (below) and its audit; a team audit entry carries + `by` (the signing member's id), `env`, `release`, `request` (the request hash) and `approvers`. + +### Team keys + +`team_create_keys` makes the team's set, once: + +| id | kind | role | Signs | +| :-- | :-- | :-- | :-- | +| `team-release` | `ed25519` | release | `minisign`, `tauri-updater` when the policy asks for 1+ approvals | +| `team-preview` | `ed25519` | test | the same, when the environment's policy asks for **0** approvals | +| `team-cosign` | `ecdsa-p256` (new kind) | release | `cosign` when the policy asks for 1+ approvals | +| `team-cosign-preview` | `ecdsa-p256` | test | `cosign` at 0 approvals | + +An Android key (`android`, SIGNING.md) is made per app with `team_create_android`; at 0 approvals an `apk` request +needs a test Android key, else it is `NoKey`. Authenticode is never signed with a key in the vault: a request goes +to an external signer (`signers`) after the policy is met. + +**Why 0 approvals uses a different key.** A preview signature is made without anyone looking. It must not be +mistakable for a release: it is made by a test-role key that production targets do not trust, exactly as today's +test keys (SIGNING.md). A signature by `team-release` always means the policy's people approved it. + +## Policy + +One rule per environment, signed by the team identity: + +``` +{"v":1,"team":"<32 hex>","rev":2,"envs":[{"env":"preview","approvals":0,"others":false,"approvers":[]},{"env":"staging","approvals":1,"others":false,"approvers":[]},{"env":"production","approvals":1,"others":true,"approvers":[]}]} +``` + +| Key | | +| :-- | :-- | +| `rev` | starts at 1, +1 on every change | +| `envs` | 1 ..= 8 rules, `env` unique, `[a-z][a-z0-9-]{0,31}`, sorted as written by `Policy::canonical` (the order given) | +| `approvals` | 0 ..= 10: how many members must approve | +| `others` | the approvers must not include the release's author, **when the team has 2 or more members** | +| `approvers` | member ids allowed to approve; empty = every member | + +Canonical form as for deploy approvals (SIGNING.md): this key order, no spaces, minimal escaping, no newline; +anything else is refused, not normalised. Signature: Ed25519 by the team identity over +`"custos team policy v1\0" ‖ text`. + +**Defaults** (`Policy::default_for(team)`): preview 0, staging 1, production 1 with `others`. A team of one approves +its own production releases (the `others` rule needs two members); when a second member joins, it applies. + +### Evaluation + +`evaluate(policy, roster, env, author, approvers) -> Verdict`, pure: + +1. No rule for `env`: `UnknownEnv`. +2. `approvals == 0`: `Allowed { key_role: Test }`. +3. Eligible = roster members in `approvers` (or all); minus the author when `others` and the roster has ≥ 2 members. + The author is the member whose id equals `author` or whose handles contain it. +4. Counted = distinct eligible members among `approvers` given. Members not on the roster, ineligible members and + duplicates are not counted (and listed in `ignored`). +5. Counted ≥ `approvals`: `Allowed { key_role: Release }`. Eligible < `approvals`: `Unsatisfiable` (no set of + approvals can ever meet it: say so instead of waiting a day). Else `Need { more }`. + +## The signing request (`sign.request`, v1) + +Fabrica asks for a signature with one line of canonical JSON (the app relays it; the core checks it): + +``` +{"v":1,"op":"sign.request","team":"<32 hex>","id":"<32 hex>","project":"mnovak/Arca","release":"0.7.0","env":"production","author":"mnovak","format":"minisign","artifact":{"name":"Arca_0.7.0_x64-setup.exe","size":25145977,"sha256":"<64 hex>"},"artifact_digest":"","image":"","pub":"","expires":1794003600} +``` + +| Key | | +| :-- | :-- | +| `team` | the team id | +| `id` | 16 random bytes, hex: the request's own nonce | +| `project` | 1–128 of `[A-Za-z0-9._/-]` | +| `release` | 1–64 of `[A-Za-z0-9._+-]` (the version) | +| `env` | as in the policy | +| `author` | the release's author as Fabrica knows them, 0–64 of `[A-Za-z0-9._@-]` (empty: unknown) | +| `format` | `minisign`, `tauri-updater`, `apk`, `cosign`, `authenticode` | +| `artifact` | `name` (1–200 characters, no `/`, `\` or control characters), `size`, `sha256` (64 lower-case hex) | +| `artifact_digest` | base64; minisign and tauri-updater: BLAKE2b-512 of the file (64 bytes); apk: 1–4 SHA-512 digests of APK Signature Scheme signed data (64·n); cosign: the image manifest's SHA-256 (32); authenticode: signtool's 32-byte `.dig` | +| `image` | cosign only, else empty: the image reference without tag or digest, 1–255 of `[a-z0-9._/:-]` | +| `pub` | Fabrica's one-time X25519 key: the reply is sealed to it, and its match code is the request's code | +| `expires` | Unix seconds, later than now, at most 25 hours ahead | + +The **request hash** is `SHA-256(text)`, hex. The **match code** is `match_code(pub)`: Fabrica shows it beside the +release, every member's card shows it. + +### Approval statements + +A member who approves signs, with their member key: + +``` +Ed25519( "custos team approval v1\0" ‖ request hash (32) ‖ match code (6 ASCII digits) ‖ member id (16) ‖ at (u64 BE, Unix seconds) ) +``` + +`approve(request, shown_code, member_key, now)` refuses (`WrongMatch`) when the code the card showed is not the +request's match code: a request whose `pub` was swapped after the card was drawn is not approved. A statement whose +code is not the request's never counts. + +### Signing + +`Vault::team_sign(request_text, statements, signer, shown_code, now)` in the vault of the member whose Custos signs: + +1. parses the request (canonical, fields as above, `team` = this team, not expired), refuses a hash in `seen` + (`Replayed`); +2. checks every statement's signature against the roster, and that its code is the request's; +3. evaluates the policy with the signer's own approval added (a signer approves by signing, and their shown code + must match: `WrongMatch` otherwise); +4. picks the key: by format and the verdict's role (`team-release` / `team-preview`, `team-cosign` / + `team-cosign-preview`, the Android key of that role whose `repos` holds the request's `project`, or for + authenticode the team's first external signer, never at 0 approvals); +5. signs, records the request in `seen` and an audit entry with `by`, `env`, `release`, `request`, `approvers`; +6. returns the reply. + +A refusal by the policy, the code or the clock changes nothing. A member who refuses on the card records an audit +entry `refused` and the request's hash in `seen` (`team_refuse`). + +### The reply (`sign.reply`, v1) + +Sealed to the request's `pub` with the context `team-sign:`: + +```json +{ "v": 1, "op": "sign.reply", "request": "", "format": "minisign", + "signature": "", "payload": "", + "key": { "id": "team-release", "public": "" }, + "signer": { "member": "", "name": "Petra" }, + "proof": { … } } +``` + +### The policy proof + +What makes a signature checkable as *approved by the team's rules*, by anyone who pinned the team identity: + +``` +{"v":1,"team":"","request":"","env":"production","author":"mnovak","policy":"","policy_sig":"","roster":[{"id":"","name":"Mark","handles":["mnovak"],"ed25519":""}],"approvals":[{"member":"","code":"684361","at":1794000000,"sig":""}],"signer":"","role":"release","signature":"","at":1794000100} +``` + +plus `"sig"`: Ed25519 by the team identity over `"custos team proof v1\0" ‖ that text`, carried next to it as +`{"text": …, "sig": …}`. `role` is `release` or `test` (0 approvals: no approvals listed). For `release`, the +signer's own approval is one of those that count: the signature is made in an approving member's Custos. `verify_proof(proof, team_identity_public, request_text, envelope, now)` checks both +signatures, every approval against the roster and the request's code, the request hash and the envelope hash, and +evaluates the policy again: it accepts only what `team_sign` itself would have signed. + +## Signature envelopes + +| `format` | `signature` in the reply | Check it with | +| :-- | :-- | :-- | +| `minisign` | the `.minisig` text (prehashed, SIGNING.md) | `minisign -V -P -m `, minisign-verify | +| `tauri-updater` | base64 of that `.minisig` text: the content of Tauri's `.sig` | Tauri's updater (minisign-verify) with `pubkey` = base64 of `minisign.pub` | +| `apk` | base64 of the n RSA PKCS#1 v1.5 SHA-512 signatures (512 bytes each) | apksig pass 2 then `apksigner verify` (the app's `custos-sign apk`) | +| `cosign` | base64 of the ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload` | `cosign verify --key cosign.pub --insecure-ignore-tlog=true @` once attached; `openssl dgst -sha256 -verify cosign.pub -signature sig.der payload.json` | +| `authenticode` | base64 of what the external signer returned for the `.dig` (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo) | `signtool sign /di`, then `signtool verify /pa`, `osslsigncode verify` | + +**cosign.** The payload is cosign's *simple signing* JSON, written by Custos (never taken from the request), with the +keys in this order and no spaces: + +``` +{"critical":{"identity":{"docker-reference":""},"image":{"docker-manifest-digest":"sha256:<64 hex>"},"type":"cosign container image signature"},"optional":null} +``` + +No transparency log is involved: Fabrica attaches it with +`cosign attach signature --payload payload.json --signature @sha256:`, and a target checks it +with the team's `cosign.pub` (PEM, SubjectPublicKeyInfo) and `--insecure-ignore-tlog=true`, or by fetching the +`sha256-.sig` manifest and checking the layer's `dev.cosignproject.cosign/signature` annotation over the +layer's bytes, which are this payload. + +## Target credentials + +A target credential is handed to the Fabrica server for one deployment: `team_target_release(target id, request, +deployment, now)` returns the plaintext to seal, only when the target's `project` and `env` equal the deployment's, +and records `target-released` with the deployment's request hash. One release per (target, deployment): a second +call is `Replayed`. The app seals it to the server's one-time key (`team-target:`); the service hands the box +out once, to the caller that asked (Custos `docs/27_team_vault.md`). + +`kind`: `ssh-key` (an OpenSSH private key), `winrm` (user and password), `openssh` (user and password), +`registry` (a Docker registry token), `kubeconfig` (the kubeconfig text). `secret` ≤ 64 KiB. + +## Crates + +`custos-team` (pure): member keys, wrapping, policy, request, statements, proof, envelopes, on `ed25519-dalek`, +`x25519-dalek` through `custos-seal`, `sha2`, `p256` (cosign verification only). `custos-sign` gains `cosign` +(ECDSA P-256 with `p256`, RFC 6979 deterministic nonces) and `tauri_updater`. `custos-vault` holds the file format, +the body and `team_sign`.