diff --git a/CLAUDE.md b/CLAUDE.md index b2c390e..8a0bc41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,6 +20,7 @@ docs/KEYS.md secret keys, API keys and key pairs docs/SEAL.md sealed boxes and the match code docs/SHARE.md the share blob and link format (versioned like FORMAT.md) 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 ``` ## Commands diff --git a/crates/custos-vault/tests/identity.rs b/crates/custos-vault/tests/identity.rs new file mode 100644 index 0000000..60bd3a2 --- /dev/null +++ b/crates/custos-vault/tests/identity.rs @@ -0,0 +1,219 @@ +//! Mandatory tests for the Domi identity (docs/IDENTITY.md): the mnemonic order, the vector shared with +//! Fundamentum, signing only certs, persistence, and no way to get the root key out. + +use custos_vault::identity::{Enrollment, Issued}; +use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault}; +use ed25519_dalek::{Signature, VerifyingKey}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +/// The root public key of `abandon` × 23 + `art` (Fundamentum `crates/tessera/tests/mandatory.rs`). +const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs"; +const CERT_DOMAIN: &[u8] = b"tessera cert v1\0"; + +fn vault() -> Vault { + Vault::create(&SecretString::from("pw"), FAST).unwrap() +} + +fn b64url(s: &str) -> Vec { + data_encoding::BASE64URL_NOPAD.decode(s.as_bytes()).unwrap() +} + +/// Runs the whole enrolment with known entropy, typing the right words. Returns the words shown. +fn enrol(v: &mut Vault, entropy: [u8; 32]) -> Vec { + let mut words = Vec::new(); + let shown = Enrollment::with_entropy(entropy).show(|w| words = w.iter().map(|s| s.to_string()).collect()); + let pick = shown.challenge().map(|i| words[i - 1].clone()); + let confirmed = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap(); + confirmed.import(v).unwrap(); + words +} + +#[test] +fn the_zero_vector_matches_fundamentum() { + let mut v = vault(); + let words = enrol(&mut v, [0; 32]); + assert_eq!(words.len(), 24); + assert!(words[..23].iter().all(|w| w == "abandon") && words[23] == "art"); + assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO)); +} + +#[test] +fn the_same_mnemonic_gives_the_same_root() { + let (mut a, mut b) = (vault(), vault()); + enrol(&mut a, [42; 32]); + enrol(&mut b, [42; 32]); + assert_eq!(a.domi_root_public(), b.domi_root_public()); + let mut c = vault(); + enrol(&mut c, [43; 32]); + assert_ne!(a.domi_root_public(), c.domi_root_public()); +} + +#[test] +fn the_mnemonic_is_shown_before_anything_is_imported() { + // The order trap at run time; at compile time see the compile_fail doctests in src/identity.rs. + let v = vault(); + let mut log = Vec::new(); + let shown = Enrollment::begin().show(|w| { + assert_eq!(w.len(), 24); + log.push("shown"); + }); + assert_eq!(log, ["shown"]); + assert!(v.domi_root_public().is_none(), "nothing in the vault before confirm + import"); + // Wrong words: refused, and the same Shown comes back to try again. + let (shown, e) = shown.confirm(&["zoo", "zoo", "zoo"]).expect_err("wrong words are refused"); + assert!(matches!(e, Error::WrongWords)); + let c = shown.challenge(); + assert!(c.iter().all(|&i| (1..=24).contains(&i)) && c[0] != c[1] && c[1] != c[2] && c[0] != c[2]); + assert!(v.domi_root_public().is_none()); +} + +#[test] +fn the_challenge_accepts_any_spacing_and_case() { + let mut v = vault(); + let mut words = Vec::new(); + let shown = Enrollment::with_entropy([5; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect()); + let pick = shown.challenge().map(|i| format!(" {} ", words[i - 1].to_uppercase())); + shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap().import(&mut v).unwrap(); + assert!(v.domi_root_public().is_some()); +} + +#[test] +fn an_identity_is_created_once() { + let mut v = vault(); + enrol(&mut v, [1; 32]); + let first = v.domi_root_public(); + let mut words = Vec::new(); + let shown = Enrollment::with_entropy([2; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect()); + let pick = shown.challenge().map(|i| words[i - 1].clone()); + let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap(); + assert!(matches!(c.import(&mut v), Err(Error::IdentityExists))); + assert_eq!(v.domi_root_public(), first); +} + +/// A cert's to-be-signed bytes as tessera makes them: TSC1 ‖ root ‖ subkey ‖ ids ‖ validity. +fn tbs(root: &[u8; 32]) -> Vec { + let mut t = b"TSC1".to_vec(); + t.extend_from_slice(root); + t.extend_from_slice(&[9; 32]); + t.extend_from_slice(b"\x06fiscus\x04sync"); + t.extend_from_slice(&1u64.to_be_bytes()); + t.extend_from_slice(&2u64.to_be_bytes()); + t +} + +#[test] +fn the_root_signs_certs_and_nothing_else() { + let mut v = vault(); + assert!(matches!(v.domi_sign_cert(&tbs(&[0; 32])), Err(Error::NoIdentity))); + enrol(&mut v, [0; 32]); + let root = v.domi_root_public().unwrap(); + let t = tbs(&root); + let sig = v.domi_sign_cert(&t).unwrap(); + let vk = VerifyingKey::from_bytes(&root).unwrap(); + vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap(); + // Not a cert, a cert for another root, the bare prefix: refused. + assert!(matches!(v.domi_sign_cert(b"pay 100 CZK to mallory"), Err(Error::NotACert))); + assert!(matches!(v.domi_sign_cert(&tbs(&[1; 32])), Err(Error::NotACert))); + assert!(matches!(v.domi_sign_cert(&t[..36]), Err(Error::NotACert))); +} + +#[test] +fn the_identity_survives_saving_in_both_versions() { + let issued = Issued { + kind: "app".into(), + app_id: "fiscus".into(), + purpose: "sync".into(), + subkey: "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk".into(), + label: "fiscus.exe".into(), + not_before: 1, + not_after: 2, + issued: 3, + }; + // Version 1. + let mut v = vault(); + enrol(&mut v, [0; 32]); + v.domi_record(issued.clone()).unwrap(); + let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(back.domi_root_public(), v.domi_root_public()); + assert_eq!(back.domi_issued(), std::slice::from_ref(&issued)); + assert!(back.domi_created().is_some()); + let t = tbs(&back.domi_root_public().unwrap()); + assert_eq!(back.domi_sign_cert(&t).unwrap(), v.domi_sign_cert(&t).unwrap(), "the same key came back"); + // Version 2. + let pw = SecretString::from("pw"); + let mut v2 = + Vault::create_with(Unlock::Password(&pw), "pw", Unlock::Material(FactorKind::Device, &[7; 32]), "pc", FAST) + .unwrap(); + enrol(&mut v2, [3; 32]); + let bytes = v2.to_bytes().unwrap(); + let back = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &[7; 32])).unwrap(); + assert_eq!(back.domi_root_public(), v2.domi_root_public()); + // A vault without an identity still opens and has none. + let plain = Vault::open(&vault().to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert!(plain.domi_root_public().is_none() && plain.domi_issued().is_empty()); +} + +#[test] +fn a_record_needs_an_identity() { + let mut v = vault(); + let i = Issued { + kind: "app".into(), + app_id: "x".into(), + purpose: "y".into(), + subkey: String::new(), + label: String::new(), + not_before: 0, + not_after: 1, + issued: 0, + }; + assert!(matches!(v.domi_record(i), Err(Error::NoIdentity))); +} + +#[test] +fn nothing_prints_the_root() { + let mut v = vault(); + let mut words = Vec::new(); + let e = Enrollment::with_entropy([0; 32]); + assert_eq!(format!("{e:?}"), "Enrollment([redacted])"); + let shown = e.show(|w| words = w.iter().map(|s| s.to_string()).collect()); + assert_eq!(format!("{shown:?}"), "Shown([redacted])"); + let pick = shown.challenge().map(|i| words[i - 1].clone()); + let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap(); + assert_eq!(format!("{c:?}"), "Confirmed([redacted])"); + c.import(&mut v).unwrap(); + let dbg = format!("{v:?}"); + assert!(!dbg.contains("abandon") && !dbg.to_lowercase().contains("root"), "{dbg}"); +} + +/// No key export: the public surface of the identity module is locked. A new public function fails this +/// test until it has been checked to return no secret. +#[test] +fn the_identity_surface_is_locked() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut got = Vec::new(); + for file in ["identity.rs", "lib.rs"] { + let text = std::fs::read_to_string(dir.join(file)).unwrap(); + for line in text.lines() { + let l = line.trim(); + if l.starts_with("pub fn ") && (file == "identity.rs" || l.starts_with("pub fn domi_")) { + got.push(format!("{file}: {}", l.trim_end_matches(" {"))); + } + } + } + got.sort(); + let mut want = vec![ + "identity.rs: pub fn begin() -> Enrollment", + "identity.rs: pub fn challenge(&self) -> [usize; 3]", + "identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result", + "identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>", + "identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown", + "identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment", + "lib.rs: pub fn domi_created(&self) -> Option", + "lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]", + "lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>", + "lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>", + "lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>", + ]; + want.sort(); + assert_eq!(got, want, "review the identity surface: it must never return the root secret"); +} diff --git a/docs/FORMAT.md b/docs/FORMAT.md index f9818f2..7bfd47a 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -119,6 +119,8 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields. - `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item). - Readers ignore JSON members they do not know, so later versions can add them. +- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md). + An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later. ### Item types and their fields (v1) diff --git a/docs/IDENTITY.md b/docs/IDENTITY.md new file mode 100644 index 0000000..8951c28 --- /dev/null +++ b/docs/IDENTITY.md @@ -0,0 +1,70 @@ +# The Domi identity (`custos-vault`, `identity`) + +Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in +the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but +subkey certificates. The certificate format, the match code and verification are in Fundamentum +(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side. + +## Creating it: the order is mandatory + +``` +entropy 32 bytes from the OS CSPRNG +mnemonic BIP39 English, 24 words, shown ONCE +confirm the person types 3 words the vault picks at random +root Ed25519 secret = HKDF-SHA256(salt = "tessera root v1", ikm = BIP39 seed(mnemonic, ""), info = "ed25519") +import the secret goes into the vault; entropy, seed and mnemonic are wiped +``` + +A key that was created non-extractable first could never be backed up. So the code cannot do it in the other +order: `identity::Enrollment` is a typestate. + +| Type | Holds | Only way forward | +|:--|:--|:--| +| `Enrollment` | the entropy | `show(display)`: hands the 24 words to `display`, once | +| `Shown` | the entropy, 3 word positions | `confirm(words)`: the 3 words, or it hands itself back to try again | +| `Confirmed` | the derived root secret; the entropy is wiped | `import(&mut vault)`: stores the root, returns its public key | + +`import` exists only on `Confirmed`, `Confirmed` only comes from `confirm`, and `confirm` only from `show`. +Swapping the order does not compile (`compile_fail` doctests in `src/identity.rs`). None of the three types +is `Clone` or `Serialize`; each prints `[redacted]`. + +Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key +`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value. + +## In the vault file + +A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before: + +```json +"identity": { + "root": "<64 hex: the Ed25519 secret>", + "public": "<64 hex>", + "created": 1793000000000, + "issued": [ + { "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "", "label": "fiscus.exe", + "not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000 } + ] +} +``` + +- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not + a trust list: revocation is v1.1. +- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every + Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way. + +## Using it + +| Function | What | +|:--|:--| +| `Vault::domi_root_public()` | the root public key, if there is an identity | +| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key | +| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs | + +The prefix check means the vault is not a general signing oracle: whatever the app hands it, the result +can only ever verify as a certificate naming this root. + +## What it does not protect + +The root secret is in the vault body, so everything in docs/THREAT_MODEL.md about an unlocked vault applies: +malware running as you while the vault is open can read it from memory. It never reaches the webview, the +Domi pipe, logs or the web vault.