diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index fa56158..ecc2cd5 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -21,6 +21,7 @@ mod device; mod format; pub mod identity; mod item; +pub mod provision; mod save; mod secret; pub mod signing; @@ -79,6 +80,9 @@ pub enum Error { UnknownKey, #[error("this vault already has {0} signing keys")] SigningExists(&'static str), + /// Names the member that does not fit (docs/FORMAT.md), never its value. + #[error("provision audit: {0}")] + Provision(&'static str), #[error("signing keys: {0}")] Signing(String), #[error("{0}")] @@ -274,6 +278,8 @@ struct Body { identity: Option, #[serde(default)] signing: Option, + #[serde(default)] + provision: Option, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. @@ -287,6 +293,8 @@ struct BodyRef<'a> { identity: Option, #[serde(skip_serializing_if = "Option::is_none")] signing: Option, + #[serde(skip_serializing_if = "Option::is_none")] + provision: Option, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. @@ -303,6 +311,8 @@ pub struct Vault { identity: Option, /// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out. signing: signing::Store, + /// The Provisio audit (docs/FORMAT.md), oldest first. + provision: Vec, } impl fmt::Debug for Vault { @@ -403,6 +413,7 @@ impl Vault { kdf_new: kdf, identity: None, signing: signing::Store::default(), + provision: Vec::new(), }) } @@ -420,6 +431,7 @@ impl Vault { kdf_new: kdf, identity: None, signing: signing::Store::default(), + provision: Vec::new(), }; v.add_factor(a, label_a)?; v.add_factor(b, label_b)?; @@ -453,6 +465,7 @@ impl Vault { kdf_new: KdfParams::DEFAULT, identity: None, signing: signing::Store::default(), + provision: Vec::new(), }) } @@ -587,6 +600,7 @@ impl Vault { kdf_new, identity, signing, + provision: provision::from_json(body.provision), }) } @@ -622,6 +636,7 @@ impl Vault { factors: self.factors.iter().map(FactorRec::json).collect(), identity: self.identity.as_ref().map(identity::Root::json), signing: self.signing.json(), + provision: provision::json(&self.provision), }; 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/provision.rs b/crates/custos-vault/src/provision.rs new file mode 100644 index 0000000..e2bbd34 --- /dev/null +++ b/crates/custos-vault/src/provision.rs @@ -0,0 +1,218 @@ +//! The Provisio audit (docs/FORMAT.md, "The provision audit"): the vault body member `provision`, beside +//! signing's audit. One entry per outcome of a server's ask or offer. An entry holds no secret: every member is +//! something the server sent in the clear through the mailbox, or the match code of a public key. + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Vault}; + +/// The log keeps the newest this many entries. +pub const AUDIT_LIMIT: usize = 5_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Direction { + /// The server asked Custos for a secret (or asked it to make one). + Ask, + /// The server offered a secret it made. + Offer, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Store { + /// A Domi-ref item in the vault. + Vault, + /// The local Claude Code store. + Claude, + /// The cloud Claude Code store. + Cloud, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Outcome { + /// Ask: Mark approved; the item's value was sealed to the request. + Approved, + /// Ask with `--generate`: Custos made the item, stored it and sealed it to the request. + Generated, + /// Offer: Mark accepted; the value was stored. + Accepted, + /// Mark refused on the card. + Refused, + /// Outside the scope: refused before a card, or again when storing. + OutOfScope, + /// An offer's box did not match the offer (item, store, kind or code key), or did not open. + Invalid, + /// Nobody answered within five minutes. + Expired, +} + +/// One audit entry. Append-only: nothing edits or removes one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProvisionEntry { + /// Unix milliseconds. + pub at: i64, + pub direction: Direction, + /// The name the factor service gave the server. + pub host: String, + pub item: String, + pub store: Store, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run: Option, + /// An offer's label (`--kind`), or an ask's `--generate` recipe. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub kind: Option, + /// The match code both screens showed: six digits. + pub code: String, + pub outcome: Outcome, + /// An accepted offer replaced an existing item. + #[serde(default)] + pub replaced: bool, +} + +/// The body member: `{"audit": [...]}`. +#[derive(Serialize, Deserialize)] +pub(crate) struct ProvisionJson { + #[serde(default)] + audit: Vec, +} + +/// The log as the vault keeps it, oldest first. +pub(crate) fn from_json(j: Option) -> Vec { + let mut audit = j.map(|j| j.audit).unwrap_or_default(); + trim(&mut audit); + audit +} + +/// Absent while the log is empty, so a vault without entries is written exactly as before. +pub(crate) fn json(audit: &[ProvisionEntry]) -> Option { + (!audit.is_empty()).then(|| ProvisionJson { audit: audit.to_vec() }) +} + +fn trim(audit: &mut Vec) { + if audit.len() > AUDIT_LIMIT { + audit.drain(..audit.len() - AUDIT_LIMIT); + } +} + +/// `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks an item. +fn item_ok(item: &str) -> bool { + let parts: Vec<&str> = item.split('/').collect(); + parts.len() <= 4 + && parts.iter().all(|p| { + let b = p.as_bytes(); + (1..=64).contains(&b.len()) + && (b[0].is_ascii_lowercase() || b[0].is_ascii_digit()) + && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(c)) + }) +} + +impl ProvisionEntry { + /// Whether every member fits docs/FORMAT.md. The error names the member, never its value. + pub fn check(&self) -> Result<(), Error> { + let host = self.host.as_bytes(); + if !(1..=253).contains(&host.len()) || !host.iter().all(|c| c.is_ascii_alphanumeric() || b".-".contains(c)) { + return Err(Error::Provision("the host is not a host name")); + } + if !item_ok(&self.item) { + return Err(Error::Provision("the item is not an item name")); + } + if let Some(run) = &self.run { + let r = run.as_bytes(); + if !(1..=64).contains(&r.len()) || !r.iter().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(c)) { + return Err(Error::Provision("the run is not a run id")); + } + } + if let Some(kind) = &self.kind + && (kind.chars().count() > 200 || kind.chars().any(char::is_control)) + { + return Err(Error::Provision("the kind is longer than 200 characters or has control characters")); + } + if self.code.len() != 6 || !self.code.bytes().all(|c| c.is_ascii_digit()) { + return Err(Error::Provision("the match code is not six digits")); + } + Ok(()) + } +} + +impl Vault { + /// Records one outcome, after `ProvisionEntry::check`. Beyond `AUDIT_LIMIT` entries the oldest goes. The + /// caller saves. + pub fn provision_record(&mut self, entry: ProvisionEntry) -> Result<(), Error> { + entry.check()?; + self.provision.push(entry); + trim(&mut self.provision); + Ok(()) + } + + /// Every outcome, oldest first (newest last). + pub fn provision_audit(&self) -> &[ProvisionEntry] { + &self.provision + } +} + +#[cfg(test)] +mod tests { + //! An older reader still opens a vault with the member. It lives here because only the crate can decrypt the + //! body and parse it the way core 0.10.0 did. + use super::*; + use crate::format::Header; + use crate::{FactorJson, Item, ItemType, KdfParams, SecretString, crypto, identity, signing}; + + /// The body as core 0.10.0 parsed it (src/lib.rs `Body` at v0.10.0): no `provision`. + #[derive(Deserialize)] + #[allow(dead_code)] + struct BodyV0_10 { + format: u32, + items: Vec, + #[serde(default)] + factors: Vec, + #[serde(default)] + identity: Option, + #[serde(default)] + signing: Option, + } + + fn body_json(v: &Vault) -> String { + let bytes = v.to_bytes().unwrap(); + let (header, at) = Header::parse(&bytes).unwrap(); + let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap(); + String::from_utf8(json.to_vec()).unwrap() + } + + fn entry() -> ProvisionEntry { + ProvisionEntry { + at: 1_793_750_000_000, + direction: Direction::Offer, + host: "nixos-vm".into(), + item: "arca/gitea-read-token".into(), + store: Store::Vault, + run: None, + kind: Some("Gitea token, read:repository".into()), + code: "684361".into(), + outcome: Outcome::Accepted, + replaced: true, + } + } + + #[test] + fn an_older_reader_opens_a_vault_with_the_provision_audit() { + let mut v = + Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap(); + v.add(Item::new(ItemType::SecureNote, "kept", 1)); + // Without entries the body has no trace of the member, so it is byte-for-byte what 0.10.0 wrote. + assert!(!body_json(&v).contains("provision")); + + v.provision_record(entry()).unwrap(); + let json = body_json(&v); + assert!(json.contains(r#""provision":{"audit":[{"#), "{json}"); + // Core 0.10.0's parser takes it and keeps everything it knows. + let old: BodyV0_10 = serde_json::from_str(&json).unwrap(); + assert_eq!(old.format, 1); + assert_eq!(old.items.len(), 1); + assert_eq!(old.items[0].title, "kept"); + assert!(old.identity.is_none() && old.signing.is_none()); + } +} diff --git a/crates/custos-vault/tests/provision.rs b/crates/custos-vault/tests/provision.rs new file mode 100644 index 0000000..554bbf8 --- /dev/null +++ b/crates/custos-vault/tests/provision.rs @@ -0,0 +1,158 @@ +//! Mandatory tests for the Provisio audit (docs/FORMAT.md, "The provision audit"): it survives a reopen, takes +//! only entries that fit, is append-only and bounded, and has no member that could hold a secret. That an older +//! reader still opens such a vault is a unit test in src/provision.rs, which can see the decrypted body. + +use custos_vault::provision::{AUDIT_LIMIT, Direction, Outcome, ProvisionEntry, Store}; +use custos_vault::{Error, KdfParams, SecretString, Vault}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +const NOW: i64 = 1_793_750_000_000; + +/// One way to spoil an entry. +type Change = Box; + +fn entry(i: i64, outcome: Outcome) -> ProvisionEntry { + ProvisionEntry { + at: NOW + i, + direction: Direction::Offer, + host: "nixos-vm".into(), + item: "fabrica/gitea-read-token".into(), + store: Store::Vault, + run: Some("deploy-7".into()), + kind: Some("Gitea token, read:repository".into()), + code: "684361".into(), + outcome, + replaced: false, + } +} + +#[test] +fn the_provision_audit_records_every_outcome_and_survives_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v.custos"); + let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + assert!(v.provision_audit().is_empty()); + let all = [ + Outcome::Approved, + Outcome::Generated, + Outcome::Accepted, + Outcome::Refused, + Outcome::OutOfScope, + Outcome::Invalid, + Outcome::Expired, + ]; + for (i, o) in all.iter().enumerate() { + let mut e = entry(i as i64, *o); + if i % 2 == 0 { + e.direction = Direction::Ask; + e.store = Store::Vault; + e.kind = None; + e.run = None; + } else { + e.store = if i % 3 == 0 { Store::Claude } else { Store::Cloud }; + e.item = "fabrica-hub-token".into(); + } + e.replaced = *o == Outcome::Accepted; + v.provision_record(e).unwrap(); + } + v.save(&path).unwrap(); + + let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap(); + let audit: &[ProvisionEntry] = back.provision_audit(); + assert_eq!(audit, v.provision_audit()); + assert_eq!(audit.iter().map(|e| e.outcome).collect::>(), all); + // Newest last. + assert!(audit.windows(2).all(|w| w[0].at < w[1].at)); + assert_eq!(audit[0].direction, Direction::Ask); + assert_eq!(audit[1].store, Store::Cloud); + assert_eq!(audit[3].store, Store::Claude); + assert!(audit[2].replaced && !audit[1].replaced); + // The signing audit is a separate log and stays empty. + assert!(back.signing_audit().is_empty()); +} + +#[test] +fn entries_that_do_not_fit_are_refused_and_not_stored() { + let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + v.provision_record(entry(0, Outcome::Approved)).unwrap(); + let secretish = "ghp_s3cr3tV4lu3ThatMustNeverBeInAnError"; + let bad: Vec = vec![ + Box::new(|e| e.code = "68436".into()), + Box::new(|e| e.code = "68436a".into()), + Box::new(|e| e.code = "6843611".into()), + Box::new(|e| e.item = "Arca/x".into()), + Box::new(|e| e.item = "../x".into()), + Box::new(|e| e.item = "a/b/c/d/e".into()), + Box::new(|e| e.item = String::new()), + Box::new(|e| e.item = format!("arca/{}", "x".repeat(65))), + Box::new(|e| e.run = Some(String::new())), + Box::new(|e| e.run = Some("run 1".into())), + Box::new(|e| e.run = Some("r".repeat(65))), + Box::new(|e| e.host = String::new()), + Box::new(|e| e.host = "nixos vm".into()), + Box::new(|e| e.host = "h".repeat(254)), + Box::new(|e| e.kind = Some("x".repeat(201))), + Box::new(move |e| e.kind = Some(format!("token\n{secretish}"))), + ]; + for (i, change) in bad.iter().enumerate() { + let mut e = entry(1, Outcome::Accepted); + change(&mut e); + let err = v.provision_record(e).unwrap_err(); + assert!(matches!(err, Error::Provision(_)), "case {i}: {err:?}"); + assert!(!format!("{err}{err:?}").contains(secretish), "case {i}: an error repeats a value"); + } + assert_eq!(v.provision_audit(), [entry(0, Outcome::Approved)]); + // The limits themselves fit. + let mut e = entry(2, Outcome::Accepted); + e.item = format!("a{0}/b{0}/c{0}/d{0}", "x".repeat(63)); + e.run = Some("R".repeat(64)); + e.host = "h".repeat(253); + e.kind = Some("k".repeat(200)); + v.provision_record(e).unwrap(); + assert_eq!(v.provision_audit().len(), 2); +} + +#[test] +fn the_audit_is_append_only_and_keeps_the_newest_entries() { + let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + v.provision_record(entry(0, Outcome::Refused)).unwrap(); + let before = v.provision_audit().to_vec(); + v.provision_record(entry(1, Outcome::Accepted)).unwrap(); + // Recording appends; what was there is unchanged. + assert_eq!(&v.provision_audit()[..1], before.as_slice()); + assert_eq!(v.provision_audit()[1], entry(1, Outcome::Accepted)); + + assert_eq!(AUDIT_LIMIT, 5_000); + for i in 2..(AUDIT_LIMIT as i64 + 3) { + v.provision_record(entry(i, Outcome::Expired)).unwrap(); + } + let audit = v.provision_audit(); + assert_eq!(audit.len(), AUDIT_LIMIT); + // The three oldest went; the newest is last. + assert_eq!(audit[0].at, NOW + 3); + assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 2); +} + +#[test] +fn an_entry_has_no_member_that_could_hold_a_secret() { + // Every member, with every option set: the JSON has exactly these names and nothing like a value. + let mut e = entry(0, Outcome::Accepted); + e.replaced = true; + let json: serde_json::Value = serde_json::to_value(&e).unwrap(); + let mut names: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect(); + names.sort(); + assert_eq!(names, ["at", "code", "direction", "host", "item", "kind", "outcome", "replaced", "run", "store"]); + for v in json.as_object().unwrap().values() { + assert!(!v.is_object() && !v.is_array(), "no nested member to hide a value in"); + } + assert_eq!( + serde_json::to_string(&e).unwrap(), + r#"{"at":1793750000000,"direction":"offer","host":"nixos-vm","item":"fabrica/gitea-read-token","store":"vault","run":"deploy-7","kind":"Gitea token, read:repository","code":"684361","outcome":"accepted","replaced":true}"# + ); + // The options are left out when absent; the outcomes are spelled as docs/FORMAT.md says. + let mut e = entry(0, Outcome::OutOfScope); + e.run = None; + e.kind = None; + let s = serde_json::to_string(&e).unwrap(); + assert!(!s.contains("\"run\"") && !s.contains("\"kind\"") && s.contains("\"out-of-scope\""), "{s}"); +} diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 6c39e20..e8117e6 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -129,6 +129,42 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: An older Custos drops `folder` and `attachments` when it saves. - `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request (docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later. +- `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. + +### The provision audit (core 0.11.0) + +```json +"provision": { + "audit": [ + { "at": 1793750100000, "direction": "offer", "host": "nixos-vm", "item": "fabrica/gitea-read-token", + "store": "vault", "run": "deploy-7", "kind": "Gitea token, read:repository", "code": "684361", + "outcome": "accepted", "replaced": true } + ] +} +``` + +| Member | | +| :-- | :-- | +| `at` | Unix milliseconds | +| `direction` | `ask` (the server asked for a secret) or `offer` (the server offered one) | +| `host` | the name the factor service gave, 1–253 characters `[A-Za-z0-9.-]` | +| `item` | `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks it | +| `store` | `vault`, `claude` or `cloud` | +| `run` | optional, `[A-Za-z0-9._-]{1,64}` | +| `kind` | optional, at most 200 characters, no control characters (an offer's label; an ask's `--generate` recipe) | +| `code` | the match code: six ASCII digits | +| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid` or `expired` | +| `replaced` | `true` when an accepted offer replaced an existing item | + +- **No value, ever.** There is no member that holds a secret: every member is something the server sent in the + clear through the mailbox (host, item, store, run, kind) or derives from a public key (`code`). A recorded + entry is checked against the table above; an entry that does not fit is refused, not stored. +- **Append-only.** The API records an entry and lists them (oldest first); nothing edits or removes one, except + that the log keeps the newest 5 000 entries and drops the oldest beyond that. +- Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or + `store` this core does not know does not open (`Corrupted`), as for `signing`. ### Item types and their fields (v1)