From d06cf04faf2d7c6c0beb06d7f9439bd4056a89c9 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:57:35 +0200 Subject: [PATCH 01/10] feat(repo): refuse to seal to a recipient this clone never accepted Protection rules, secret wrap lists and private-branch KEK wrap labels are repository data, so a writer with no key could grant their own key and wait for the victim's next commit, merge or replay reseal, rewrap, secret rotate or branch revoke to wrap a DEK to them. .sc/accepted-recipients is a local record of the recipient ids accepted per scope (path:, secret:, branch:); local [escrow] keys count everywhere. encrypt_protected, the one function that turns a rule into wraps, refuses before sealing anything when a key is not accepted for the winning rule's prefix. sc protect validates the candidate rule before its first ref move, secret_rotate and branch_revoke check the final set, and rewrap skips an entry with an unaccepted key. Carries that copy existing wraps are not gated. Keys named by the caller are accepted on the spot (protect, grant, secret add/grant, branch --private, branch grant); the local revoke operations drop the pair. The record is written atomically under the repo lock and is never committed, packed or transferred. The test seams that hand-build rules accept the keys they name. Refs ADR-0059. --- crates/repo/src/accepted.rs | 967 +++++++++++++++++++++++++++++++ crates/repo/src/error.rs | 6 + crates/repo/src/layout.rs | 6 + crates/repo/src/lib.rs | 1 + crates/repo/src/partial_merge.rs | 5 + crates/repo/src/private.rs | 31 +- crates/repo/src/protect.rs | 63 +- crates/repo/src/protect_ops.rs | 63 +- crates/repo/src/replay.rs | 27 +- crates/repo/src/repo.rs | 32 +- crates/repo/src/rewrap.rs | 24 + crates/repo/src/secrets.rs | 19 +- 12 files changed, 1195 insertions(+), 49 deletions(-) create mode 100644 crates/repo/src/accepted.rs diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs new file mode 100644 index 00000000..15d9df7f --- /dev/null +++ b/crates/repo/src/accepted.rs @@ -0,0 +1,967 @@ +//! Locally accepted recipients (ADR-0059). +//! +//! Protection rules, secret wrap lists and private-branch KEK wrap labels are +//! repository data, so a writer without a key can make your next seal wrap a +//! DEK to them. `.sc/accepted-recipients` is the local answer: one +//! `\t` line per key YOU accepted for a scope (`path:` +//! with the full public key, `secret:` and `branch:` with the +//! recipient id). A seal that would wrap to a key not accepted for its scope +//! (and not in the local `[escrow]`) refuses before anything is written. +//! +//! The file is local state like `.sc/local-key`: written atomically under the +//! repo lock, never committed, never in a pack, never transferred, never read +//! by gc. Sessions (`sc ws`, `sc work`) commit through the host repo, so they +//! read the host's record. + +use std::collections::{BTreeMap, BTreeSet}; + +use scl_crypto::{PublicKey, RecipientId}; + +use crate::error::{Error, Result}; +use crate::layout::Layout; +use crate::repo::Repo; + +/// Scope of a protected-path rule: the rule's own prefix string. +pub(crate) fn path_scope(prefix: &str) -> String { + format!("path:{prefix}") +} + +/// Scope of a committed secret's wrap list. +pub(crate) fn secret_scope(name: &str) -> String { + format!("secret:{name}") +} + +/// Scope of a private branch's KEK wrap list. +pub(crate) fn branch_scope(name: &str) -> String { + format!("branch:{name}") +} + +/// What `scope` records for `key`: the full public key for a path rule (a rule +/// holds full keys), the recipient id for a secret or a branch (a wrap label +/// is an id). +fn entry(scope: &str, key: &PublicKey) -> String { + if scope.starts_with("path:") { + key.to_key_string() + } else { + key.recipient_id().to_string() + } +} + +/// A recipient a seal would wrap to that this clone never accepted for the scope. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unaccepted { + pub scope: String, + /// What `sc policy accept --key` takes for this scope: the full public key + /// for `path:`, the recipient id otherwise. + pub key: String, + pub id: String, + /// The local `[recipients]` name for the key, if there is one. + pub name: Option, +} + +impl Unaccepted { + fn label(&self) -> &str { + self.name.as_deref().unwrap_or("UNKNOWN") + } + + /// The exact `sc policy accept` command; an unknown key needs + /// `--allow-unknown`. + pub fn accept_command(&self) -> String { + let unknown = if self.name.is_none() { + " --allow-unknown" + } else { + "" + }; + format!( + "sc policy accept {} --key {}{unknown}", + sh_quote(&self.scope), + self.key + ) + } + + /// The command that removes the recipient from the repository data. + pub fn remove_command(&self) -> String { + let (kind, target) = self.scope.split_once(':').unwrap_or(("", &self.scope)); + let target = sh_quote(target); + match kind { + "path" => format!("sc revoke {target} --recipient-id {}", self.id), + "secret" => format!("sc secret revoke {target} --recipient-id {}", self.id), + _ => format!( + "sc branch revoke {target} --recipient-id {} --identity ", + self.id + ), + } + } +} + +/// Quote `s` for a POSIX shell unless it is plainly safe. +fn sh_quote(s: &str) -> String { + if !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || "_./:@%+=,-".contains(c)) + { + s.to_string() + } else { + format!("'{}'", s.replace('\'', "'\\''")) + } +} + +/// The text of [`Error::UnacceptedRecipients`]. +pub(crate) fn describe(pairs: &[Unaccepted]) -> String { + let mut out = String::new(); + for p in pairs { + out.push_str(&format!( + "{} grants a recipient you have not accepted: {} ({}).\n Accept: {}\n Remove: {}\n", + p.scope, + p.id, + p.label(), + p.accept_command(), + p.remove_command() + )); + } + out.push_str("Nothing was written."); + out +} + +/// One-line form for a skipped `rewrap` entry. +pub(crate) fn describe_inline(pairs: &[Unaccepted]) -> String { + pairs + .iter() + .map(|p| { + format!( + "grants a recipient you have not accepted: {} ({}); accept: {}; remove: {}", + p.id, + p.label(), + p.accept_command(), + p.remove_command() + ) + }) + .collect::>() + .join("; ") +} + +/// This clone's accepted pairs plus the local escrow keys (accepted in every +/// scope) and `[recipients]` names, as read from `.sc/`. +#[derive(Default, Clone)] +pub(crate) struct Accepted { + pairs: BTreeSet<(String, String)>, + escrow: BTreeSet, + names: BTreeMap, +} + +impl Accepted { + pub(crate) fn load(layout: &Layout) -> Result { + let mut out = Accepted { + pairs: read_pairs(layout)?, + ..Default::default() + }; + // An unreadable or malformed recipients file yields no escrow and no + // names: fewer keys count as accepted, never more. + #[derive(serde::Deserialize, Default)] + struct Escrow { + key: Option, + #[serde(default)] + keys: Vec, + } + #[derive(serde::Deserialize, Default)] + struct File { + #[serde(default)] + recipients: BTreeMap, + escrow: Option, + } + let file: File = std::fs::read_to_string(layout.dot_sc.join("recipients.toml")) + .ok() + .and_then(|t| toml::from_str(&t).ok()) + .unwrap_or_default(); + for (name, k) in file.recipients { + if let Ok(pk) = PublicKey::from_key_string(&k) { + out.names.insert(pk.recipient_id().to_string(), name); + } + } + let escrow = file.escrow.unwrap_or_default(); + for k in escrow.key.iter().chain(escrow.keys.iter()) { + if let Ok(pk) = PublicKey::from_key_string(k) { + out.escrow.insert(pk.recipient_id().to_string()); + } + } + Ok(out) + } + + /// Also count `keys` as escrow: the break-glass set a caller passes in. + pub(crate) fn with_escrow(mut self, keys: &[PublicKey]) -> Accepted { + self.escrow + .extend(keys.iter().map(|k| k.recipient_id().to_string())); + self + } + + /// Also count `keys` as accepted for `scope` (the ones the user just named). + pub(crate) fn with_named(mut self, scope: &str, keys: &[PublicKey]) -> Accepted { + for k in keys { + self.pairs.insert((scope.to_string(), entry(scope, k))); + } + self + } + + fn is_accepted(&self, scope: &str, key: &PublicKey) -> bool { + self.escrow.contains(key.recipient_id().as_str()) + || self.pairs.contains(&(scope.to_string(), entry(scope, key))) + } + + /// The keys in `keys` not accepted for `scope`, deduped, in input order. + pub(crate) fn unaccepted(&self, scope: &str, keys: &[PublicKey]) -> Vec { + let mut out: Vec = Vec::new(); + for k in keys { + let key = entry(scope, k); + if self.is_accepted(scope, k) || out.iter().any(|u| u.key == key) { + continue; + } + let id = k.recipient_id().to_string(); + out.push(Unaccepted { + scope: scope.to_string(), + key, + name: self.names.get(&id).cloned(), + id, + }); + } + out + } + + /// Refuse (nothing written) unless every key in `keys` is accepted for `scope`. + pub(crate) fn require(&self, scope: &str, keys: &[PublicKey]) -> Result<()> { + refuse_if_any(self.unaccepted(scope, keys)) + } +} + +/// `Err` naming every pair, or `Ok` when there is none. +pub(crate) fn refuse_if_any(pairs: Vec) -> Result<()> { + if pairs.is_empty() { + Ok(()) + } else { + Err(Error::UnacceptedRecipients { pairs }) + } +} + +/// Scope text goes through a line-oriented file and a path prefix can hold any +/// byte but NUL, so escape the three characters the format uses. +fn esc(s: &str) -> String { + s.replace('%', "%25") + .replace('\t', "%09") + .replace('\n', "%0A") + .replace('\r', "%0D") +} + +fn unesc(s: &str) -> String { + s.replace("%0D", "\r") + .replace("%0A", "\n") + .replace("%09", "\t") + .replace("%25", "%") +} + +/// The recipient id behind a recorded entry, or `None` when the entry is not a +/// valid key or id for its scope. +fn entry_id(scope: &str, entry: &str) -> Option { + if scope.starts_with("path:") { + PublicKey::from_key_string(entry) + .ok() + .map(|k| k.recipient_id()) + } else { + RecipientId::from_hex(entry).ok() + } +} + +/// A missing file is an empty record; a line that does not parse is skipped +/// (an unreadable pair is never an accepted one). +fn read_pairs(layout: &Layout) -> Result> { + let text = match std::fs::read_to_string(layout.accepted_recipients_path()) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeSet::new()), + Err(e) => return Err(e.into()), + }; + Ok(text + .lines() + .filter_map(|l| l.split_once('\t')) + .map(|(s, e)| (unesc(s), e.to_string())) + .filter(|(s, e)| entry_id(s, e).is_some()) + .collect()) +} + +fn write_pairs(layout: &Layout, pairs: &BTreeSet<(String, String)>) -> Result<()> { + let body: String = pairs + .iter() + .map(|(s, e)| format!("{}\t{e}\n", esc(s))) + .collect(); + let tmp = layout.dot_sc.join("accepted-recipients.tmp"); + std::fs::write(&tmp, body)?; + std::fs::rename(&tmp, layout.accepted_recipients_path())?; + Ok(()) +} + +/// `path:`, `secret:` or `branch:`, with something after the colon. +fn validate_scope(scope: &str) -> Result<()> { + let ok = ["path:", "secret:", "branch:"] + .iter() + .any(|k| scope.strip_prefix(k).is_some_and(|rest| !rest.is_empty())); + if ok { + Ok(()) + } else { + Err(Error::InvalidArgument(format!( + "bad scope {scope:?}: use path:, secret: or branch:" + ))) + } +} + +impl Repo { + pub(crate) fn accepted(&self) -> Result { + Accepted::load(&self.layout) + } + + /// Record `id` as accepted for `scope` (`sc policy accept`; idempotent). + /// `key` is the full public key when the caller has it; a `path:` scope + /// records full keys, so it is required there. Local file only: allowed + /// while a merge, pick or rebase is stopped. + pub fn accept_recipient( + &self, + scope: &str, + id: &RecipientId, + key: Option<&PublicKey>, + ) -> Result<()> { + validate_scope(scope)?; + let recorded = match (scope.starts_with("path:"), key) { + (true, Some(k)) => entry(scope, k), + (true, None) => { + return Err(Error::InvalidArgument(format!( + "{scope} records full public keys: pass the scl-pk- key of {id}, \ + or a recipient id that is in .sc/recipients.toml" + ))) + } + (false, _) => id.to_string(), + }; + let mut pairs = read_pairs(&self.layout)?; + if pairs.insert((scope.to_string(), recorded)) { + write_pairs(&self.layout, &pairs)?; + } + Ok(()) + } + + /// [`Repo::accept_recipient`] for keys the user named on the command line. + pub fn accept_keys(&self, scope: &str, keys: &[PublicKey]) -> Result<()> { + for k in keys { + self.accept_recipient(scope, &k.recipient_id(), Some(k))?; + } + Ok(()) + } + + /// Remove every accepted pair of `scope` for this recipient (`sc policy + /// forget`, and every local revoke). Returns whether there was one. + pub fn forget_recipient(&self, scope: &str, id: &RecipientId) -> Result { + let mut pairs = read_pairs(&self.layout)?; + let before = pairs.len(); + pairs.retain(|(s, e)| s != scope || entry_id(s, e).as_ref() != Some(id)); + let removed = pairs.len() != before; + if removed { + write_pairs(&self.layout, &pairs)?; + } + Ok(removed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use scl_core::{Object, WrappedKey}; + use scl_crypto::{generate_keypair, SecretKey}; + use std::path::{Path, PathBuf}; + + fn dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("scl-accepted-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn put(root: &Path, rel: &str, body: &str) { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, body).unwrap(); + } + + fn id_of(pk: &PublicKey) -> String { + pk.recipient_id().to_string() + } + + /// The error's pairs, when it is a refusal that wrote nothing. + fn refused(r: Result) -> Vec { + match r { + Err(Error::UnacceptedRecipients { pairs }) => pairs, + other => panic!("expected an unaccepted-recipients refusal, got {other:?}"), + } + } + + /// Is a wrap addressed to `id` recorded in any snapshot in the store? + fn wrapped_to(repo: &Repo, id: &str) -> bool { + let store_arc = repo.vfs().store(); + let mut s = store_arc.lock().unwrap(); + for oid in s.list_loose().unwrap() { + if let Ok(Object::Snapshot(snap)) = s.get(&oid) { + if snap + .protection + .wrapped + .values() + .flatten() + .any(|w| w.recipient_id == id) + { + return true; + } + } + } + false + } + + /// A victim repo with `secret/` protected for the victim, cloned by a writer + /// who holds no key (`attack` runs in that clone), then fetched back as + /// remote `a`. + struct World { + v: Repo, + v_root: PathBuf, + a_root: PathBuf, + vsk: SecretKey, + atk: PublicKey, + } + + fn world(tag: &str, attack: impl FnOnce(&Repo, &PublicKey)) -> World { + let v_root = dir(&format!("{tag}-v")); + let a_root = dir(&format!("{tag}-a")); + std::fs::remove_dir_all(&a_root).unwrap(); + let (vsk, vpk) = generate_keypair(); + let (_, atk) = generate_keypair(); + let v = Repo::init(&v_root).unwrap(); + put(&v_root, "secret/a.txt", "victim data\n"); + put(&v_root, "readme.txt", "hello\n"); + v.protect("secret/", &[vpk], None).unwrap(); + drop(v); + let a = Repo::clone_to(&v_root, &a_root).unwrap(); + attack(&a, &atk); + drop(a); + let v = Repo::open(&v_root).unwrap(); + v.remote_add("a", a_root.to_str().unwrap()).unwrap(); + v.fetch("a").unwrap(); + World { + v, + v_root, + a_root, + vsk, + atk, + } + } + + impl World { + fn pull(&self) { + self.v + .merge_with_identity("a/main", "me", Some(&self.vsk)) + .unwrap(); + } + fn cleanup(self) { + let (v, a) = (self.v_root.clone(), self.a_root.clone()); + drop(self); + let _ = std::fs::remove_dir_all(v); + let _ = std::fs::remove_dir_all(a); + } + } + + // 1. A narrower rule from a keyless writer: the victim fast-forwards, edits + // under it and commits. Refused, nothing moved, no wrap to the attacker in + // the store; after an explicit accept it passes. + #[test] + fn a_narrower_rule_from_a_writer_is_refused_until_accepted() { + let w = world("narrow", |a, atk| { + a.protect("secret/sub/", std::slice::from_ref(atk), None) + .unwrap(); + }); + w.pull(); + let atk_id = id_of(&w.atk); + put(&w.v_root, "secret/sub/x.txt", "new victim data\n"); + let tip = w.v.head_tip().unwrap(); + let pairs = refused(w.v.commit("me", "edit")); + assert_eq!( + pairs, + vec![Unaccepted { + scope: "path:secret/sub/".into(), + key: w.atk.to_key_string(), + id: atk_id.clone(), + name: None + }] + ); + assert_eq!(w.v.head_tip().unwrap(), tip, "the ref did not move"); + assert!(!wrapped_to(&w.v, &atk_id), "no wrap to the attacker stored"); + + w.v.accept_keys("path:secret/sub/", std::slice::from_ref(&w.atk)) + .unwrap(); + w.v.commit("me", "edit").unwrap(); + assert!(wrapped_to(&w.v, &atk_id), "sealed to the accepted key"); + w.cleanup(); + } + + // 2a. The same on a fresh clone, and the error names the local recipient + // (a key listed in recipients.toml is still not an accepted one). + #[test] + fn a_fresh_clone_refuses_and_names_the_local_recipient() { + let w = world("fresh", |a, atk| { + a.protect("secret/sub/", std::slice::from_ref(atk), None) + .unwrap(); + }); + let c_root = dir("fresh-c"); + std::fs::remove_dir_all(&c_root).unwrap(); + let c = Repo::clone_to(&w.a_root, &c_root).unwrap(); + put(&c_root, "secret/sub/x.txt", "data\n"); + let atk_id = id_of(&w.atk); + let unknown = refused(c.commit("me", "m")); + assert_eq!(unknown[0].name, None); + let text = Error::UnacceptedRecipients { pairs: unknown }.to_string(); + assert!( + text.contains(&format!( + "sc policy accept path:secret/sub/ --key {} --allow-unknown", + w.atk.to_key_string() + )) && text.contains(&format!("sc revoke secret/sub/ --recipient-id {atk_id}")) + && text.contains("(UNKNOWN)") + && text.contains("Nothing was written."), + "{text}" + ); + + put( + &c_root, + ".sc/recipients.toml", + &format!("[recipients]\nmallory = \"{}\"\n", w.atk.to_key_string()), + ); + let named = refused(c.commit("me", "m")); + assert_eq!(named[0].name.as_deref(), Some("mallory")); + assert!(!named[0].accept_command().contains("--allow-unknown")); + drop(c); + let _ = std::fs::remove_dir_all(c_root); + w.cleanup(); + } + + // 2b. A merge where only theirs has the rule: ours' plain file under it must + // be sealed by the merge, which wraps to their key. + #[test] + fn a_merge_that_brings_in_a_rule_refuses_to_seal_to_its_key() { + let v_root = dir("merge-v"); + let a_root = dir("merge-a"); + std::fs::remove_dir_all(&a_root).unwrap(); + let (_, atk) = generate_keypair(); + let v = Repo::init(&v_root).unwrap(); + put(&v_root, "readme.txt", "hello\n"); + v.commit("me", "base").unwrap(); + drop(v); + let a = Repo::clone_to(&v_root, &a_root).unwrap(); + a.protect("docs/", std::slice::from_ref(&atk), None) + .unwrap(); + drop(a); + let v = Repo::open(&v_root).unwrap(); + put(&v_root, "docs/q.txt", "ours only\n"); + v.commit("me", "docs").unwrap(); + v.remote_add("a", a_root.to_str().unwrap()).unwrap(); + v.fetch("a").unwrap(); + + let tip = v.head_tip().unwrap(); + let atk_id = id_of(&atk); + let pairs = refused(v.merge("a/main", "me")); + assert_eq!(pairs[0].scope, "path:docs/"); + assert_eq!(pairs[0].id, atk_id); + assert_eq!(v.head_tip().unwrap(), tip); + assert_eq!( + std::fs::read_to_string(v_root.join("docs/q.txt")).unwrap(), + "ours only\n" + ); + assert!(!wrapped_to(&v, &atk_id)); + + v.accept_keys("path:docs/", std::slice::from_ref(&atk)) + .unwrap(); + v.merge("a/main", "me").unwrap(); + assert!(wrapped_to(&v, &atk_id)); + drop(v); + let _ = std::fs::remove_dir_all(v_root); + let _ = std::fs::remove_dir_all(a_root); + } + + /// Plant a wrap label for `atk_id` (no usable wrap bytes) on a secret. + fn plant_secret_label(repo: &Repo, name: &str, atk_id: &str) { + let tip = repo.head_tip().unwrap().unwrap(); + let snap = repo.snapshot(&tip).unwrap(); + let store_arc = repo.vfs().store(); + let mut s = store_arc.lock().unwrap(); + let Object::Secret(mut secret) = s.get(&snap.secrets[name]).unwrap() else { + panic!("not a secret") + }; + secret.wrapped_keys.push(WrappedKey { + recipient_id: atk_id.into(), + wrapped_dek: vec![0; 48], + }); + let sid = s.put(Object::Secret(secret)).unwrap(); + drop(s); + let mut secrets = snap.secrets.clone(); + secrets.insert(name.into(), sid); + repo.commit_snapshot(snap.root, vec![tip], secrets, snap.protection, "w", "x") + .unwrap(); + } + + // 3. A bogus wrap label on a secret: rotate without --to would re-seal to + // that key; rewrap skips the entry, keeps the rest and reports it. + #[test] + fn a_planted_secret_label_blocks_rotate_and_is_skipped_by_rewrap() { + let root = dir("secret-label"); + let (vsk, vpk) = generate_keypair(); + let (_, atk) = generate_keypair(); + let v = Repo::init(&root).unwrap(); + v.secret_add("API_TOKEN", b"t", std::slice::from_ref(&vpk)) + .unwrap(); + v.secret_add("OTHER", b"o", std::slice::from_ref(&vpk)) + .unwrap(); + let atk_id = id_of(&atk); + plant_secret_label(&v, "API_TOKEN", &atk_id); + + // What the CLI derives from the labels with the key in recipients.toml. + let both = [vpk.clone(), atk.clone()]; + let pairs = refused(v.secret_rotate("API_TOKEN", None, &both, Some(&vsk))); + assert_eq!(pairs[0].scope, "secret:API_TOKEN"); + assert_eq!(pairs[0].id, atk_id); + assert!(pairs[0] + .remove_command() + .starts_with("sc secret revoke API_TOKEN --recipient-id")); + + let report = v.rewrap(&vsk, &[], &both, false).unwrap(); + assert_eq!(report.secrets_rewrapped, vec!["OTHER".to_string()]); + assert!(report.commit.is_some(), "partial success is kept"); + assert_eq!(report.skipped.len(), 1); + assert_eq!(report.skipped[0].0, "secret API_TOKEN"); + assert!( + report.skipped[0].1.contains(&atk_id), + "{:?}", + report.skipped + ); + + // Accepting it is the user's call; then the rotate goes through. + v.accept_keys("secret:API_TOKEN", std::slice::from_ref(&atk)) + .unwrap(); + v.secret_rotate("API_TOKEN", None, &both, Some(&vsk)) + .unwrap(); + drop(v); + let _ = std::fs::remove_dir_all(root); + } + + // 4. A bogus kek_wraps label: revoke would hand the fresh KEK to that key. + #[test] + fn a_planted_branch_label_blocks_revoke() { + let root = dir("branch-label"); + let (vsk, vpk) = generate_keypair(); + let (_, bob) = generate_keypair(); + let (_, atk) = generate_keypair(); + let v = Repo::init(&root).unwrap(); + put(&root, "a.txt", "a\n"); + v.commit("me", "base").unwrap(); + v.branch_private("emb", &vsk, std::slice::from_ref(&bob), &[]) + .unwrap(); + let atk_id = id_of(&atk); + let (mid, mut m) = v.branch_manifest("emb").unwrap().unwrap(); + m.kek_wraps.push(WrappedKey { + recipient_id: atk_id.clone(), + wrapped_dek: vec![0; 48], + }); + m.prev = Some(mid); + let planted = { + let store_arc = v.vfs().store(); + let id = store_arc.lock().unwrap().put(Object::Manifest(m)).unwrap(); + id + }; + crate::refs::write_branch_tip(v.layout(), "emb", &planted).unwrap(); + + let remaining = [vpk.clone(), atk.clone()]; + let pairs = refused(v.branch_revoke("emb", &vsk, &bob.recipient_id(), &remaining)); + assert_eq!(pairs[0].scope, "branch:emb"); + assert_eq!(pairs[0].id, atk_id); + assert_eq!( + crate::refs::read_branch_tip(v.layout(), "emb").unwrap(), + Some(planted), + "the manifest did not change" + ); + + v.accept_keys("branch:emb", std::slice::from_ref(&atk)) + .unwrap(); + v.branch_revoke("emb", &vsk, &bob.recipient_id(), &remaining) + .unwrap(); + // A local revoke drops the pair, so a later reappearance is refused again. + assert_eq!( + v.accepted() + .unwrap() + .unaccepted("branch:emb", std::slice::from_ref(&bob)) + .len(), + 1 + ); + drop(v); + let _ = std::fs::remove_dir_all(root); + } + + // The writer adds its key to the victim's existing rule. + fn world_with_foreign_key_in_rule(tag: &str) -> World { + world(tag, |a, atk| { + // Built by hand: an honest `sc protect` in this clone would refuse + // the victim's own key, which the writer has not accepted. The + // writer cannot unwrap any DEK, so the sealed file keeps its wrap + // list; only the rule changes. + let tip = a.head_tip().unwrap().unwrap(); + let snap = a.snapshot(&tip).unwrap(); + let mut prot = snap.protection; + let rule = prot + .prefixes + .iter_mut() + .find(|p| p.prefix == "secret/") + .unwrap(); + let epoch = rule.next_epoch(); + rule.set_standing(atk.to_bytes(), epoch, scl_core::RecipientState::Granted); + a.commit_snapshot(snap.root, vec![tip], snap.secrets, prot, "w", "x") + .unwrap(); + }) + } + + // 5. Own `protect --to` then commit needs no accept; protect over a merged-in + // foreign key refuses before any ref move. + #[test] + fn protect_accepts_its_own_keys_but_refuses_a_foreign_one_before_moving_a_ref() { + let w = world_with_foreign_key_in_rule("protect"); + let (_, me) = generate_keypair(); + // Own protect, own commit: no accept anywhere. + put(&w.v_root, "mine/x.txt", "x\n"); + w.v.protect("mine/", std::slice::from_ref(&me), None) + .unwrap(); + put(&w.v_root, "mine/x.txt", "y\n"); + w.v.commit("me", "again").unwrap(); + + w.pull(); + let tip = w.v.head_tip().unwrap(); + let oplog = w.v.oplog().unwrap().len(); + let pairs = refused(w.v.protect("secret/", std::slice::from_ref(&me), None)); + assert_eq!(pairs[0].scope, "path:secret/"); + assert_eq!(pairs[0].id, id_of(&w.atk)); + assert_eq!(w.v.head_tip().unwrap(), tip, "no ref move"); + assert_eq!(w.v.oplog().unwrap().len(), oplog, "no oplog record"); + + w.v.accept_keys("path:secret/", std::slice::from_ref(&w.atk)) + .unwrap(); + w.v.protect("secret/", std::slice::from_ref(&me), None) + .unwrap(); + w.cleanup(); + } + + // protect also builds its sealing commit before moving any ref, so a seal + // that another rule's unaccepted key refuses leaves no policy-only commit. + #[test] + fn protect_leaves_no_policy_commit_when_another_rule_refuses_its_seal() { + let w = world("protect-atomic", |a, atk| { + a.protect("secret/sub/", std::slice::from_ref(atk), None) + .unwrap(); + }); + w.pull(); + let (_, me) = generate_keypair(); + put(&w.v_root, "secret/sub/x.txt", "victim data\n"); + put(&w.v_root, "docs/y.txt", "y\n"); + let tip = w.v.head_tip().unwrap(); + let oplog = w.v.oplog().unwrap().len(); + let pairs = refused(w.v.protect("docs/", std::slice::from_ref(&me), None)); + assert_eq!(pairs[0].scope, "path:secret/sub/"); + assert_eq!(w.v.head_tip().unwrap(), tip, "no ref move"); + assert_eq!(w.v.oplog().unwrap().len(), oplog, "no oplog record"); + assert!(w + .v + .protected_prefixes() + .unwrap() + .iter() + .all(|(p, _)| p != "docs/")); + w.cleanup(); + } + + // 6. A commit that only carries sealed content passes with an unaccepted key + // in the rule; the same commit sealing a changed file does not. + #[test] + fn a_carry_only_commit_passes_with_an_unaccepted_key_in_the_rule() { + let w = world_with_foreign_key_in_rule("carry"); + w.pull(); + put(&w.v_root, "readme.txt", "edited\n"); + w.v.commit("me", "carry only").unwrap(); + assert!( + !wrapped_to(&w.v, &id_of(&w.atk)), + "carrying minted no wrap for the planted key" + ); + + put(&w.v_root, "secret/a.txt", "changed\n"); + let pairs = refused(w.v.commit("me", "seals")); + assert_eq!(pairs[0].id, id_of(&w.atk)); + w.cleanup(); + } + + // 7. A secret added in this clone can be rotated with the default recipient + // set; a key outside it cannot. + #[test] + fn secret_add_then_default_rotate_passes() { + let root = dir("rotate"); + let (vsk, vpk) = generate_keypair(); + let (_, other) = generate_keypair(); + let v = Repo::init(&root).unwrap(); + v.secret_add("S1", b"v", std::slice::from_ref(&vpk)) + .unwrap(); + v.secret_rotate("S1", None, std::slice::from_ref(&vpk), Some(&vsk)) + .unwrap(); + refused(v.secret_rotate("S1", None, &[vpk, other], Some(&vsk))); + drop(v); + let _ = std::fs::remove_dir_all(root); + } + + // 8. A stopped merge refuses on an unaccepted key; accepting while stopped + // lets the completion retry. + #[test] + fn a_stopped_merge_completes_after_an_accept_made_during_the_stop() { + let v_root = dir("stop-v"); + let a_root = dir("stop-a"); + std::fs::remove_dir_all(&a_root).unwrap(); + let (_, atk) = generate_keypair(); + let v = Repo::init(&v_root).unwrap(); + put(&v_root, "n.txt", "base\n"); + v.commit("me", "base").unwrap(); + drop(v); + let a = Repo::clone_to(&v_root, &a_root).unwrap(); + put(&a_root, "n.txt", "theirs\n"); + a.protect("docs/", std::slice::from_ref(&atk), None) + .unwrap(); + drop(a); + let v = Repo::open(&v_root).unwrap(); + put(&v_root, "n.txt", "ours\n"); + put(&v_root, "docs/q.txt", "ours only\n"); + v.commit("me", "ours").unwrap(); + v.remote_add("a", a_root.to_str().unwrap()).unwrap(); + v.fetch("a").unwrap(); + assert!(matches!( + v.merge("a/main", "me"), + Err(Error::MergeConflicts(1)) + )); + put(&v_root, "n.txt", "resolved\n"); + + let atk_id = id_of(&atk); + let pairs = refused(v.commit("me", "merge")); + assert_eq!(pairs[0].id, atk_id); + assert!( + crate::merge_state::in_progress(v.layout()), + "the stop is intact" + ); + + v.accept_keys("path:docs/", std::slice::from_ref(&atk)) + .unwrap(); + let id = v.commit("me", "merge").unwrap(); + assert!(!crate::merge_state::in_progress(v.layout())); + assert_eq!(v.snapshot(&id).unwrap().parents.len(), 2); + assert!(wrapped_to(&v, &atk_id)); + drop(v); + let _ = std::fs::remove_dir_all(v_root); + let _ = std::fs::remove_dir_all(a_root); + } + + // 9. The record never travels: not in a clone, not by push or fetch, and gc + // leaves it alone. + #[test] + fn the_record_never_appears_in_clone_fetch_or_push() { + let v_root = dir("travel-v"); + let c_root = dir("travel-c"); + std::fs::remove_dir_all(&c_root).unwrap(); + let (_, pk) = generate_keypair(); + let v = Repo::init(&v_root).unwrap(); + put(&v_root, "secret/a.txt", "x\n"); + v.protect("secret/", &[pk], None).unwrap(); + let record = v.layout().accepted_recipients_path(); + let bytes = std::fs::read(&record).unwrap(); + assert!(!bytes.is_empty(), "premise: protect recorded its key"); + drop(v); + + let c = Repo::clone_to(&v_root, &c_root).unwrap(); + let c_record = c.layout().accepted_recipients_path(); + assert!(!c_record.exists(), "a clone starts with an empty record"); + // What the origin accepted is not inherited: sealing to its key is + // refused here until this clone accepts it. + put(&c_root, "secret/b.txt", "b\n"); + refused(c.commit("me", "seal")); + std::fs::remove_file(c_root.join("secret/b.txt")).unwrap(); + put(&c_root, "more.txt", "m\n"); + c.commit("me", "more").unwrap(); + c.push("origin").unwrap(); + assert!(!c_record.exists(), "a push does not create it either"); + assert_eq!(std::fs::read(&record).unwrap(), bytes, "push left it alone"); + drop(c); + + let v = Repo::open(&v_root).unwrap(); + v.remote_add("c", c_root.to_str().unwrap()).unwrap(); + v.fetch("c").unwrap(); + v.gc(std::time::Duration::from_secs(0)).unwrap(); + assert_eq!(std::fs::read(&record).unwrap(), bytes, "fetch and gc too"); + drop(v); + let _ = std::fs::remove_dir_all(v_root); + let _ = std::fs::remove_dir_all(c_root); + } + + // A prefix may hold tabs, newlines and `%`; the file format must survive it. + // A path scope records the full key, the others the id. + #[test] + fn a_scope_with_control_characters_round_trips() { + let root = dir("escape"); + let (_, pk) = generate_keypair(); + let (_, other) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + let scope = "path:we\tird\n%0A\r/"; + repo.accept_keys(scope, std::slice::from_ref(&pk)).unwrap(); + repo.accept_keys("secret:S", std::slice::from_ref(&pk)) + .unwrap(); + let text = std::fs::read_to_string(repo.layout().accepted_recipients_path()).unwrap(); + assert!(text.contains(&format!( + "path:we%09ird%0A%250A%0D/\t{}", + pk.to_key_string() + ))); + assert!(text.contains(&format!("secret:S\t{}", id_of(&pk)))); + let acc = repo.accepted().unwrap(); + assert!(acc.unaccepted(scope, std::slice::from_ref(&pk)).is_empty()); + assert_eq!(acc.unaccepted(scope, std::slice::from_ref(&other)).len(), 1); + assert_eq!(acc.pairs.len(), 2); + // A path scope needs the full key; a bad scope is refused. + assert!(repo + .accept_recipient("path:x/", &pk.recipient_id(), None) + .is_err()); + repo.accept_recipient("secret:T", &pk.recipient_id(), None) + .unwrap(); + assert!(repo.accept_keys("nope", std::slice::from_ref(&pk)).is_err()); + // Forgetting goes by recipient id, whichever form was recorded. + assert!(repo.forget_recipient(scope, &pk.recipient_id()).unwrap()); + assert!(!repo.forget_recipient(scope, &pk.recipient_id()).unwrap()); + assert!(repo + .forget_recipient("secret:S", &pk.recipient_id()) + .unwrap()); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // Escrow is accepted in every scope. + #[test] + fn local_escrow_counts_as_accepted_everywhere() { + let root = dir("escrow"); + let (_, escrow) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put( + &root, + ".sc/recipients.toml", + &format!("[escrow]\nkeys = [\"{}\"]\n", escrow.to_key_string()), + ); + let acc = repo.accepted().unwrap(); + let (_, other) = generate_keypair(); + for scope in ["path:a/", "secret:X", "branch:b"] { + assert!(acc + .unaccepted(scope, std::slice::from_ref(&escrow)) + .is_empty()); + assert_eq!(acc.unaccepted(scope, std::slice::from_ref(&other)).len(), 1); + } + drop(repo); + let _ = std::fs::remove_dir_all(root); + } +} diff --git a/crates/repo/src/error.rs b/crates/repo/src/error.rs index eb9807ec..3bdaf757 100644 --- a/crates/repo/src/error.rs +++ b/crates/repo/src/error.rs @@ -30,6 +30,12 @@ pub enum Error { NotAuthorized(String), #[error("invalid argument: {}", scl_core::sanitize_display_line(.0))] InvalidArgument(String), + /// A seal would wrap a key to a recipient this clone never accepted for the + /// scope (ADR-0059). Raised before any ref moves. + #[error("{}", crate::accepted::describe(.pairs))] + UnacceptedRecipients { + pairs: Vec, + }, #[error("operation requires at least one commit (branch is unborn)")] Unborn, #[error("a merge is already in progress (resolve and `sc commit`, or `sc merge --abort`)")] diff --git a/crates/repo/src/layout.rs b/crates/repo/src/layout.rs index e3b84350..ffcba040 100644 --- a/crates/repo/src/layout.rs +++ b/crates/repo/src/layout.rs @@ -110,6 +110,12 @@ impl Layout { pub fn transcript_pending_trust_path(&self) -> PathBuf { self.dot_sc.join("transcript-pending-trust") } + /// `.sc/accepted-recipients` — the keys this clone accepted per scope + /// (ADR-0059). Local state like `.sc/local-key`: never committed, packed, + /// transferred or read by gc. + pub fn accepted_recipients_path(&self) -> PathBuf { + self.dot_sc.join("accepted-recipients") + } /// `.sc/tmp` — scratch space for transient files (P25 streaming pack /// transfer: spilled sender/receiver pack bodies). Never durable state — /// safe to delete at any time; callers that write here are responsible diff --git a/crates/repo/src/lib.rs b/crates/repo/src/lib.rs index 945e0f2f..84d7da75 100644 --- a/crates/repo/src/lib.rs +++ b/crates/repo/src/lib.rs @@ -3,6 +3,7 @@ #[cfg(test)] mod abort_transitions; +pub mod accepted; pub mod bucket_transport; pub(crate) mod cache; pub(crate) mod conflict_plaintext; diff --git a/crates/repo/src/partial_merge.rs b/crates/repo/src/partial_merge.rs index bddd3361..4be4c9de 100644 --- a/crates/repo/src/partial_merge.rs +++ b/crates/repo/src/partial_merge.rs @@ -772,6 +772,11 @@ fn keyless_protected_merge_refuses_before_fetching_the_ciphertext() { before ); + // Resealing the merged content wraps to the rule's key, which this fresh + // clone has not accepted yet (ADR-0059). + clone + .accept_keys("path:vault/", std::slice::from_ref(&pk)) + .unwrap(); let (merged, _) = clone .merge_with_identity("origin/b2", "t", Some(&sk)) .unwrap(); diff --git a/crates/repo/src/private.rs b/crates/repo/src/private.rs index 52fbaeb2..844b826a 100644 --- a/crates/repo/src/private.rs +++ b/crates/repo/src/private.rs @@ -331,6 +331,8 @@ impl Repo { wrap_keys.push(pk.clone()); } } + // The creator and the keys named for this branch are accepted for it. + self.accept_keys(&crate::accepted::branch_scope(name), &wrap_keys)?; let kek_wraps: Vec = wrap_keys .iter() .map(|pk| scl_crypto::wrap_kek_for(&kek, pk)) @@ -1234,6 +1236,11 @@ impl Repo { ) -> Result { self.guard_states()?; let ctx = self.open_private_branch(name, Some(identity))?; + // The caller named `new`, so it is accepted for this branch. + self.accept_keys( + &crate::accepted::branch_scope(name), + std::slice::from_ref(new), + )?; let mut kek_wraps = ctx.manifest.kek_wraps.clone(); let new_id = new.recipient_id().to_string(); kek_wraps.retain(|w| w.recipient_id != new_id); @@ -1293,6 +1300,11 @@ impl Repo { ))); } + // `remaining` was resolved from the manifest's own wrap labels + // (repository data): the fresh KEK may only go to keys this clone + // accepted for the branch (ADR-0059). + self.accepted()? + .require(&crate::accepted::branch_scope(name), remaining)?; let new_kek = scl_crypto::generate_kek(); let kek_wraps: Vec = remaining .iter() @@ -1306,7 +1318,9 @@ impl Repo { index_ct: ctx.index.encrypt(&new_kek), kek_wraps, }; - self.replace_manifest(name, &ctx, manifest, &format!("branch revoke {name}")) + let id = self.replace_manifest(name, &ctx, manifest, &format!("branch revoke {name}"))?; + self.forget_recipient(&crate::accepted::branch_scope(name), revoked)?; + Ok(id) } fn replace_manifest( @@ -1857,9 +1871,13 @@ impl Repo { } let bytes = self.inner_blob(&mut store, &ctx, id)?; match crate::protect::matching_prefix(&snap.protection, path) { - Some(rule) => { - to_encrypt.push((path.clone(), bytes, *mode, rule.granted_keys())) - } + Some(rule) => to_encrypt.push(( + path.clone(), + bytes, + *mode, + rule.granted_keys(), + rule.prefix.clone(), + )), None => plain.push((path.clone(), bytes, *mode)), } } @@ -1873,12 +1891,13 @@ impl Repo { let seal_plaintexts: BTreeMap> = if *inner_id == inner_tip { to_encrypt .iter() - .map(|(p, b, _, _)| (p.clone(), b.clone())) + .map(|(p, b, ..)| (p.clone(), b.clone())) .collect() } else { BTreeMap::new() }; - let (encrypted, fresh) = crate::protect::encrypt_protected(to_encrypt)?; + let (encrypted, fresh) = + crate::protect::encrypt_protected(to_encrypt, &self.accepted()?)?; for (path, ct, mode, perms) in encrypted { let blob = Object::blob(ct.clone()); let bid = blob.id(); diff --git a/crates/repo/src/protect.rs b/crates/repo/src/protect.rs index 2afc1fc5..46685198 100644 --- a/crates/repo/src/protect.rs +++ b/crates/repo/src/protect.rs @@ -124,8 +124,9 @@ pub(crate) fn decrypt_with( } /// A working-tree file headed for sealing: `(path, plaintext, mode, recipient -/// pubkeys)`. -pub(crate) type SealInput = (String, Vec, FileMode, Vec<[u8; 32]>); +/// pubkeys, winning rule's prefix)`. The prefix names the scope the recipients +/// must be accepted for (ADR-0059). +pub(crate) type SealInput = (String, Vec, FileMode, Vec<[u8; 32]>, String); /// A sealed (or carried) protected file: `(path, ciphertext, mode, perms)`. pub(crate) type SealedFile = (String, Vec, FileMode, u8); /// Wrapped DEKs keyed by the ciphertext blob they unlock. @@ -141,11 +142,32 @@ pub(crate) type WrapMap = BTreeMap>; /// file's recipient list is empty: a rule whose every recipient is /// tombstoned (e.g. crossed revokes merged together) must fail the seal /// loudly — sealing to nobody mints permanently unreadable ciphertext. -pub(crate) fn encrypt_protected(plaintexts: Vec) -> Result<(Vec, WrapMap)> { +/// +/// The one place a rule's recipients become wraps, so it is also the gate +/// (ADR-0059): every recipient must be accepted in this clone for the winning +/// rule's scope (or be local escrow), else the call refuses, naming every +/// unaccepted pair, before any file is sealed. +pub(crate) fn encrypt_protected( + plaintexts: Vec, + accepted: &crate::accepted::Accepted, +) -> Result<(Vec, WrapMap)> { + let mut unaccepted: Vec = Vec::new(); + for (_, _, _, recipients, prefix) in &plaintexts { + let keys: Vec = recipients + .iter() + .map(|k| scl_crypto::PublicKey::from_bytes(*k)) + .collect(); + for u in accepted.unaccepted(&crate::accepted::path_scope(prefix), &keys) { + if !unaccepted.contains(&u) { + unaccepted.push(u); + } + } + } + crate::accepted::refuse_if_any(unaccepted)?; // Encrypt protected files; accumulate fresh wrapped DEKs keyed by blob id. let mut all: Vec<(String, Vec, FileMode, u8)> = Vec::new(); let mut fresh_wrapped: BTreeMap> = BTreeMap::new(); - for (path, bytes, mode, recipients) in plaintexts { + for (path, bytes, mode, recipients, _) in plaintexts { if recipients.is_empty() { return Err(Error::InvalidArgument(format!( "{path} is protected but its rule has no granted recipients \ @@ -202,12 +224,17 @@ mod tests { fn encrypt_protected_seals_randomized() { let (_sk, pk) = scl_crypto::generate_keypair(); let f = |v: &[u8]| { - encrypt_protected(vec![( - "secret/x".into(), - v.to_vec(), - FileMode::FILE, - vec![pk.to_bytes()], - )]) + encrypt_protected( + vec![( + "secret/x".into(), + v.to_vec(), + FileMode::FILE, + vec![pk.to_bytes()], + "secret/".into(), + )], + &crate::accepted::Accepted::default() + .with_named("path:secret/", std::slice::from_ref(&pk)), + ) .unwrap() }; let (a1, _) = f(b"same"); @@ -403,12 +430,16 @@ mod tests { #[test] fn encrypt_protected_refuses_empty_recipient_list() { - let err = encrypt_protected(vec![( - "secret/x".into(), - b"v".to_vec(), - FileMode::FILE, - vec![], - )]) + let err = encrypt_protected( + vec![( + "secret/x".into(), + b"v".to_vec(), + FileMode::FILE, + vec![], + "secret/".into(), + )], + &crate::accepted::Accepted::default(), + ) .unwrap_err(); assert!( matches!(err, Error::InvalidArgument(_)), diff --git a/crates/repo/src/protect_ops.rs b/crates/repo/src/protect_ops.rs index ec1fdf64..d9988b10 100644 --- a/crates/repo/src/protect_ops.rs +++ b/crates/repo/src/protect_ops.rs @@ -82,9 +82,29 @@ impl Repo { .collect(), }), } + // The candidate rule holds the keys just named plus any already in it + // (a merged-in foreign one), and the sealing commit would wrap to all of + // them, so refuse before anything moves (ADR-0059). This catches a rule + // with nothing to seal yet too. + let scope = crate::accepted::path_scope(prefix); + if let Some(rule) = protection.prefixes.iter().find(|p| p.prefix == prefix) { + let granted: Vec = rule + .granted_keys() + .iter() + .map(|k| scl_crypto::PublicKey::from_bytes(*k)) + .collect(); + self.accepted()? + .with_named(&scope, recipients) + .require(&scope, &granted)?; + } + self.accept_keys(&scope, recipients)?; let head = crate::refs::current_branch(self.layout())?; let before = crate::refs::read_branch_tip(self.layout(), &head)?; - let id = self.commit_snapshot( + // Build the rule's snapshot and the sealing commit on top of it before + // either ref moves, so a seal the gate refuses under ANY rule leaves the + // ref and the oplog untouched. (`commit` does the same work, but only + // after the rule's own ref move.) + let policy_id = self.build_snapshot( root, parents, secrets, @@ -92,17 +112,42 @@ impl Repo { "system", &format!("protect {prefix}"), )?; + let files = worktree::read_worktree(&self.layout, &self.tracked_paths()?)?; + let mut cache = self.open_protected_cache()?; + let message = format!("encrypt under {prefix}"); + let id = self.snapshot_files( + files, + Some(policy_id), + None, + None, + None, + None, + None, + &self.sparse_spec()?, + &self.layout.root, + Some(&mut cache), + "system", + &message, + )?; + crate::refs::write_branch_tip(self.layout(), &head, &policy_id)?; crate::oplog::record( self.layout(), &format!("protect {prefix}"), &head, &head, - &[(head.clone(), before, Some(id))], + &[(head.clone(), before, Some(policy_id))], )?; - // Now encrypt matching working-tree files under the freshly-recorded rule. - // `commit` (repo.rs) logs its own oplog record ("commit: encrypt under - // ") — a second, distinct ref move, so no double-logging here. - self.commit("system", &format!("encrypt under {prefix}")) + // The sealing commit logs its own record, like `commit`. + crate::refs::write_branch_tip(self.layout(), &head, &id)?; + cache.save_best_effort(); + crate::oplog::record( + self.layout(), + &format!("commit: {message}"), + &head, + &head, + &[(head.clone(), Some(policy_id), Some(id))], + )?; + Ok(id) } /// Collect the PROTECTED blob ids in the tip tree whose path is governed by @@ -163,6 +208,11 @@ impl Repo { .position(|p| p.prefix == prefix) .ok_or_else(|| Error::NotProtected(prefix.to_string()))?; + // The caller named `new`, so it is accepted for this prefix. + self.accept_keys( + &crate::accepted::path_scope(prefix), + std::slice::from_ref(new), + )?; let protected_ids = self.protected_blob_ids_under(root, &protection, prefix)?; let authorized_id = authorized.public().recipient_id().to_string(); let new_id = new.recipient_id().to_string(); @@ -299,6 +349,7 @@ impl Repo { &head, &[(head.clone(), before, Some(id))], )?; + self.forget_recipient(&crate::accepted::path_scope(prefix), recipient_id)?; Ok(id) } diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 27a8ee4e..3dbf019e 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -105,21 +105,30 @@ fn split_for_encryption( union_prot: &Protection, ) -> Result<( Vec<(String, Vec, FileMode, u8)>, - Vec<(String, Vec, FileMode, Vec<[u8; 32]>)>, + Vec, )> { let mut carried: Vec<(String, Vec, FileMode, u8)> = Vec::new(); - let mut to_encrypt: Vec<(String, Vec, FileMode, Vec<[u8; 32]>)> = Vec::new(); + let mut to_encrypt: Vec = Vec::new(); for f in files { if f.needs_encrypt { - let recipients = protect::matching_prefix(union_prot, &f.path) - .map(|r| r.granted_keys()) + let rule = protect::matching_prefix(union_prot, &f.path) .ok_or_else(|| Error::NotProtected(f.path.clone()))?; - to_encrypt.push((f.path.clone(), f.bytes.clone(), f.mode, recipients)); + to_encrypt.push(( + f.path.clone(), + f.bytes.clone(), + f.mode, + rule.granted_keys(), + rule.prefix.clone(), + )); } else if f.perms & scl_core::PROTECTED == 0 { match protect::matching_prefix(union_prot, &f.path) { - Some(rule) => { - to_encrypt.push((f.path.clone(), f.bytes.clone(), f.mode, rule.granted_keys())) - } + Some(rule) => to_encrypt.push(( + f.path.clone(), + f.bytes.clone(), + f.mode, + rule.granted_keys(), + rule.prefix.clone(), + )), None => carried.push((f.path.clone(), f.bytes.clone(), f.mode, 0)), } } else { @@ -241,7 +250,7 @@ pub(crate) fn replay_commit( }; let (mut all, to_encrypt) = split_for_encryption(&fm.files, &union_prot)?; - let (encrypted, fresh_wrapped) = protect::encrypt_protected(to_encrypt)?; + let (encrypted, fresh_wrapped) = protect::encrypt_protected(to_encrypt, &repo.accepted()?)?; all.extend(encrypted); let root = match &tree_carried { Some((crate::merge_tree::Carried::Root(id), _)) => *id, diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 61841091..66164dd1 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -481,7 +481,9 @@ impl Repo { let mut protected: Vec = Vec::new(); for (path, bytes, mode) in files { match crate::protect::matching_prefix(&protection, &path) { - Some(rule) => protected.push((path, bytes, mode, rule.granted_keys())), + Some(rule) => { + protected.push((path, bytes, mode, rule.granted_keys(), rule.prefix.clone())) + } None => plain.push((path, bytes, mode)), } } @@ -580,7 +582,7 @@ impl Repo { Some(h) if cache.is_some() => Some(self.snapshot(&h)?.root), _ => None, }; - for (path, bytes, mode, granted) in protected { + for (path, bytes, mode, granted, prefix) in protected { // Does `blob_id` (a protected blob with `perms`) provably hold // exactly `bytes`? A convergent prior is proven by re-encrypting // and comparing; a randomized one can't be, so it consults the @@ -674,18 +676,19 @@ impl Repo { // fall back to sealing rather than dropping content. None => { sealed_plaintexts.push((path.clone(), bytes.clone())); - to_seal.push((path, bytes, mode, granted)); + to_seal.push((path, bytes, mode, granted, prefix)); } } } None => { sealed_plaintexts.push((path.clone(), bytes.clone())); - to_seal.push((path, bytes, mode, granted)); + to_seal.push((path, bytes, mode, granted, prefix)); } } } - let (protected_all, sealed_wrapped) = crate::protect::encrypt_protected(to_seal)?; + let (protected_all, sealed_wrapped) = + crate::protect::encrypt_protected(to_seal, &self.accepted()?)?; // Record every freshly sealed path's new blob id into the cache; the // committing caller persists it only after the ref actually moves. if let Some(c) = cache { @@ -1784,10 +1787,15 @@ impl Repo { let mut to_encrypt: Vec = Vec::new(); for f in &merge_result.files { if f.needs_encrypt { - let recipients = crate::protect::matching_prefix(&union_prot, &f.path) - .map(|r| r.granted_keys()) + let rule = crate::protect::matching_prefix(&union_prot, &f.path) .ok_or_else(|| Error::NotProtected(f.path.clone()))?; - to_encrypt.push((f.path.clone(), f.bytes.clone(), f.mode, recipients)); + to_encrypt.push(( + f.path.clone(), + f.bytes.clone(), + f.mode, + rule.granted_keys(), + rule.prefix.clone(), + )); } else if f.perms & scl_core::PROTECTED == 0 { match crate::protect::matching_prefix(&union_prot, &f.path) { Some(rule) => to_encrypt.push(( @@ -1795,6 +1803,7 @@ impl Repo { f.bytes.clone(), f.mode, rule.granted_keys(), + rule.prefix.clone(), )), None => carried.push((f.path.clone(), f.bytes.clone(), f.mode, 0)), } @@ -1868,7 +1877,8 @@ impl Repo { return Err(Error::MergeConflicts(merge_result.conflicts.len())); } - let (encrypted, fresh_wrapped) = crate::protect::encrypt_protected(to_encrypt)?; + let (encrypted, fresh_wrapped) = + crate::protect::encrypt_protected(to_encrypt, &self.accepted()?)?; carried.extend(encrypted); let all = carried; @@ -2215,7 +2225,7 @@ impl Repo { &self.layout, &sidecars.iter().map(|(r, _)| r.clone()).collect::>(), )?; - for (path, bytes, mode, _recipients) in to_encrypt { + for (path, bytes, mode, ..) in to_encrypt { let full = worktree::safe_join(&self.layout.root, path)?; worktree::clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { @@ -3049,6 +3059,8 @@ impl Repo { (root, vec![], BTreeMap::new(), Protection::default()) } }; + // The test names these keys, like `protect --to` does. + self.accept_keys(&crate::accepted::path_scope(prefix), recipients)?; protection.prefixes.retain(|p| p.prefix != prefix); protection.prefixes.push(ProtectPrefix { prefix: prefix.to_string(), diff --git a/crates/repo/src/rewrap.rs b/crates/repo/src/rewrap.rs index 02cab7b9..0862595d 100644 --- a/crates/repo/src/rewrap.rs +++ b/crates/repo/src/rewrap.rs @@ -84,6 +84,10 @@ impl Repo { let tip = self.head_tip()?.ok_or(Error::Unborn)?; let snap = self.snapshot(&tip)?; let mut skipped: Vec<(String, String)> = Vec::new(); + // Wraps minted here come from repository data (wrap labels, rules), so + // an entry whose target set holds a key this clone never accepted is + // skipped, not sealed (ADR-0059). The escrow set passed in is local. + let accepted = self.accepted()?.with_escrow(escrows); // ---- Secrets half: fresh-DEK reseal to current set + escrow. ---- let mut registry = snap.secrets.clone(); @@ -134,6 +138,14 @@ impl Repo { continue; } let targets = crate::secrets::append_dedup(targets, escrows); + let pending = accepted.unaccepted(&crate::accepted::secret_scope(&name), &targets); + if !pending.is_empty() { + skipped.push(( + format!("secret {name}"), + crate::accepted::describe_inline(&pending), + )); + continue; + } let value = match scl_crypto::open(&secret, identity) { Ok(v) => v, Err(_) => { @@ -200,6 +212,7 @@ impl Repo { continue; }; let granted = rule.granted_keys(); + let scope = crate::accepted::path_scope(&rule.prefix); if granted.is_empty() { skipped.push(( format!("path {path}"), @@ -242,6 +255,14 @@ impl Repo { target_pks.push(e.clone()); } } + let pending = accepted.unaccepted(&scope, &target_pks); + if !pending.is_empty() { + skipped.push(( + format!("path {path}"), + crate::accepted::describe_inline(&pending), + )); + continue; + } let convergent = perms & scl_core::RANDOMIZED == 0; if convergent || rotate { // Convergent (pre-P33): eager upgrade. Randomized with @@ -722,6 +743,9 @@ mod tests { rule_pk: &scl_crypto::PublicKey, entries: &[(&str, &[u8], &scl_crypto::PublicKey, bool)], ) { + // The test names the rule's key, like `protect --to` does. + repo.accept_keys("path:secret/", std::slice::from_ref(rule_pk)) + .unwrap(); let mut prot = Protection::default(); prot.prefixes.push(ProtectPrefix { prefix: "secret/".into(), diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index ee0a9c75..ae52dc34 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -107,6 +107,8 @@ impl Repo { } check_secret_name(name)?; require_recipients(recipients)?; + // The caller named these keys, so they are accepted for this secret. + self.accept_keys(&crate::accepted::secret_scope(name), recipients)?; let secret = scl_crypto::seal(name, value, recipients); let id = { let arc = self.store_arc(); @@ -155,6 +157,10 @@ impl Repo { _ => return Err(Error::NoSuchSecret(format!("{name} is not a secret"))), } }; + self.accept_keys( + &crate::accepted::secret_scope(name), + std::slice::from_ref(new), + )?; let regranted = scl_crypto::rewrap_for(&secret, authorized, new)?; let new_id = { let arc = self.store_arc(); @@ -213,12 +219,14 @@ impl Repo { i }; reg.insert(name.to_string(), new_id); - self.commit_registry( + let id = self.commit_registry( reg, "secret", &format!("revoke from {name}"), &format!("secret revoke {name}"), - ) + )?; + self.forget_recipient(&crate::accepted::secret_scope(name), recipient)?; + Ok(id) } /// Rotate a secret's value under a **fresh DEK**, re-sealing for `recipients`. @@ -247,6 +255,11 @@ impl Repo { return Err(Error::RebaseInProgress); } require_recipients(recipients)?; + // The set may come from the secret's own wrap labels (repository + // data), so every key must be accepted for it (ADR-0059). A caller + // that named the keys accepts them first (`accept_keys`). + self.accepted()? + .require(&crate::accepted::secret_scope(name), recipients)?; let mut reg = self.registry()?; let sid = *reg .get(name) @@ -1384,6 +1397,8 @@ mod tests { let (sk, pk) = scl_crypto::generate_keypair(); let repo = Repo::init(&root).unwrap(); plant(&repo, "A", "B", b"value-of-b", &pk); + repo.accept_keys("secret:A", std::slice::from_ref(&pk)) + .unwrap(); let err = repo .secret_rotate("A", None, std::slice::from_ref(&pk), Some(&sk)) .unwrap_err(); From 40b879407c7f315ac37cde5ba1e3c663e50c4a8c Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:57:36 +0200 Subject: [PATCH 02/10] feat(cli): add sc policy accept and forget sc policy accept --key [,...] records recipients in the local .sc/accepted-recipients; a key in neither [recipients] nor [escrow] needs --allow-unknown. sc policy forget removes one. Both touch only the local file, so they work while a merge, pick or rebase is stopped and a refused completion can be retried. sc secret rotate --to accepts the keys it names, since the library cannot tell a named set from one derived from the secret's own wrap labels. The rewrap hint now mentions the accept route for skipped entries. Refs ADR-0059. --- .claude/skills/sc-cli-reference/SKILL.md | 6 + crates/cli/src/main.rs | 104 +++++++++- crates/cli/tests/policy_accept.rs | 243 +++++++++++++++++++++++ 3 files changed, 351 insertions(+), 2 deletions(-) create mode 100644 crates/cli/tests/policy_accept.rs diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 998d11fe..3b0123a6 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -147,6 +147,12 @@ cargo run --bin sc -- rewrap [--identity ] [--dry-run] [--rotate] # one-c cargo run --bin sc -- escrow add # append a break-glass key (list) cargo run --bin sc -- escrow remove cargo run --bin sc -- escrow show # lists all escrow keys +cargo run --bin sc -- policy accept --key [,...] [--allow-unknown] + # accept recipients for path:, secret: or + # branch: (local .sc/accepted-recipients; a seal + # refuses a key you never accepted, ADR-0059; works + # while a merge/pick/rebase is stopped) +cargo run --bin sc -- policy forget # stop accepting one bash demo/run_rewrap_demo.sh # bulk rewrap + escrow-list proof bash demo/run_randomized_demo.sh # randomized protected-encryption proof # (P33): same plaintext → different ciphertext ids diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 1544cf20..d0d08267 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -518,6 +518,13 @@ enum Cmd { #[command(subcommand)] op: EscrowOp, }, + /// Manage which recipients this clone has accepted (local, never + /// transferred): a seal refuses to wrap to a key a rule, secret or private + /// branch lists but you never accepted for it. + Policy { + #[command(subcommand)] + op: PolicyOp, + }, /// Re-seal every secret and protected file's wrap list at the tip to the /// current recipient + escrow sets, in one undoable commit. Rewrap { @@ -737,6 +744,29 @@ enum EscrowOp { Show, } +#[derive(Subcommand)] +enum PolicyOp { + /// Accept recipients for a scope: `path:`, `secret:` or + /// `branch:`. Allowed while a merge, pick or rebase is stopped. + Accept { + /// The scope the keys are accepted for. + scope: String, + /// Public keys (`scl-pk-...`) or recipient ids to accept. + #[arg(long, required = true, value_delimiter = ',')] + key: Vec, + /// Accept a key that is in neither `[recipients]` nor `[escrow]`. + #[arg(long)] + allow_unknown: bool, + }, + /// Stop accepting a recipient for a scope. + Forget { + /// The scope the key was accepted for. + scope: String, + /// Public key (`scl-pk-...`) or recipient id. + key: String, + }, +} + #[derive(Subcommand)] enum WsOp { /// Fork N durable workspaces from HEAD under `.sc/ws//` (or, with @@ -1276,6 +1306,7 @@ fn real_main() -> Result<()> { include_encrypted, } => run_export(to, r#ref, include_encrypted), Cmd::Escrow { op } => run_escrow(op), + Cmd::Policy { op } => run_policy(op), Cmd::Rewrap { identity, dry_run, @@ -3316,7 +3347,13 @@ fn run_secret(op: SecretOp) -> Result<()> { pool.extend(escrows.iter().cloned()); resolve_ids_to_pubkeys(&ids, &pool)? } else { - resolve_names(&dir, &to)? + // Named on the command line, so accepted for this secret. The + // derived set above is not: it comes from the secret's own + // wrap labels, and `secret_rotate` refuses one with a key + // this clone never accepted. + let named = resolve_names(&dir, &to)?; + repo.accept_keys(&format!("secret:{name}"), &named)?; + named }; let pks = append_escrow(pks, &escrows); let new_value = value.as_deref().map(|s| s.as_bytes()); @@ -3336,6 +3373,66 @@ fn run_secret(op: SecretOp) -> Result<()> { Ok(()) } +/// A `--key` argument: a `scl-pk-...` public key or a 32-hex recipient id, as +/// the id plus the key when the argument was one. +fn parse_recipient_ref( + s: &str, +) -> Result<(scl_crypto::RecipientId, Option)> { + match scl_crypto::PublicKey::from_key_string(s) { + Ok(pk) => Ok((pk.recipient_id(), Some(pk))), + Err(_) => scl_crypto::RecipientId::from_hex(s) + .map(|id| (id, None)) + .map_err(|_| { + anyhow::anyhow!("'{s}' is neither a scl-pk- public key nor a recipient id") + }), + } +} + +/// `sc policy accept/forget`: the local record of accepted recipients +/// (ADR-0059). Touches only `.sc/accepted-recipients`, so it works while a +/// merge, pick or rebase is stopped. +fn run_policy(op: PolicyOp) -> Result<()> { + let repo = open_repo()?; + match op { + PolicyOp::Accept { + scope, + key, + allow_unknown, + } => { + let path = repo.layout().dot_sc.join("recipients.toml"); + let mut known: Vec = load_recipients(&path) + .map(|m| m.into_values().collect()) + .unwrap_or_default(); + known.extend(load_escrows(&path).unwrap_or_default()); + let mut resolved = Vec::new(); + for k in &key { + let (id, given) = parse_recipient_ref(k)?; + let local = known.iter().find(|pk| pk.recipient_id() == id).cloned(); + if local.is_none() && !allow_unknown { + anyhow::bail!( + "{id} is in neither [recipients] nor [escrow] of .sc/recipients.toml; \ + check whose key it is, then pass --allow-unknown to accept it anyway" + ); + } + resolved.push((id, given.or(local))); + } + for (id, pk) in &resolved { + repo.accept_recipient(&scope, id, pk.as_ref())?; + } + println!("accepted {} recipient(s) for {scope}", resolved.len()); + } + PolicyOp::Forget { scope, key } => { + let (id, _) = parse_recipient_ref(&key)?; + if repo.forget_recipient(&scope, &id)? { + println!("forgot {id} for {scope}"); + } else { + println!("{id} was not accepted for {scope}"); + } + } + } + Ok(()) +} + /// `sc escrow set/add/remove/show`: manage the break-glass escrow recipient /// keys in `.sc/recipients.toml`. Config only — auto-including the escrow /// keys at seal/protect time is a separate concern. @@ -4923,7 +5020,10 @@ fn run_rewrap(identity: Option, dry_run: bool, rotate: bool) -> Result< } else { "sc rewrap" }; - eprintln!("re-run `{again}` with an identity that can open them to complete the sweep"); + eprintln!( + "re-run `{again}` to complete the sweep: with an identity that can open them, \ + or after `sc policy accept` for the recipients listed as not accepted" + ); } eprintln!( "note: rewrap cuts the live tip only — snapshots already in history keep \ diff --git a/crates/cli/tests/policy_accept.rs b/crates/cli/tests/policy_accept.rs new file mode 100644 index 00000000..38a4706e --- /dev/null +++ b/crates/cli/tests/policy_accept.rs @@ -0,0 +1,243 @@ +//! ADR-0059: `sc policy accept|forget` and the refusals they answer. + +use std::path::Path; +use std::process::Command; + +fn sc(dir: &Path, args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_sc")) + .args(args) + .current_dir(dir) + .output() + .expect("sc runs") +} + +fn stderr(out: &std::process::Output) -> String { + String::from_utf8_lossy(&out.stderr).to_string() +} + +fn tmp(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("scl-cli-policy-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// keygen an identity, returning (identity file, public key string). +fn keygen(dir: &Path, name: &str) -> (std::path::PathBuf, String) { + let idfile = dir.join(format!("{name}.id")); + let out = sc(dir, &["keygen", "--out", idfile.to_str().unwrap()]); + assert!(out.status.success(), "keygen: {}", stderr(&out)); + let text = String::from_utf8_lossy(&out.stdout).to_string(); + let pk = text + .lines() + .find(|l| l.contains("public key")) + .and_then(|l| l.split_whitespace().find(|w| w.starts_with("scl-pk-"))) + .expect("public key in keygen output") + .to_string(); + (idfile, pk) +} + +fn record(repo: &Path) -> String { + std::fs::read_to_string(repo.join(".sc/accepted-recipients")).unwrap_or_default() +} + +#[test] +fn accept_checks_the_key_is_known_and_forget_removes_it() { + let root = tmp("accept"); + let keys = tmp("accept-keys"); + let (_, alice_pk) = keygen(&keys, "alice"); + let (_, stranger_pk) = keygen(&keys, "stranger"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write( + root.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{alice_pk}\"\n"), + ) + .unwrap(); + + // A key from the local recipients file is accepted as is. + let out = sc(&root, &["policy", "accept", "secret:X", "--key", &alice_pk]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(record(&root).starts_with("secret:X\t"), "{}", record(&root)); + + // One the clone has never heard of needs the explicit flag. + let out = sc( + &root, + &["policy", "accept", "path:a/", "--key", &stranger_pk], + ); + assert!(!out.status.success()); + assert!(stderr(&out).contains("--allow-unknown"), "{}", stderr(&out)); + assert!(!record(&root).contains("path:a/")); + let out = sc( + &root, + &[ + "policy", + "accept", + "path:a/", + "--key", + &stranger_pk, + "--allow-unknown", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(record(&root).contains("path:a/\t")); + + // A scope has a kind. + let out = sc(&root, &["policy", "accept", "a/", "--key", &alice_pk]); + assert!(!out.status.success()); + + let out = sc(&root, &["policy", "forget", "path:a/", &stranger_pk]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(!record(&root).contains("path:a/")); + assert!(record(&root).contains("secret:X\t"), "other pairs stay"); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +#[test] +fn accept_works_while_a_merge_is_stopped() { + let root = tmp("stopped"); + let keys = tmp("stopped-keys"); + let (_, pk) = keygen(&keys, "k"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write(root.join("file.txt"), "base\n").unwrap(); + assert!(sc(&root, &["commit", "-m", "base"]).status.success()); + assert!(sc(&root, &["branch", "feature"]).status.success()); + std::fs::write(root.join("file.txt"), "ours\n").unwrap(); + assert!(sc(&root, &["commit", "-m", "ours"]).status.success()); + assert!(sc(&root, &["switch", "feature"]).status.success()); + std::fs::write(root.join("file.txt"), "theirs\n").unwrap(); + assert!(sc(&root, &["commit", "-m", "theirs"]).status.success()); + assert!(sc(&root, &["switch", "main"]).status.success()); + assert_eq!(sc(&root, &["merge", "feature"]).status.code(), Some(1)); + + let out = sc( + &root, + &[ + "policy", + "accept", + "path:docs/", + "--key", + &pk, + "--allow-unknown", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(record(&root).contains("path:docs/\t")); + let out = sc(&root, &["policy", "forget", "path:docs/", &pk]); + assert!(out.status.success(), "{}", stderr(&out)); + // The stop is still there. + assert!(String::from_utf8_lossy(&sc(&root, &["conflicts"]).stdout).contains("file.txt")); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A repo with `alice` in recipients.toml, `secret/` protected for her and a +/// secret `DB` added for her, and a fresh clone of it with the same +/// recipients file (the record is never copied). +fn origin_and_clone(tag: &str) -> (std::path::PathBuf, std::path::PathBuf, String, String) { + let root = tmp(tag); + // Keys live beside the working trees, not in them (the scanner flags them). + let keys = root.join("keys"); + std::fs::create_dir_all(&keys).unwrap(); + let (alice_id, alice_pk) = keygen(&keys, "alice"); + let a = root.join("a"); + std::fs::create_dir_all(&a).unwrap(); + assert!(sc(&a, &["init"]).status.success()); + let toml = format!("[recipients]\nalice = \"{alice_pk}\"\n"); + std::fs::write(a.join(".sc/recipients.toml"), &toml).unwrap(); + std::fs::create_dir_all(a.join("secret")).unwrap(); + std::fs::write(a.join("secret/a.txt"), "data\n").unwrap(); + let out = sc(&a, &["protect", "secret/", "--to", "alice"]); + assert!(out.status.success(), "{}", stderr(&out)); + let out = sc( + &a, + &["secret", "add", "DB", "--to", "alice", "--value", "v0"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + // The origin never needed an accept: it named alice itself. + let out = sc( + &a, + &[ + "secret", + "rotate", + "DB", + "--identity", + alice_id.to_str().unwrap(), + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + + let b = root.join("b"); + let out = sc(&root, &["clone", a.to_str().unwrap(), b.to_str().unwrap()]); + assert!(out.status.success(), "{}", stderr(&out)); + std::fs::write(b.join(".sc/recipients.toml"), &toml).unwrap(); + assert!(!b.join(".sc/accepted-recipients").exists()); + (root, b, alice_pk, alice_id.to_str().unwrap().to_string()) +} + +#[test] +fn a_fresh_clone_refuses_a_rule_seal_until_the_key_is_accepted() { + let (root, b, alice_pk, _) = origin_and_clone("clone-commit"); + std::fs::create_dir_all(b.join("secret")).unwrap(); + std::fs::write(b.join("secret/b.txt"), "more\n").unwrap(); + + let out = sc(&b, &["commit", "-m", "seal"]); + assert!(!out.status.success()); + let err = stderr(&out); + for want in [ + "path:secret/ grants a recipient you have not accepted", + "(alice)", + "sc policy accept path:secret/ --key", + "sc revoke secret/ --recipient-id", + "Nothing was written.", + ] { + assert!(err.contains(want), "missing {want:?} in: {err}"); + } + + let out = sc( + &b, + &["policy", "accept", "path:secret/", "--key", &alice_pk], + ); + assert!(out.status.success(), "{}", stderr(&out)); + let out = sc(&b, &["commit", "-m", "seal"]); + assert!(out.status.success(), "{}", stderr(&out)); + std::fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn a_fresh_clone_refuses_a_default_secret_rotate_until_accepted() { + let (root, b, alice_pk, alice_id) = origin_and_clone("clone-rotate"); + let rotate = |dir: &Path| sc(dir, &["secret", "rotate", "DB", "--identity", &alice_id]); + + let out = rotate(&b); + assert!(!out.status.success()); + let err = stderr(&out); + assert!( + err.contains("secret:DB grants a recipient you have not accepted") + && err.contains("sc policy accept secret:DB --key") + && err.contains("sc secret revoke DB --recipient-id"), + "{err}" + ); + + // Naming the key on the command line accepts it, like add does. + let out = sc( + &b, + &[ + "secret", + "rotate", + "DB", + "--to", + "alice", + "--identity", + &alice_id, + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(record(&b).contains("secret:DB\t")); + assert!(rotate(&b).status.success(), "default set now accepted"); + + let _ = alice_pk; + std::fs::remove_dir_all(&root).unwrap(); +} From 407a240f96eabc59ba8db5dc585abf37b2d21a3b Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 11:57:36 +0200 Subject: [PATCH 03/10] docs: ADR-0059 locally accepted recipients Records the problem, the local accepted-recipients record, the gate sites, the auto-accept rule, the migration, the alternatives rejected (seal only to recipients.toml; signed policy) and the deferred items and residual risks. Adds the matching THREAT-MODEL entries (Protected paths, with one line each under Committed secrets and Private branches), a CLAUDE.md standing-boundary bullet, the ADR index row, and status pointers on ADR-0025 and ADR-0027. --- CLAUDE.md | 15 ++ ROADMAP.md | 10 + docs/THREAT-MODEL.md | 44 ++++- docs/adr/0025-protected-merge-and-replay.md | 2 +- docs/adr/0027-bulk-rewrap-and-multi-escrow.md | 2 +- docs/adr/0059-locally-accepted-recipients.md | 175 ++++++++++++++++++ docs/adr/README.md | 5 +- 7 files changed, 248 insertions(+), 5 deletions(-) create mode 100644 docs/adr/0059-locally-accepted-recipients.md diff --git a/CLAUDE.md b/CLAUDE.md index 96e547e7..94b89a0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -260,6 +260,21 @@ transport-adjacent. The rest, imperatively: `sc keygen` identity and the TLS serve key use the same primitive (#281); `tlsio` is a leaf, so `load_or_mint` takes the creator from `repo` (`load_or_mint_serve_identity`) and never calls core. `windows-sys` and the sole Windows `unsafe` live in `scl-core` only. +- **A seal wraps only to recipients this clone accepted (ADR-0059).** Rules, + secret wrap labels and private-branch KEK labels are repository data, so + `.sc/accepted-recipients` (local like `.sc/local-key`: atomic write under the + repo lock, never committed, packed or transferred, ignored by gc; ws/work use + the host's) lists the keys accepted per scope (full key for `path:`, + id for `secret:` and `branch:`; local `[escrow]` counts everywhere). + `protect::encrypt_protected` (commit, merge, replay, publish), `sc protect` + (before either of its ref moves), `secret_rotate`, `rewrap` (skip, non-zero exit) + and `branch_revoke` refuse before writing when a key is not accepted; a carry + that copies existing wraps is not a seal. Only keys named on the command line + auto-accept (`protect --to`, `grant`, `secret add|grant|rotate`, `branch + --private --to|grant`); the record starts empty per clone; `sc policy + accept|forget` work while a merge/pick/rebase is stopped. A new seal site must + go through the gate. A test or demo that seals in a clone to a key it did not + name accepts it first. - **Revoke is standing-only.** A revoked recipient keeps decrypting ciphertext sealed before the revoke (they hold the old wraps); cryptographic cutover is `sc rewrap --rotate` at the tip (fresh key per protected blob; a plain diff --git a/ROADMAP.md b/ROADMAP.md index ad4a04bb..31c315c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -946,6 +946,16 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in fetch-time freshness attestation so a hostile remote can't re-serve a stale pre-revoke manifest — the same gittuf-shaped signed-ref effort the P22 provenance boundary already defers. +- **Accepted-recipient follow-ons (ADR-0059).** Deferred rather than built: + (1) binding protected ciphertext to its path (a format change), so a file + relocated under an accepted prefix cannot gain recipients through that + prefix's rewrap; (2) pinning the private-branch KEK generation, since `sc undo` + can restore a pre-revoke manifest and reuse a retired KEK; (3) + authenticating the secret registry, since a writer can replace a value under + an allowed name (`sc verify --require` before `sc run` is the mitigation); + (4) `sc policy status` and `sc policy accept --all`; (5) a refused `sc work` + harvest discards the agent's checkout with the session (a preflight that + refuses to start would avoid it). - **Leases (P36a follow-on).** The only cross-writer coordination today is the manifest's compare-and-swap; there is no lease/TTL primitive for operations that need to hold exclusive intent across more than one bucket diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index dfa79c43..a335234d 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -54,7 +54,9 @@ too, not just the src-control-side metadata. first), and before decrypting anything. An entry whose name fails the rule (planted, or added by an older CLI that took any name such as `db-pass`) is skipped with a stderr warning, never opened and never injected, in strict and - non-strict mode alike. An entry whose key differs from the `name` the secret + non-strict mode alike. A wrap label is repository data too: `sc secret rotate` + without `--to` and `sc rewrap` seal only to recipients accepted for + `secret:` in this clone (ADR-0059, see Protected paths). An entry whose key differs from the `name` the secret was sealed under (the AEAD binds that name) refuses the whole run, and `sc secret rotate` without `--value` refuses it too (`--value` re-seals it afresh). **Residual:** a writer can still replace the value of an allowed name @@ -120,6 +122,41 @@ too, not just the src-control-side metadata. `sc protect`, or, while a merge, pick or rebase is stopped, to abort it, restore the rule and retry. Case aliases of the other parent's protected paths are not checked. +- **A seal wraps only to recipients you accepted (ADR-0059):** protection rules, + secret wrap lists and private-branch KEK wrap labels are repository data, so a + writer with no key could add a rule (or a narrower one under your prefix) + granting their key and wait for your next commit, merge or replay reseal, + `sc rewrap`, `sc secret rotate` without `--to` or `sc branch revoke` to wrap a + DEK to them. `.sc/accepted-recipients` (local; written atomically under the + repo lock; never committed, packed, transferred or read by gc; `sc ws` and + `sc work` use the host's) lists what you accepted per scope: the full public + key for `path:`, the recipient id for `secret:` and + `branch:`; local `[escrow]` keys count in every scope. The gate is + `encrypt_protected`, the one function that turns a rule into wraps, plus + `sc protect` (it checks the rule it changes and builds its sealing commit + before either ref moves), `secret_rotate`, `rewrap` (an entry with an + unaccepted key is skipped, the rest commits, the exit code is non-zero) and + `branch_revoke`. A carry that copies + existing wraps is not a seal and is not gated. A refusal writes nothing and + names the scope, the id, the local `[recipients]` name or `UNKNOWN`, the + `sc policy accept` command and the revoke command. Only keys you name on the + command line are accepted automatically (`sc protect --to`, `sc grant`, + `sc secret add|grant|rotate`, `sc branch --private --to`, `sc branch grant`); + a key found in the data never is, and a key listed in `recipients.toml` is + still not accepted. `sc policy accept|forget` edit the file and work while a + merge, pick or rebase is stopped. The record starts empty in every clone (not + seeded from the tip, which would accept what an attacker merged), so the first + affected seal lists the pairs and refuses; CI provisions the file from trusted + configuration. **Residual:** any writer can still make your seals refuse by + adding keys (denial of service); history already sealed to a writer's key + stays readable; binaries from before ADR-0059 do not enforce it; protected + ciphertext is not bound to its path, so a file relocated under an accepted + prefix can gain recipients through that prefix's rewrap (a format change, + deferred). A spurious reseal of unchanged content (a lost cache) is a seal and + refuses like any other. The printed revoke command can itself refuse (`sc revoke` + will not remove a rule's last recipient, and will not run while a merge, pick or + rebase is stopped), and a refused `sc work` harvest discards that agent's + temporary checkout with the session; accept first, or use `sc ws`. - **Local cache key, `sc keygen` identity and TLS serve key are owner-only on unix and Windows (P33, #214, #281):** the unchanged-detection cache is keyed by `.sc/local-key`, created owner-only from @@ -192,6 +229,11 @@ too, not just the src-control-side metadata. keeps the old manifest reachable in any clone that has it). The rotation guarantees they can read nothing sealed *after*. Real cutover of already- disclosed content also means rotating the underlying credential. +- **A KEK wrap label is repository data:** `sc branch revoke` rewraps the fresh + KEK only to keys accepted for `branch:` in this clone (ADR-0059, see + Protected paths); `sc branch grant` and the creator's key accept themselves. + The KEK generation is not pinned, so `sc undo` can restore a pre-revoke + manifest and reuse a retired KEK (deferred). - **Escrow holders can read pre-publish:** the branch KEK is wrapped to the configured escrow set at creation (and re-wrapped on every membership change), so break-glass holders can open an embargoed branch — the standing diff --git a/docs/adr/0025-protected-merge-and-replay.md b/docs/adr/0025-protected-merge-and-replay.md index a2e1cb56..59fcc379 100644 --- a/docs/adr/0025-protected-merge-and-replay.md +++ b/docs/adr/0025-protected-merge-and-replay.md @@ -1,6 +1,6 @@ # ADR-0025: Protected merge & replay — perms-aware three-way with decrypt-on-demand -- **Status:** Accepted +- **Status:** Accepted; a reseal under a union rule wraps only to recipients the clone accepted, by [ADR-0059](0059-locally-accepted-recipients.md) - **Date:** 2026-07-06 - **Phase:** 15 - **Builds on:** ADR-0012 (three-way merge), ADR-0014 (encrypted paths), diff --git a/docs/adr/0027-bulk-rewrap-and-multi-escrow.md b/docs/adr/0027-bulk-rewrap-and-multi-escrow.md index de4b0c97..c11e4f81 100644 --- a/docs/adr/0027-bulk-rewrap-and-multi-escrow.md +++ b/docs/adr/0027-bulk-rewrap-and-multi-escrow.md @@ -1,6 +1,6 @@ # ADR-0027: Bulk re-wrap and multiple escrow keys -- **Status:** Accepted +- **Status:** Accepted; an entry whose target set holds a key the clone never accepted is skipped, by [ADR-0059](0059-locally-accepted-recipients.md) - **Date:** 2026-07-07 - **Phase:** 17 - **Builds on:** ADR-0019 (secret lifecycle), ADR-0009 (key management), ADR-0026 (revocation tombstones) diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md new file mode 100644 index 00000000..e569ec12 --- /dev/null +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -0,0 +1,175 @@ +# ADR-0059: Locally accepted recipients + +- **Status:** Accepted +- **Date:** 2026-11-20 +- **Phase:** security hardening (post-P38) +- **Amends:** ADR-0025 (protected merge and replay: rules merge by union, and + the union decides who a reseal wraps to), ADR-0027 (bulk rewrap: the target + set is the rule plus escrow, or the secret's wrap labels plus escrow) +- **Builds on:** ADR-0008/0009 (secrets), ADR-0014 (protected paths), ADR-0019 + (rotation), ADR-0044 (private branches) + +## Context + +Three pieces of repository data decide whose key a seal wraps a DEK to, and a +writer needs no key to change any of them: + +- **Protection rules** (`Protection.prefixes`). A writer can add a rule, or a + narrower one under an existing prefix, granting their own key. +- **Secret wrap lists.** `Secret.wrapped_keys` labels are recipient ids with no + proof attached. `sc secret rotate` without `--to` and `sc rewrap` resolve + those labels back to keys and re-seal to the result. +- **Private-branch KEK wrap labels.** `BranchManifest.kek_wraps` is read the + same way by `sc branch revoke`. + +The victim then does something ordinary: fast-forwards, edits a file under the +new rule, commits. The commit seals the file and wraps its DEK to the writer. +The same happens through a clean merge or a replay that reseals a carried +plain file under a union rule (ADR-0025), a conflict completion, `sc rewrap`, +`sc secret rotate` and `sc branch revoke`. Nothing on the victim's side marks +the key as foreign, and signed commits do not help: the rule travels inside a +commit the victim has every reason to merge. + +The fix must put the decision where a key is actually wrapped, must not need +the writer's cooperation, and must not turn every ordinary commit into a +prompt. + +## Decision + +### The record + +`.sc/accepted-recipients` lists the keys **this clone** accepted, one +`\t` line each. A scope is `path:` (the winning rule's own +prefix string), `secret:` or `branch:`. A `path:` line holds the +full public key (`scl-pk-...`), since a rule holds full keys; `secret:` and +`branch:` lines hold the recipient id, since a wrap label is an id. Scope text +is escaped (`%`, tab, newline, carriage return) because a path prefix can hold +any byte but NUL. Local `[escrow]` keys from `.sc/recipients.toml` count as +accepted in every scope. + +It is local state like `.sc/local-key`: written atomically (temp file and +rename) by a command that holds the repo lock, never part of a snapshot, never +in a pack, never sent by clone, fetch or push, and not read by `sc gc`. `sc ws` +and `sc work` commit through the host repo, so they use the host's record. + +### The gate + +A seal refuses, before anything is written, when a key it would wrap to is +neither accepted for the seal's scope nor escrow. The error names every +unaccepted pair: the scope, the recipient id, the local `[recipients]` name or +`UNKNOWN`, the `sc policy accept` command (with `--allow-unknown` for an +unknown key; a `path:` scope shows the full key to pass) and the command that +removes the key from the data: + +``` +path:secret/sub/ grants a recipient you have not accepted: 3f9a... (UNKNOWN). + Accept: sc policy accept path:secret/sub/ --key scl-pk-... --allow-unknown + Remove: sc revoke secret/sub/ --recipient-id 3f9a... +Nothing was written. +``` + +Remove is `sc revoke --recipient-id `, `sc secret revoke +--recipient-id ` or `sc branch revoke --recipient-id +--identity `. + +The gate sits where wraps are minted, after the carry-or-seal decision, so a +carry that copies existing wraps is never gated: + +| Site | Scope | Behavior | +|---|---|---| +| `protect::encrypt_protected`, the one function that turns a rule's recipients into wraps | `path:` | refuses the whole call, naming every pair | +| callers: `snapshot_files` (commit, amend, merge/pick/rebase completion, `sc ws harvest`, `sc work`, `ws refresh`), the clean merge, `replay_commit` (cherry-pick, rebase), `branch_publish` (private-branch protected files) | | inherit it | +| `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit before either ref moves (it advanced the ref before its sealing commit), so a refusal under any rule leaves ref and oplog alone | +| `secret_rotate` | `secret:` | refuses on the final recipient set | +| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report) | +| `branch_revoke` | `branch:` | refuses on the remaining set | + +A conflict stop writes plaintext and seals nothing, so it is not gated; its +completion commit is. + +### Auto-accept + +Only keys the user names on the command line are accepted without asking: +`sc protect --to`, `sc grant`, `sc secret add`, `sc secret grant`, +`sc secret rotate --to`, `sc branch --private --to` (and the creator's own +key) and `sc branch grant`. The library functions behind them record the keys +they were given; `sc secret rotate --to` does it from the CLI because the +library cannot tell a named set from one derived from wrap labels. A key that +comes from repository data, by any route, is never auto-accepted. The local +revoke commands remove the pair they revoke. + +### Commands + +`sc policy accept --key [,...] [--allow-unknown]` records +pairs. A key in neither `[recipients]` nor `[escrow]` needs `--allow-unknown`, +so accepting a key you cannot identify takes a flag you typed. A `path:` scope +needs the full key: pass the `scl-pk-` string, or an id that resolves through +`[recipients]` or `[escrow]`. +`sc policy forget ` removes one. Both touch only the local file, +so both work while a merge, pick or rebase is stopped, and a refused +completion can be retried after an accept. + +### Migration + +The record starts empty and is not seeded from the tip: seeding would accept +exactly what an attacker already merged. The first seal in each clone that +reaches a key lists the pairs and refuses; the cost is one `sc policy accept` +per scope per clone, then silence. CI provisions the file from trusted +configuration. No snapshot encoding or wire change, and `PROTOCOL_VERSION` +stays 6. + +## Consequences + +- A writer without a key can no longer get a wrap by editing rules, wrap + labels or manifests. They can still make a victim's seals refuse (below). +- A spurious reseal (a lost protected-path cache, ADR-0043) of unchanged + content under a rule with an unaccepted key refuses too: the gate sees a + seal, not a change. +- Accepting is a trust decision about a key, per scope and per clone. The + error is the review prompt; `UNKNOWN` and the `--allow-unknown` flag mark + the ones the user has no record of. +- Binaries from before this ADR do not enforce it. History already sealed to a + writer's key stays readable by them (rotation is not erasure). + +## Alternatives considered + +- **Seal only to `.sc/recipients.toml`.** A rule would grant nothing the local + file does not already list. Rejected: `recipients.toml` is a name directory + of everyone the clone has ever wanted to talk to, not a per-scope decision, + and a key listed there for one prefix would become valid for every rule and + every secret. It also cannot express "this key for `secret/prod/` only". + (A key in `recipients.toml` is still not accepted: test 2 pins that.) +- **Signed policy.** Rules and wrap labels authenticated by a trusted signer + set. Rejected for now: it needs a trust root and key distribution that + `sc` does not have for recipients (ADR-0032 signs snapshots, not policy), a + format change to carry the signature, and it still leaves a trusted signer's + mistake or compromise as a path to a wrap. A signed policy could later + *supply* the accepted set; it would not remove the gate. +- **Gate at merge, not at seal.** Refuse a merge that brings in a new key. + Rejected: a fast-forward brings the rule in without a merge, and a carried + key that is never sealed to is harmless; the seal is the moment a key gets a + DEK. +- **Seed the record from the tip on first use.** Rejected (see Migration). + +## Deferred and residual risks + +- **Protected ciphertext is not bound to its path.** Binding it is a format + change. Until then a file relocated under an accepted prefix can gain + recipients through that prefix's rewrap. +- **The private-branch KEK generation is not pinned.** `sc undo` can restore a + pre-revoke manifest and so reuse a retired KEK. +- **A value can be replaced under an allowed secret name.** The registry is not + authenticated; `sc verify --require` before `sc run` is the mitigation + (THREAT-MODEL). +- **Denial of service.** Any writer can make a victim's seals refuse by adding + keys; the cure is to revoke or accept, never silent. +- **`sc policy status` and `--all`** (list the record, accept every pending + pair) are not built. +- **The printed Remove command does not always work.** `sc revoke` refuses to + revoke a rule's last recipient (the attacker's own narrower rule: run + `sc grant --to ` first) and refuses while a merge, pick or + rebase is stopped (accept, or abort the operation). A writer with a higher + epoch can add the key back after a revoke. +- **`sc work` discards a refused agent's work.** Its harvest error is reported + per workspace, but the temporary checkouts go with the session. Accept the + keys first (`sc policy accept`); `sc ws` workspaces persist and can retry. diff --git a/docs/adr/README.md b/docs/adr/README.md index 1c2b57c7..1845de69 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -35,9 +35,9 @@ supersedes the old one and update the **Status** line of the superseded record. | [0022](0022-ssh-native-transport.md) | sc-native network transport over SSH (trait-mirror wire protocol) | Accepted | 12 | | [0023](0023-agent-workspaces.md) | Agent workspaces — vfs-backed sessions over the persistent store | Accepted | 13 | | [0024](0024-history-editing.md) | History editing via replay + operation log | Accepted | 14 | -| [0025](0025-protected-merge-and-replay.md) | Protected merge & replay — perms-aware three-way with decrypt-on-demand | Accepted | 15 | +| [0025](0025-protected-merge-and-replay.md) | Protected merge & replay — perms-aware three-way with decrypt-on-demand | Accepted; reseal recipients gated by 0059 | 15 | | [0026](0026-revocation-tombstones.md) | Revocation tombstones — durable prefix-rule revocation | Accepted | 16 | -| [0027](0027-bulk-rewrap-and-multi-escrow.md) | Bulk re-wrap and multiple escrow keys | Accepted | 17 | +| [0027](0027-bulk-rewrap-and-multi-escrow.md) | Bulk re-wrap and multiple escrow keys | Accepted; unaccepted targets skipped by 0059 | 17 | | [0028](0028-network-git-remotes.md) | Network Git remotes (GitHub over https/ssh) | Accepted | 18 | | [0029](0029-history-editing-polish.md) | History-editing polish — amend, resumable rebase, pick abort, merge replay | Accepted | 19 | | [0030](0030-agent-sessions-and-automerge.md) | Agent sessions and auto-merge of clean results | Accepted; one-session rule superseded by 0056 | 20 | @@ -69,6 +69,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0056](0056-named-concurrent-ws-sessions.md) | Named and concurrent `sc ws` sessions and `sc ws refresh` | Accepted (built, including `sc ws refresh`) | 20 | | [0057](0057-bucket-compaction.md) | Bucket remote compaction and gc (`sc remote compact`) | Accepted | 36 | | [0058](0058-sc-forge-gitea-compatible-git-forge.md) | sc-forge: a Gitea-compatible Git forge (bare Git, recorded API subset) | Proposed | 38 | +| [0059](0059-locally-accepted-recipients.md) | Locally accepted recipients: a seal wraps only to keys this clone accepted (`sc policy`) | Accepted | hardening | See [`ROADMAP.md`](../../ROADMAP.md) for the phase sequence. ADR numbers are assigned in creation order, so 0017 — the secret scanner — sequences as phase P5, From 3721a0f92f21dcff1589b1cd3e983c1dc727d4ac Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:31:46 +0200 Subject: [PATCH 04/10] fix(repo): harden accepted-recipient bookkeeping after review Escrow keys are no longer recorded as approvals. protect and secret add persist only the keys the user named (the library drops the keys currently in [escrow] from what it records, the CLI records the named ones), and private branch creation records the creator and the named recipients only, so removing a key from [escrow] withdraws its acceptance. The three local revokes drop the approval after validation and before the new ref is published, so an interruption cannot leave an approval outliving a landed revoke. sc policy accept validates the whole batch and writes the record once; a path: scope with an id that has no key behind it is an error even with --allow-unknown. Refusal messages escape every repository-controlled field with sanitize_display_line and print no command for a scope with control characters. A Remove target that starts with "-" is written flags first and after "--". The shared seal path loads the record only when something is sealed, and rewrap loads it at the first entry that wraps anything, so a commit that wraps nothing no longer depends on the record being readable. The ADR notes that the record's integrity depends on the working-tree path guard. --- crates/cli/src/main.rs | 25 +- crates/cli/tests/policy_accept.rs | 121 ++++++ crates/repo/src/accepted.rs | 407 ++++++++++++++++--- crates/repo/src/private.rs | 13 +- crates/repo/src/protect.rs | 18 +- crates/repo/src/protect_ops.rs | 7 +- crates/repo/src/replay.rs | 2 +- crates/repo/src/repo.rs | 4 +- crates/repo/src/rewrap.rs | 22 +- crates/repo/src/secrets.rs | 13 +- docs/THREAT-MODEL.md | 8 +- docs/adr/0059-locally-accepted-recipients.md | 37 +- 12 files changed, 587 insertions(+), 90 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index d0d08267..b5f5ae84 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -754,7 +754,9 @@ enum PolicyOp { /// Public keys (`scl-pk-...`) or recipient ids to accept. #[arg(long, required = true, value_delimiter = ',')] key: Vec, - /// Accept a key that is in neither `[recipients]` nor `[escrow]`. + /// Accept a key that is in neither `[recipients]` nor `[escrow]`. A + /// `path:` scope records full keys, so it still needs the `scl-pk-` + /// key: an id that does not resolve to one is an error. #[arg(long)] allow_unknown: bool, }, @@ -3289,10 +3291,14 @@ fn run_secret(op: SecretOp) -> Result<()> { None => read_value_from_stdin()?, }; let dir = load_recipients(&recipients_path)?; - let mut pks = resolve_names(&dir, &to)?; + let named = resolve_names(&dir, &to)?; let escrows = load_escrows(&recipients_path)?; - pks = append_escrow(pks, &escrows); + let pks = append_escrow(named.clone(), &escrows); repo.secret_add(&name, value.as_bytes(), &pks)?; + // Only the keys named here are recorded as accepted (a key that is + // also escrow included); the escrow keys appended above count from + // `[escrow]` at check time. + repo.accept_keys(&format!("secret:{name}"), &named)?; println!("added secret {name} for {} recipient(s)", pks.len()); } SecretOp::Grant { name, to, identity } => { @@ -3416,9 +3422,8 @@ fn run_policy(op: PolicyOp) -> Result<()> { } resolved.push((id, given.or(local))); } - for (id, pk) in &resolved { - repo.accept_recipient(&scope, id, pk.as_ref())?; - } + // The whole batch is checked, then written once. + repo.accept_recipients(&scope, &resolved)?; println!("accepted {} recipient(s) for {scope}", resolved.len()); } PolicyOp::Forget { scope, key } => { @@ -4817,10 +4822,14 @@ fn run_protect(prefix: Option, to: Vec, list: bool, json: bool) let recipients_path = repo.layout().dot_sc.join("recipients.toml"); let dir = load_recipients(&recipients_path)?; - let mut pks = resolve_names(&dir, &to)?; + let named = resolve_names(&dir, &to)?; let escrows = load_escrows(&recipients_path)?; - pks = append_escrow(pks, &escrows); + let pks = append_escrow(named.clone(), &escrows); let id = repo.protect(&prefix, &pks, None)?; + // Only the keys named here are recorded as accepted (a key that is also + // escrow included); the escrow keys appended above count from `[escrow]` + // at check time. + repo.accept_keys(&format!("path:{prefix}"), &named)?; println!( "protected {prefix} for {} recipient(s): {}", pks.len(), diff --git a/crates/cli/tests/policy_accept.rs b/crates/cli/tests/policy_accept.rs index 38a4706e..72f1958b 100644 --- a/crates/cli/tests/policy_accept.rs +++ b/crates/cli/tests/policy_accept.rs @@ -241,3 +241,124 @@ fn a_fresh_clone_refuses_a_default_secret_rotate_until_accepted() { let _ = alice_pk; std::fs::remove_dir_all(&root).unwrap(); } + +#[test] +fn a_batch_with_an_unresolvable_path_id_records_nothing() { + let root = tmp("batch"); + let keys = tmp("batch-keys"); + let (_, alice_pk) = keygen(&keys, "alice"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write( + root.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{alice_pk}\"\n"), + ) + .unwrap(); + + // The first key is fine; the second is an id nobody here can resolve to a + // full key, which a `path:` scope needs even with --allow-unknown. + let unknown = "00112233445566778899aabbccddeeff"; + let both = format!("{alice_pk},{unknown}"); + let out = sc( + &root, + &[ + "policy", + "accept", + "path:a/", + "--key", + &both, + "--allow-unknown", + ], + ); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("full public keys"), + "{}", + stderr(&out) + ); + assert_eq!(record(&root), "", "the first key was not written"); + + // For a secret an id is all the record holds, so the same batch works. + let out = sc( + &root, + &[ + "policy", + "accept", + "secret:X", + "--key", + &both, + "--allow-unknown", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert_eq!(record(&root).lines().count(), 2); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +#[test] +fn the_remove_command_form_for_a_dashed_target_parses() { + let root = tmp("dashed"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write(root.join("f.txt"), "1\n").unwrap(); + assert!(sc(&root, &["commit", "-m", "c"]).status.success()); + let id = "00112233445566778899aabbccddeeff"; + for args in [ + vec!["revoke", "--recipient-id", id, "--", "-x/"], + vec!["secret", "revoke", "--recipient-id", id, "--", "-X"], + vec![ + "branch", + "revoke", + "--recipient-id", + id, + "--identity", + "/nonexistent", + "--", + "-b", + ], + ] { + let out = sc(&root, &args); + let err = stderr(&out); + assert!(!out.status.success(), "{args:?} has nothing to revoke"); + assert!( + !err.contains("unexpected argument") && !err.contains("Usage:"), + "{args:?} did not parse: {err}" + ); + } + std::fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn escrow_keys_are_not_recorded_by_protect_or_secret_add() { + let root = tmp("escrow"); + let keys = tmp("escrow-keys"); + let (_, alice_pk) = keygen(&keys, "alice"); + let (_, escrow_pk) = keygen(&keys, "escrow"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write( + root.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{alice_pk}\"\n[escrow]\nkeys = [\"{escrow_pk}\"]\n"), + ) + .unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), "data\n").unwrap(); + let out = sc(&root, &["protect", "secret/", "--to", "alice"]); + assert!(out.status.success(), "{}", stderr(&out)); + let out = sc( + &root, + &["secret", "add", "DB", "--to", "alice", "--value", "v"], + ); + assert!(out.status.success(), "{}", stderr(&out)); + + let rec = record(&root); + assert!(rec.contains(&alice_pk), "the named key is recorded: {rec}"); + assert!(rec.contains("secret:DB\t"), "{rec}"); + assert!(!rec.contains(&escrow_pk), "escrow recorded: {rec}"); + // The secret line holds an id: compare through the escrow's own id. + let shown = String::from_utf8_lossy(&sc(&root, &["escrow", "show"]).stdout).to_string(); + let escrow_id = shown.split(": ").nth(1).unwrap().lines().next().unwrap(); + assert!(!rec.contains(escrow_id), "escrow id recorded: {rec}"); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index 15d9df7f..c8e1be2a 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -60,35 +60,88 @@ pub struct Unaccepted { } impl Unaccepted { - fn label(&self) -> &str { - self.name.as_deref().unwrap_or("UNKNOWN") + /// The local `[recipients]` name, or `UNKNOWN`, made safe to print. + fn label(&self) -> String { + match &self.name { + Some(n) => scl_core::sanitize_display_line(n).into_owned(), + None => "UNKNOWN".to_string(), + } + } + + /// The scope as text that is safe to print: a rule prefix, secret name or + /// branch name comes from the repository, so it can hold control characters. + fn shown_scope(&self) -> String { + scl_core::sanitize_display_line(&self.scope).into_owned() + } + + /// Whether the scope prints as itself. A scope that does not never gets a + /// runnable command, however it would be quoted. + fn scope_is_plain(&self) -> bool { + matches!( + scl_core::sanitize_display_line(&self.scope), + std::borrow::Cow::Borrowed(_) + ) } /// The exact `sc policy accept` command; an unknown key needs - /// `--allow-unknown`. - pub fn accept_command(&self) -> String { + /// `--allow-unknown`. `None` when the scope holds control characters. + pub fn accept_command(&self) -> Option { + if !self.scope_is_plain() { + return None; + } let unknown = if self.name.is_none() { " --allow-unknown" } else { "" }; - format!( + Some(format!( "sc policy accept {} --key {}{unknown}", sh_quote(&self.scope), self.key - ) + )) } - /// The command that removes the recipient from the repository data. - pub fn remove_command(&self) -> String { + /// The command that removes the recipient from the repository data, flags + /// first and the target after `--` when it starts with `-`. `None` when the + /// scope holds control characters. + pub fn remove_command(&self) -> Option { + if !self.scope_is_plain() { + return None; + } let (kind, target) = self.scope.split_once(':').unwrap_or(("", &self.scope)); let target = sh_quote(target); - match kind { - "path" => format!("sc revoke {target} --recipient-id {}", self.id), - "secret" => format!("sc secret revoke {target} --recipient-id {}", self.id), + let (head, flags) = match kind { + "path" => ("sc revoke", format!("--recipient-id {}", self.id)), + "secret" => ("sc secret revoke", format!("--recipient-id {}", self.id)), + _ => ( + "sc branch revoke", + format!("--recipient-id {} --identity ", self.id), + ), + }; + Some(if target.starts_with('-') { + format!("{head} {flags} -- {target}") + } else { + format!("{head} {target} {flags}") + }) + } + + /// Where to look at a scope that has no safe command. + fn inspect_command(&self) -> &'static str { + match self.scope.split_once(':').map(|(k, _)| k) { + Some("path") => "sc protect --list", + Some("secret") => "sc secret list", + _ => "sc branch list", + } + } + + /// The Accept and Remove lines of the refusal. + fn command_lines(&self) -> String { + match (self.accept_command(), self.remove_command()) { + (Some(accept), Some(remove)) => format!(" Accept: {accept}\n Remove: {remove}\n"), _ => format!( - "sc branch revoke {target} --recipient-id {} --identity ", - self.id + " The scope holds control characters, so no command is suggested; \ + inspect it with `{}`.\n", + self.inspect_command() ), } } @@ -106,17 +159,17 @@ fn sh_quote(s: &str) -> String { } } -/// The text of [`Error::UnacceptedRecipients`]. +/// The text of [`Error::UnacceptedRecipients`]. Every field that can come from +/// the repository is escaped. pub(crate) fn describe(pairs: &[Unaccepted]) -> String { let mut out = String::new(); for p in pairs { out.push_str(&format!( - "{} grants a recipient you have not accepted: {} ({}).\n Accept: {}\n Remove: {}\n", - p.scope, + "{} grants a recipient you have not accepted: {} ({}).\n{}", + p.shown_scope(), p.id, p.label(), - p.accept_command(), - p.remove_command() + p.command_lines() )); } out.push_str("Nothing was written."); @@ -128,12 +181,18 @@ pub(crate) fn describe_inline(pairs: &[Unaccepted]) -> String { pairs .iter() .map(|p| { + let commands = match (p.accept_command(), p.remove_command()) { + (Some(accept), Some(remove)) => format!("accept: {accept}; remove: {remove}"), + _ => format!( + "the scope holds control characters, so no command is suggested \ + (inspect it with `{}`)", + p.inspect_command() + ), + }; format!( - "grants a recipient you have not accepted: {} ({}); accept: {}; remove: {}", + "grants a recipient you have not accepted: {} ({}); {commands}", p.id, - p.label(), - p.accept_command(), - p.remove_command() + p.label() ) }) .collect::>() @@ -315,40 +374,60 @@ impl Repo { Accepted::load(&self.layout) } - /// Record `id` as accepted for `scope` (`sc policy accept`; idempotent). - /// `key` is the full public key when the caller has it; a `path:` scope - /// records full keys, so it is required there. Local file only: allowed - /// while a merge, pick or rebase is stopped. - pub fn accept_recipient( + /// Record recipients as accepted for `scope` (`sc policy accept`; + /// idempotent). Each entry is the id plus the full public key when the + /// caller has it; a `path:` scope records full keys, so it is required + /// there. The whole batch is validated before the record is written, once. + /// Local file only: allowed while a merge, pick or rebase is stopped. + pub fn accept_recipients( &self, scope: &str, - id: &RecipientId, - key: Option<&PublicKey>, + entries: &[(RecipientId, Option)], ) -> Result<()> { validate_scope(scope)?; - let recorded = match (scope.starts_with("path:"), key) { - (true, Some(k)) => entry(scope, k), - (true, None) => { - return Err(Error::InvalidArgument(format!( - "{scope} records full public keys: pass the scl-pk- key of {id}, \ - or a recipient id that is in .sc/recipients.toml" - ))) - } - (false, _) => id.to_string(), - }; + let mut recorded = Vec::with_capacity(entries.len()); + for (id, key) in entries { + recorded.push(match (scope.starts_with("path:"), key) { + (true, Some(k)) => entry(scope, k), + (true, None) => { + return Err(Error::InvalidArgument(format!( + "{scope} records full public keys: pass the scl-pk- key of {id}, \ + or a recipient id that is in .sc/recipients.toml" + ))) + } + (false, _) => id.to_string(), + }); + } let mut pairs = read_pairs(&self.layout)?; - if pairs.insert((scope.to_string(), recorded)) { + let before = pairs.len(); + pairs.extend(recorded.into_iter().map(|e| (scope.to_string(), e))); + if pairs.len() != before { write_pairs(&self.layout, &pairs)?; } Ok(()) } - /// [`Repo::accept_recipient`] for keys the user named on the command line. + /// [`Repo::accept_recipients`] for keys the user named on the command line. pub fn accept_keys(&self, scope: &str, keys: &[PublicKey]) -> Result<()> { - for k in keys { - self.accept_recipient(scope, &k.recipient_id(), Some(k))?; - } - Ok(()) + let entries: Vec<_> = keys + .iter() + .map(|k| (k.recipient_id(), Some(k.clone()))) + .collect(); + self.accept_recipients(scope, &entries) + } + + /// [`Repo::accept_keys`] for a recipient list a command assembled from what + /// the user named plus the configured escrow keys. An escrow key is never + /// recorded: it counts as accepted from the current `[escrow]` config at + /// check time, so removing it from there takes the acceptance with it. + pub(crate) fn accept_named_keys(&self, scope: &str, keys: &[PublicKey]) -> Result<()> { + let accepted = self.accepted()?; + let named: Vec = keys + .iter() + .filter(|k| !accepted.escrow.contains(k.recipient_id().as_str())) + .cloned() + .collect(); + self.accept_keys(scope, &named) } /// Remove every accepted pair of `scope` for this recipient (`sc policy @@ -534,7 +613,10 @@ mod tests { ); let named = refused(c.commit("me", "m")); assert_eq!(named[0].name.as_deref(), Some("mallory")); - assert!(!named[0].accept_command().contains("--allow-unknown")); + assert!(!named[0] + .accept_command() + .unwrap() + .contains("--allow-unknown")); drop(c); let _ = std::fs::remove_dir_all(c_root); w.cleanup(); @@ -626,6 +708,7 @@ mod tests { assert_eq!(pairs[0].id, atk_id); assert!(pairs[0] .remove_command() + .unwrap() .starts_with("sc secret revoke API_TOKEN --recipient-id")); let report = v.rewrap(&vsk, &[], &both, false).unwrap(); @@ -927,9 +1010,9 @@ mod tests { assert_eq!(acc.pairs.len(), 2); // A path scope needs the full key; a bad scope is refused. assert!(repo - .accept_recipient("path:x/", &pk.recipient_id(), None) + .accept_recipients("path:x/", &[(pk.recipient_id(), None)]) .is_err()); - repo.accept_recipient("secret:T", &pk.recipient_id(), None) + repo.accept_recipients("secret:T", &[(pk.recipient_id(), None)]) .unwrap(); assert!(repo.accept_keys("nope", std::slice::from_ref(&pk)).is_err()); // Forgetting goes by recipient id, whichever form was recorded. @@ -964,4 +1047,232 @@ mod tests { drop(repo); let _ = std::fs::remove_dir_all(root); } + + // Escrow keys a command appends are accepted from the current `[escrow]` + // config at check time, never recorded: removing one from the config takes + // the acceptance with it. + #[test] + fn escrow_keys_a_command_appends_are_not_recorded() { + let root = dir("escrow-not-recorded"); + let (sk, me) = generate_keypair(); + let (_, bob) = generate_keypair(); + let (_, escrow) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + let toml = format!("[escrow]\nkeys = [\"{}\"]\n", escrow.to_key_string()); + put(&root, ".sc/recipients.toml", &toml); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", &[me.clone(), escrow.clone()], None) + .unwrap(); + repo.secret_add("S", b"v", &[me.clone(), escrow.clone()]) + .unwrap(); + repo.branch_private( + "b", + &sk, + std::slice::from_ref(&bob), + std::slice::from_ref(&escrow), + ) + .unwrap(); + + let record = std::fs::read_to_string(repo.layout().accepted_recipients_path()).unwrap(); + assert!( + !record.contains(&escrow.to_key_string()) && !record.contains(&id_of(&escrow)), + "escrow recorded: {record}" + ); + for (scope, key) in [ + ("path:p/", &me), + ("secret:S", &me), + ("branch:b", &bob), + ("branch:b", &sk.public()), + ] { + assert!(repo + .accepted() + .unwrap() + .unaccepted(scope, std::slice::from_ref(key)) + .is_empty()); + } + // Escrow is accepted while it is configured. + let acc = repo.accepted().unwrap(); + for scope in ["path:p/", "secret:S", "branch:b"] { + assert!(acc + .unaccepted(scope, std::slice::from_ref(&escrow)) + .is_empty()); + } + // And stops being accepted when it is removed from the config. + put(&root, ".sc/recipients.toml", "[recipients]\n"); + let acc = repo.accepted().unwrap(); + for scope in ["path:p/", "secret:S", "branch:b"] { + assert_eq!( + acc.unaccepted(scope, std::slice::from_ref(&escrow)).len(), + 1 + ); + } + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // The local approval goes before the ref moves: when the record cannot be + // written the revoke fails with nothing moved, and it lands once it can. + #[test] + fn a_revoke_drops_the_approval_before_it_moves_the_ref() { + let root = dir("revoke-order"); + let (sk, a) = generate_keypair(); + let (_, b) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", &[a.clone(), b.clone()], None).unwrap(); + repo.secret_add("S", b"v", &[a.clone(), b.clone()]).unwrap(); + repo.branch_private("emb", &sk, std::slice::from_ref(&b), &[]) + .unwrap(); + let block = root.join(".sc/accepted-recipients.tmp"); + std::fs::create_dir(&block).unwrap(); + + let tip = repo.head_tip().unwrap(); + assert!(repo.revoke("p/", &b.recipient_id()).is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "path revoke moved the ref"); + assert!(repo.secret_revoke("S", &b.recipient_id()).is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "secret revoke moved the ref"); + assert_eq!(repo.secret_recipients("S").unwrap().len(), 2); + let emb = crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(); + assert!(repo + .branch_revoke("emb", &sk, &b.recipient_id(), std::slice::from_ref(&a)) + .is_err()); + assert_eq!( + crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(), + emb, + "branch revoke moved the ref" + ); + + std::fs::remove_dir(&block).unwrap(); + repo.revoke("p/", &b.recipient_id()).unwrap(); + repo.secret_revoke("S", &b.recipient_id()).unwrap(); + assert_eq!(repo.secret_recipients("S").unwrap().len(), 1); + // `a` is the creator of `emb` and the key `branch_private` accepted. + repo.branch_revoke("emb", &sk, &b.recipient_id(), std::slice::from_ref(&a)) + .unwrap(); + let acc = repo.accepted().unwrap(); + for scope in ["path:p/", "secret:S", "branch:emb"] { + assert_eq!(acc.unaccepted(scope, std::slice::from_ref(&b)).len(), 1); + } + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // A batch with one entry it cannot record writes none of them. + #[test] + fn a_batch_with_a_bad_entry_writes_nothing() { + let root = dir("batch"); + let (_, good) = generate_keypair(); + let (_, other) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + let err = repo + .accept_recipients( + "path:x/", + &[ + (good.recipient_id(), Some(good.clone())), + (other.recipient_id(), None), + ], + ) + .unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err}"); + assert!(!repo.layout().accepted_recipients_path().exists()); + // Without the bad entry the same call records, in one write. + repo.accept_recipients("path:x/", &[(good.recipient_id(), Some(good.clone()))]) + .unwrap(); + assert_eq!(repo.accepted().unwrap().pairs.len(), 1); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // A scope comes from the repository: it is escaped in the message and a + // scope with control characters gets no command to run. + #[test] + fn a_scope_with_control_characters_is_escaped_and_gets_no_command() { + let evil = "path:a\n Accept: sc policy accept x\u{1b}[2J/"; + let pair = Unaccepted { + scope: evil.into(), + key: "k".into(), + id: "0".repeat(32), + name: Some("na\nme\u{202e}".into()), + }; + assert_eq!(pair.accept_command(), None); + assert_eq!(pair.remove_command(), None); + for text in [ + Error::UnacceptedRecipients { + pairs: vec![pair.clone()], + } + .to_string(), + describe_inline(std::slice::from_ref(&pair)), + ] { + assert!( + text.chars() + .all(|c| c == '\n' || !(c.is_control() || c == '\u{202e}')), + "raw control character in {text:?}" + ); + assert!(text.contains("control characters"), "{text}"); + assert!(text.contains("sc protect --list"), "{text}"); + assert!( + text.lines().all(|l| !l.trim_start().starts_with("Accept:")), + "{text}" + ); + } + // A plain scope still gets both commands. + let plain = Unaccepted { + scope: "secret:DB".into(), + ..pair + }; + assert!(plain.accept_command().is_some() && plain.remove_command().is_some()); + } + + // A target that starts with `-` goes after `--`, flags first. + #[test] + fn a_remove_command_puts_a_dashed_target_after_the_flags() { + let id = "0".repeat(32); + let at = |scope: &str| { + Unaccepted { + scope: scope.into(), + key: "k".into(), + id: id.clone(), + name: None, + } + .remove_command() + .unwrap() + }; + assert_eq!( + at("path:-x/"), + format!("sc revoke --recipient-id {id} -- -x/") + ); + assert_eq!( + at("secret:-X"), + format!("sc secret revoke --recipient-id {id} -- -X") + ); + assert_eq!( + at("branch:-b"), + format!("sc branch revoke --recipient-id {id} --identity -- -b") + ); + assert_eq!(at("path:x/"), format!("sc revoke x/ --recipient-id {id}")); + } + + // An unreadable record blocks a seal, not a commit that wraps nothing. + #[test] + fn an_unreadable_record_blocks_only_what_seals() { + let root = dir("lazy"); + let (_, pk) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "plain.txt", "p\n"); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", std::slice::from_ref(&pk), None).unwrap(); + let record = repo.layout().accepted_recipients_path(); + std::fs::remove_file(&record).unwrap(); + std::fs::create_dir(&record).unwrap(); + + // Plain edit: the protected file is carried, nothing is wrapped. + put(&root, "plain.txt", "edited\n"); + repo.commit("me", "plain").unwrap(); + // A seal needs the record. + put(&root, "p/x.txt", "changed\n"); + let err = repo.commit("me", "seal").unwrap_err(); + assert!(matches!(err, Error::Io(_)), "{err}"); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } } diff --git a/crates/repo/src/private.rs b/crates/repo/src/private.rs index 844b826a..4595e0b2 100644 --- a/crates/repo/src/private.rs +++ b/crates/repo/src/private.rs @@ -331,8 +331,11 @@ impl Repo { wrap_keys.push(pk.clone()); } } - // The creator and the keys named for this branch are accepted for it. - self.accept_keys(&crate::accepted::branch_scope(name), &wrap_keys)?; + // The creator and the keys named for this branch are accepted for it; + // the escrow keys are not recorded (they count from `[escrow]`). + let mut named = vec![creator.public()]; + named.extend(recipients.iter().cloned()); + self.accept_keys(&crate::accepted::branch_scope(name), &named)?; let kek_wraps: Vec = wrap_keys .iter() .map(|pk| scl_crypto::wrap_kek_for(&kek, pk)) @@ -1318,9 +1321,9 @@ impl Repo { index_ct: ctx.index.encrypt(&new_kek), kek_wraps, }; - let id = self.replace_manifest(name, &ctx, manifest, &format!("branch revoke {name}"))?; + // Drop the local approval before the ref moves (see `Repo::revoke`). self.forget_recipient(&crate::accepted::branch_scope(name), revoked)?; - Ok(id) + self.replace_manifest(name, &ctx, manifest, &format!("branch revoke {name}")) } fn replace_manifest( @@ -1897,7 +1900,7 @@ impl Repo { BTreeMap::new() }; let (encrypted, fresh) = - crate::protect::encrypt_protected(to_encrypt, &self.accepted()?)?; + crate::protect::encrypt_protected(to_encrypt, || self.accepted())?; for (path, ct, mode, perms) in encrypted { let blob = Object::blob(ct.clone()); let bid = blob.id(); diff --git a/crates/repo/src/protect.rs b/crates/repo/src/protect.rs index 46685198..933f9687 100644 --- a/crates/repo/src/protect.rs +++ b/crates/repo/src/protect.rs @@ -146,11 +146,17 @@ pub(crate) type WrapMap = BTreeMap>; /// The one place a rule's recipients become wraps, so it is also the gate /// (ADR-0059): every recipient must be accepted in this clone for the winning /// rule's scope (or be local escrow), else the call refuses, naming every -/// unaccepted pair, before any file is sealed. +/// unaccepted pair, before any file is sealed. `accepted` loads the record, and +/// runs only when there is something to seal: a commit that wraps nothing must +/// not depend on the record being readable. pub(crate) fn encrypt_protected( plaintexts: Vec, - accepted: &crate::accepted::Accepted, + accepted: impl FnOnce() -> Result, ) -> Result<(Vec, WrapMap)> { + if plaintexts.is_empty() { + return Ok((Vec::new(), BTreeMap::new())); + } + let accepted = accepted()?; let mut unaccepted: Vec = Vec::new(); for (_, _, _, recipients, prefix) in &plaintexts { let keys: Vec = recipients @@ -232,8 +238,10 @@ mod tests { vec![pk.to_bytes()], "secret/".into(), )], - &crate::accepted::Accepted::default() - .with_named("path:secret/", std::slice::from_ref(&pk)), + || { + Ok(crate::accepted::Accepted::default() + .with_named("path:secret/", std::slice::from_ref(&pk))) + }, ) .unwrap() }; @@ -438,7 +446,7 @@ mod tests { vec![], "secret/".into(), )], - &crate::accepted::Accepted::default(), + || Ok(crate::accepted::Accepted::default()), ) .unwrap_err(); assert!( diff --git a/crates/repo/src/protect_ops.rs b/crates/repo/src/protect_ops.rs index d9988b10..c617873a 100644 --- a/crates/repo/src/protect_ops.rs +++ b/crates/repo/src/protect_ops.rs @@ -97,7 +97,7 @@ impl Repo { .with_named(&scope, recipients) .require(&scope, &granted)?; } - self.accept_keys(&scope, recipients)?; + self.accept_named_keys(&scope, recipients)?; let head = crate::refs::current_branch(self.layout())?; let before = crate::refs::read_branch_tip(self.layout(), &head)?; // Build the rule's snapshot and the sealing commit on top of it before @@ -332,6 +332,10 @@ impl Repo { e.epoch = epoch; e.state = scl_core::RecipientState::Revoked; } + // Drop the local approval before the ref moves: an interruption between + // the two leaves a revoke that did not land and a recipient to revoke + // again, never a landed revoke the approval outlives. + self.forget_recipient(&crate::accepted::path_scope(prefix), recipient_id)?; let head = crate::refs::current_branch(self.layout())?; let before = crate::refs::read_branch_tip(self.layout(), &head)?; let id = self.commit_snapshot( @@ -349,7 +353,6 @@ impl Repo { &head, &[(head.clone(), before, Some(id))], )?; - self.forget_recipient(&crate::accepted::path_scope(prefix), recipient_id)?; Ok(id) } diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 3dbf019e..fcb10985 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -250,7 +250,7 @@ pub(crate) fn replay_commit( }; let (mut all, to_encrypt) = split_for_encryption(&fm.files, &union_prot)?; - let (encrypted, fresh_wrapped) = protect::encrypt_protected(to_encrypt, &repo.accepted()?)?; + let (encrypted, fresh_wrapped) = protect::encrypt_protected(to_encrypt, || repo.accepted())?; all.extend(encrypted); let root = match &tree_carried { Some((crate::merge_tree::Carried::Root(id), _)) => *id, diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 66164dd1..c3733521 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -688,7 +688,7 @@ impl Repo { } let (protected_all, sealed_wrapped) = - crate::protect::encrypt_protected(to_seal, &self.accepted()?)?; + crate::protect::encrypt_protected(to_seal, || self.accepted())?; // Record every freshly sealed path's new blob id into the cache; the // committing caller persists it only after the ref actually moves. if let Some(c) = cache { @@ -1878,7 +1878,7 @@ impl Repo { } let (encrypted, fresh_wrapped) = - crate::protect::encrypt_protected(to_encrypt, &self.accepted()?)?; + crate::protect::encrypt_protected(to_encrypt, || self.accepted())?; carried.extend(encrypted); let all = carried; diff --git a/crates/repo/src/rewrap.rs b/crates/repo/src/rewrap.rs index 0862595d..1dd11cdc 100644 --- a/crates/repo/src/rewrap.rs +++ b/crates/repo/src/rewrap.rs @@ -86,8 +86,10 @@ impl Repo { let mut skipped: Vec<(String, String)> = Vec::new(); // Wraps minted here come from repository data (wrap labels, rules), so // an entry whose target set holds a key this clone never accepted is - // skipped, not sealed (ADR-0059). The escrow set passed in is local. - let accepted = self.accepted()?.with_escrow(escrows); + // skipped, not sealed (ADR-0059). The escrow set passed in is local. The + // record loads at the first entry that wraps anything, so a rewrap with + // nothing to wrap does not depend on it being readable. + let mut accepted: Option = None; // ---- Secrets half: fresh-DEK reseal to current set + escrow. ---- let mut registry = snap.secrets.clone(); @@ -138,7 +140,13 @@ impl Repo { continue; } let targets = crate::secrets::append_dedup(targets, escrows); - let pending = accepted.unaccepted(&crate::accepted::secret_scope(&name), &targets); + if accepted.is_none() { + accepted = Some(self.accepted()?.with_escrow(escrows)); + } + let pending = accepted + .as_ref() + .expect("loaded above") + .unaccepted(&crate::accepted::secret_scope(&name), &targets); if !pending.is_empty() { skipped.push(( format!("secret {name}"), @@ -255,7 +263,13 @@ impl Repo { target_pks.push(e.clone()); } } - let pending = accepted.unaccepted(&scope, &target_pks); + if accepted.is_none() { + accepted = Some(self.accepted()?.with_escrow(escrows)); + } + let pending = accepted + .as_ref() + .expect("loaded above") + .unaccepted(&scope, &target_pks); if !pending.is_empty() { skipped.push(( format!("path {path}"), diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index ae52dc34..79216fa0 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -107,8 +107,9 @@ impl Repo { } check_secret_name(name)?; require_recipients(recipients)?; - // The caller named these keys, so they are accepted for this secret. - self.accept_keys(&crate::accepted::secret_scope(name), recipients)?; + // The caller named these keys, so they are accepted for this secret + // (the escrow keys a command appends are not recorded). + self.accept_named_keys(&crate::accepted::secret_scope(name), recipients)?; let secret = scl_crypto::seal(name, value, recipients); let id = { let arc = self.store_arc(); @@ -213,20 +214,20 @@ impl Repo { use `secret rotate --to ` to change the recipient set instead" ))); } + // Drop the local approval before the ref moves (see `Repo::revoke`). + self.forget_recipient(&crate::accepted::secret_scope(name), recipient)?; let new_id = { let arc = self.store_arc(); let i = arc.lock().unwrap().put(Object::Secret(revoked))?; i }; reg.insert(name.to_string(), new_id); - let id = self.commit_registry( + self.commit_registry( reg, "secret", &format!("revoke from {name}"), &format!("secret revoke {name}"), - )?; - self.forget_recipient(&crate::accepted::secret_scope(name), recipient)?; - Ok(id) + ) } /// Rotate a secret's value under a **fresh DEK**, re-sealing for `recipients`. diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index a335234d..a066c7b4 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -136,7 +136,13 @@ too, not just the src-control-side metadata. `sc protect` (it checks the rule it changes and builds its sealing commit before either ref moves), `secret_rotate`, `rewrap` (an entry with an unaccepted key is skipped, the rest commits, the exit code is non-zero) and - `branch_revoke`. A carry that copies + `branch_revoke`. The record loads only when something is sealed, so a commit + that wraps nothing does not depend on it. Escrow keys are never recorded: they + count from the current `[escrow]` section, so removing one withdraws it. A + scope in a refusal comes from the repository, so it is escaped and a scope + with control characters gets no runnable command. The record's integrity + relies on the working-tree path guard (a checkout never writes under `.sc/`). + A carry that copies existing wraps is not a seal and is not gated. A refusal writes nothing and names the scope, the id, the local `[recipients]` name or `UNKNOWN`, the `sc policy accept` command and the revoke command. Only keys you name on the diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md index e569ec12..badca3f5 100644 --- a/docs/adr/0059-locally-accepted-recipients.md +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -50,7 +50,15 @@ accepted in every scope. It is local state like `.sc/local-key`: written atomically (temp file and rename) by a command that holds the repo lock, never part of a snapshot, never in a pack, never sent by clone, fetch or push, and not read by `sc gc`. `sc ws` -and `sc work` commit through the host repo, so they use the host's record. +and `sc work` commit through the host repo, so they use the host's record. Its +integrity depends on the working-tree path guard (a checkout never writes under +`.sc/`, fix/sc-path-guard): without it a cloned tree could plant the file. + +Escrow keys are never recorded. They count as accepted from the `[escrow]` +section as it is when a seal is checked, so removing a key from `[escrow]` +withdraws its acceptance everywhere. The record loads only when something is +about to be sealed (or accepted, forgotten or checked by a revoke), so a commit +or a rewrap that wraps nothing does not depend on it being readable. ### The gate @@ -59,7 +67,11 @@ neither accepted for the seal's scope nor escrow. The error names every unaccepted pair: the scope, the recipient id, the local `[recipients]` name or `UNKNOWN`, the `sc policy accept` command (with `--allow-unknown` for an unknown key; a `path:` scope shows the full key to pass) and the command that -removes the key from the data: +removes the key from the data. A scope is a rule prefix, secret name or branch +name, so the repository controls it: every field is escaped with +`sanitize_display_line`, and a scope with control characters gets no command +at all, only a pointer to `sc protect --list`, `sc secret list` or +`sc branch list`: ``` path:secret/sub/ grants a recipient you have not accepted: 3f9a... (UNKNOWN). @@ -70,7 +82,8 @@ Nothing was written. Remove is `sc revoke --recipient-id `, `sc secret revoke --recipient-id ` or `sc branch revoke --recipient-id ---identity `. +--identity `. A target that starts with `-` is written flags first and +after `--` (`sc revoke --recipient-id -- -x/`). The gate sits where wraps are minted, after the carry-or-seal decision, so a carry that copies existing wraps is never gated: @@ -93,10 +106,16 @@ Only keys the user names on the command line are accepted without asking: `sc protect --to`, `sc grant`, `sc secret add`, `sc secret grant`, `sc secret rotate --to`, `sc branch --private --to` (and the creator's own key) and `sc branch grant`. The library functions behind them record the keys -they were given; `sc secret rotate --to` does it from the CLI because the -library cannot tell a named set from one derived from wrap labels. A key that -comes from repository data, by any route, is never auto-accepted. The local -revoke commands remove the pair they revoke. +they were given, minus any key in the current `[escrow]` (a command appends the +escrow keys to the list it passes in, and those are not the user's choice); the +CLI then records the keys the user named, so a named key that is also escrow +survives its removal from `[escrow]`. `sc secret rotate --to` records from the +CLI because the library cannot tell a named set from one derived from wrap +labels. A key that comes from repository data, by any route, is never +auto-accepted. The local revoke commands remove the pair they revoke, after +validation and before the new ref is published, so an interruption leaves a +revoke that did not land (retry it), never a landed revoke whose approval +outlives it. ### Commands @@ -104,7 +123,9 @@ revoke commands remove the pair they revoke. pairs. A key in neither `[recipients]` nor `[escrow]` needs `--allow-unknown`, so accepting a key you cannot identify takes a flag you typed. A `path:` scope needs the full key: pass the `scl-pk-` string, or an id that resolves through -`[recipients]` or `[escrow]`. +`[recipients]` or `[escrow]`. `--allow-unknown` does not lift that: an id with +no key behind it is an error for a `path:` scope. The batch is checked as a +whole and written once, so a bad entry leaves the record as it was. `sc policy forget ` removes one. Both touch only the local file, so both work while a merge, pick or rebase is stopped, and a refused completion can be retried after an accept. From e9492099082fa7bbef9de71fa106e280595aa15b Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:38:25 +0200 Subject: [PATCH 05/10] fix(cli): print one revoke form, warn on a rule-less path scope, document revoke gap The suggested Remove command is always "flags, --, target", so a target that starts with "-" cannot be read as a flag (the check ran after quoting before, so it never fired). The shell quoting is POSIX only, as its comment says. sc rewrap prints its skipped entries through sanitize_display_line: they carry paths and names from the repository. sc policy accept warns when a path: scope names no rule at the tip, and still records it. An ignored test (needs PR #367) pins that a cloned tree holding .sc/accepted-recipients or .sc/recipients.toml is refused, since the record's integrity does not rest on this change alone. ADR-0059, THREAT-MODEL and ROADMAP record the residual risk that a revoke made in another clone leaves this clone's acceptance in place, and the follow-on of recording the grant epoch with each path: pair. --- ROADMAP.md | 4 +- crates/cli/src/main.rs | 21 ++++- crates/cli/tests/policy_accept.rs | 47 ++++++++++- crates/repo/src/accepted.rs | 84 ++++++++++++++++---- docs/THREAT-MODEL.md | 12 ++- docs/adr/0059-locally-accepted-recipients.md | 20 +++-- 6 files changed, 159 insertions(+), 29 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 31c315c2..e0b01e19 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -955,7 +955,9 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in an allowed name (`sc verify --require` before `sc run` is the mitigation); (4) `sc policy status` and `sc policy accept --all`; (5) a refused `sc work` harvest discards the agent's checkout with the session (a preflight that - refuses to start would avoid it). + refuses to start would avoid it); (6) record the grant epoch with each + `path:` pair, so a revoke made in another clone, followed by a re-grant at a + higher epoch, is not sealed to on the strength of an old acceptance. - **Leases (P36a follow-on).** The only cross-writer coordination today is the manifest's compare-and-swap; there is no lease/TTL primitive for operations that need to hold exclusive intent across more than one bucket diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index b5f5ae84..56283266 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3425,6 +3425,20 @@ fn run_policy(op: PolicyOp) -> Result<()> { // The whole batch is checked, then written once. repo.accept_recipients(&scope, &resolved)?; println!("accepted {} recipient(s) for {scope}", resolved.len()); + // A `path:` scope names a rule's prefix exactly. One the tip has no + // rule for is recorded all the same (a rule may arrive by a merge), + // but it is usually a typo. A private branch has no rule list to read. + if let Some(prefix) = scope.strip_prefix("path:") { + if let Ok(rules) = repo.protected_prefixes() { + if !rules.iter().any(|(p, _)| p == prefix) { + eprintln!( + "warning: no protection rule with the prefix {:?} at the tip of the current branch; \ + recorded anyway (see `sc protect --list`)", + scl_core::sanitize_display_line(prefix) + ); + } + } + } } PolicyOp::Forget { scope, key } => { let (id, _) = parse_recipient_ref(&key)?; @@ -5022,7 +5036,12 @@ fn run_rewrap(identity: Option, dry_run: bool, rotate: bool) -> Result< if !report.skipped.is_empty() { eprintln!("skipped {} entr(ies):", report.skipped.len()); for (entry, reason) in &report.skipped { - eprintln!(" {entry}: {reason}"); + // Paths and names come from the repository. + eprintln!( + " {}: {}", + scl_core::sanitize_display_line(entry), + scl_core::sanitize_display_line(reason) + ); } let again = if rotate { "sc rewrap --rotate" diff --git a/crates/cli/tests/policy_accept.rs b/crates/cli/tests/policy_accept.rs index 72f1958b..368e43a5 100644 --- a/crates/cli/tests/policy_accept.rs +++ b/crates/cli/tests/policy_accept.rs @@ -190,7 +190,8 @@ fn a_fresh_clone_refuses_a_rule_seal_until_the_key_is_accepted() { "path:secret/ grants a recipient you have not accepted", "(alice)", "sc policy accept path:secret/ --key", - "sc revoke secret/ --recipient-id", + "sc revoke --recipient-id", + "-- secret/", "Nothing was written.", ] { assert!(err.contains(want), "missing {want:?} in: {err}"); @@ -217,7 +218,8 @@ fn a_fresh_clone_refuses_a_default_secret_rotate_until_accepted() { assert!( err.contains("secret:DB grants a recipient you have not accepted") && err.contains("sc policy accept secret:DB --key") - && err.contains("sc secret revoke DB --recipient-id"), + && err.contains("sc secret revoke --recipient-id") + && err.contains("-- DB"), "{err}" ); @@ -362,3 +364,44 @@ fn escrow_keys_are_not_recorded_by_protect_or_secret_add() { std::fs::remove_dir_all(&root).unwrap(); std::fs::remove_dir_all(&keys).unwrap(); } + +#[test] +fn a_path_scope_with_no_rule_at_the_tip_warns_but_is_recorded() { + let root = tmp("norule"); + let keys = tmp("norule-keys"); + let (_, alice_pk) = keygen(&keys, "alice"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write( + root.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{alice_pk}\"\n"), + ) + .unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), "data\n").unwrap(); + let out = sc(&root, &["protect", "secret/", "--to", "alice"]); + assert!(out.status.success(), "{}", stderr(&out)); + + // A rule exists for `secret/`: no warning. + let out = sc( + &root, + &["policy", "accept", "path:secret/", "--key", &alice_pk], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!(!stderr(&out).contains("warning"), "{}", stderr(&out)); + + // None for `secret` (a different prefix string): warned, still recorded. + let out = sc( + &root, + &["policy", "accept", "path:secrets/", "--key", &alice_pk], + ); + assert!(out.status.success(), "{}", stderr(&out)); + assert!( + stderr(&out).contains("warning: no protection rule"), + "{}", + stderr(&out) + ); + assert!(record(&root).contains("path:secrets/\t")); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index c8e1be2a..e4c33c2a 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -101,15 +101,14 @@ impl Unaccepted { )) } - /// The command that removes the recipient from the repository data, flags - /// first and the target after `--` when it starts with `-`. `None` when the - /// scope holds control characters. + /// The command that removes the recipient from the repository data: flags + /// first, then `--`, then the target, so a target that starts with `-` is + /// not read as a flag. `None` when the scope holds control characters. pub fn remove_command(&self) -> Option { if !self.scope_is_plain() { return None; } let (kind, target) = self.scope.split_once(':').unwrap_or(("", &self.scope)); - let target = sh_quote(target); let (head, flags) = match kind { "path" => ("sc revoke", format!("--recipient-id {}", self.id)), "secret" => ("sc secret revoke", format!("--recipient-id {}", self.id)), @@ -118,11 +117,7 @@ impl Unaccepted { format!("--recipient-id {} --identity ", self.id), ), }; - Some(if target.starts_with('-') { - format!("{head} {flags} -- {target}") - } else { - format!("{head} {target} {flags}") - }) + Some(format!("{head} {flags} -- {}", sh_quote(target))) } /// Where to look at a scope that has no safe command. @@ -147,7 +142,8 @@ impl Unaccepted { } } -/// Quote `s` for a POSIX shell unless it is plainly safe. +/// Quote `s` for a POSIX shell unless it is plainly safe. The `'\''` escape is +/// POSIX only; PowerShell and cmd.exe quote differently and are not handled. fn sh_quote(s: &str) -> String { if !s.is_empty() && s.chars() @@ -600,7 +596,7 @@ mod tests { text.contains(&format!( "sc policy accept path:secret/sub/ --key {} --allow-unknown", w.atk.to_key_string() - )) && text.contains(&format!("sc revoke secret/sub/ --recipient-id {atk_id}")) + )) && text.contains(&format!("sc revoke --recipient-id {atk_id} -- secret/sub/")) && text.contains("(UNKNOWN)") && text.contains("Nothing was written."), "{text}" @@ -709,7 +705,7 @@ mod tests { assert!(pairs[0] .remove_command() .unwrap() - .starts_with("sc secret revoke API_TOKEN --recipient-id")); + .starts_with("sc secret revoke --recipient-id")); let report = v.rewrap(&vsk, &[], &both, false).unwrap(); assert_eq!(report.secrets_rewrapped, vec!["OTHER".to_string()]); @@ -1223,9 +1219,10 @@ mod tests { assert!(plain.accept_command().is_some() && plain.remove_command().is_some()); } - // A target that starts with `-` goes after `--`, flags first. + // The target always goes after the flags and `--`, so one that starts with + // `-` is not read as a flag. #[test] - fn a_remove_command_puts_a_dashed_target_after_the_flags() { + fn a_remove_command_puts_the_target_after_the_flags() { let id = "0".repeat(32); let at = |scope: &str| { Unaccepted { @@ -1249,7 +1246,64 @@ mod tests { at("branch:-b"), format!("sc branch revoke --recipient-id {id} --identity -- -b") ); - assert_eq!(at("path:x/"), format!("sc revoke x/ --recipient-id {id}")); + assert_eq!( + at("path:x/"), + format!("sc revoke --recipient-id {id} -- x/") + ); + } + + // The record's integrity does not rest on this change alone: a tree that + // carries `.sc/accepted-recipients` or `.sc/recipients.toml` (the escrow + // list also counts as accepted) must not be able to write them on clone. + // That is the working-tree path guard's job (PR #367). + #[test] + #[ignore = "needs PR #367"] + fn a_cloned_tree_cannot_plant_the_record_or_the_recipients_file() { + for (i, planted) in [".sc/accepted-recipients", ".sc/recipients.toml"] + .into_iter() + .enumerate() + { + let s_root = dir(&format!("plant-s{i}")); + let c_root = dir(&format!("plant-c{i}")); + std::fs::remove_dir_all(&c_root).unwrap(); + let src = Repo::init(&s_root).unwrap(); + put(&s_root, "readme.txt", "hello\n"); + let tip = src.commit("me", "base").unwrap(); + let snap = src.snapshot(&tip).unwrap(); + let root = src + .vfs() + .write_tree_with_perms(&[ + ( + "readme.txt".to_string(), + b"hello\n".to_vec(), + scl_core::FileMode::FILE, + 0, + ), + ( + planted.to_string(), + b"planted".to_vec(), + scl_core::FileMode::FILE, + 0, + ), + ]) + .unwrap(); + src.commit_snapshot(root, vec![tip], snap.secrets, snap.protection, "w", "plant") + .unwrap(); + drop(src); + + let cloned = Repo::clone_to(&s_root, &c_root); + assert!( + cloned.is_err(), + "a clone of a tree holding {planted} succeeded" + ); + assert!( + !c_root.join(planted).exists(), + "{planted} was written by a checkout" + ); + drop(cloned); + let _ = std::fs::remove_dir_all(s_root); + let _ = std::fs::remove_dir_all(c_root); + } } // An unreadable record blocks a seal, not a commit that wraps nothing. diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index a066c7b4..a7b5c7b7 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -159,10 +159,14 @@ too, not just the src-control-side metadata. ciphertext is not bound to its path, so a file relocated under an accepted prefix can gain recipients through that prefix's rewrap (a format change, deferred). A spurious reseal of unchanged content (a lost cache) is a seal and - refuses like any other. The printed revoke command can itself refuse (`sc revoke` - will not remove a rule's last recipient, and will not run while a merge, pick or - rebase is stopped), and a refused `sc work` harvest discards that agent's - temporary checkout with the session; accept first, or use `sc ws`. + refuses like any other. A revoke made in another clone does not remove this + clone's acceptance: if Alice revokes Mallory, Bob's clone still accepts her, and + a later re-grant at a higher epoch is sealed to without a prompt (recording the + grant epoch with each `path:` pair would close it; deferred). The printed + revoke command can itself refuse (`sc revoke` will not remove a rule's last + recipient, and will not run while a merge, pick or rebase is stopped), and a + refused `sc work` harvest discards that agent's temporary checkout with the + session; accept first, or use `sc ws`. - **Local cache key, `sc keygen` identity and TLS serve key are owner-only on unix and Windows (P33, #214, #281):** the unchanged-detection cache is keyed by `.sc/local-key`, created owner-only from diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md index badca3f5..ff6cc335 100644 --- a/docs/adr/0059-locally-accepted-recipients.md +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -76,14 +76,15 @@ at all, only a pointer to `sc protect --list`, `sc secret list` or ``` path:secret/sub/ grants a recipient you have not accepted: 3f9a... (UNKNOWN). Accept: sc policy accept path:secret/sub/ --key scl-pk-... --allow-unknown - Remove: sc revoke secret/sub/ --recipient-id 3f9a... + Remove: sc revoke --recipient-id 3f9a... -- secret/sub/ Nothing was written. ``` -Remove is `sc revoke --recipient-id `, `sc secret revoke ---recipient-id ` or `sc branch revoke --recipient-id ---identity `. A target that starts with `-` is written flags first and -after `--` (`sc revoke --recipient-id -- -x/`). +Remove is `sc revoke --recipient-id -- `, +`sc secret revoke --recipient-id -- ` or +`sc branch revoke --recipient-id --identity -- `: flags first, +then `--`, then the target, so a target that starts with `-` is not read as a +flag. The quoting of a target is POSIX shell only. The gate sits where wraps are minted, after the carry-or-seal decision, so a carry that copies existing wraps is never gated: @@ -125,7 +126,9 @@ so accepting a key you cannot identify takes a flag you typed. A `path:` scope needs the full key: pass the `scl-pk-` string, or an id that resolves through `[recipients]` or `[escrow]`. `--allow-unknown` does not lift that: an id with no key behind it is an error for a `path:` scope. The batch is checked as a -whole and written once, so a bad entry leaves the record as it was. +whole and written once, so a bad entry leaves the record as it was. A `path:` +scope that names no rule at the tip prints a warning and is recorded anyway (a +rule may arrive by a merge, and a typo is only a harmless dead line). `sc policy forget ` removes one. Both touch only the local file, so both work while a merge, pick or rebase is stopped, and a refused completion can be retried after an accept. @@ -191,6 +194,11 @@ stays 6. `sc grant --to ` first) and refuses while a merge, pick or rebase is stopped (accept, or abort the operation). A writer with a higher epoch can add the key back after a revoke. +- **A revoke made in another clone does not remove this clone's acceptance.** + If Alice revokes Mallory, Bob's clone still accepts Mallory for that scope, + and a later re-grant of Mallory at a higher epoch is sealed to without a + prompt. Recording the grant epoch with each `path:` pair would close it + (deferred). - **`sc work` discards a refused agent's work.** Its harvest error is reported per workspace, but the temporary checkouts go with the session. Accept the keys first (`sc policy accept`); `sc ws` workspaces persist and can retry. From bad868635cfc97dd8f4dbd27d2c1b07713495884 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:45:47 +0200 Subject: [PATCH 06/10] test(repo): run the clone-planting check now that the path guard landed --- crates/repo/src/accepted.rs | 52 ++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index e4c33c2a..7b6a4dd4 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -1257,7 +1257,6 @@ mod tests { // list also counts as accepted) must not be able to write them on clone. // That is the working-tree path guard's job (PR #367). #[test] - #[ignore = "needs PR #367"] fn a_cloned_tree_cannot_plant_the_record_or_the_recipients_file() { for (i, planted) in [".sc/accepted-recipients", ".sc/recipients.toml"] .into_iter() @@ -1270,23 +1269,40 @@ mod tests { put(&s_root, "readme.txt", "hello\n"); let tip = src.commit("me", "base").unwrap(); let snap = src.snapshot(&tip).unwrap(); - let root = src - .vfs() - .write_tree_with_perms(&[ - ( - "readme.txt".to_string(), - b"hello\n".to_vec(), - scl_core::FileMode::FILE, - 0, - ), - ( - planted.to_string(), - b"planted".to_vec(), - scl_core::FileMode::FILE, - 0, - ), - ]) - .unwrap(); + // Built through the store: a commit now refuses a `.sc` path itself. + let root = { + use scl_core::{EntryKind, FileMode, Object, Tree, TreeEntry}; + let store = src.vfs_handle().store(); + let mut st = store.lock().unwrap(); + let blob = st.put(Object::blob(b"planted".to_vec())).unwrap(); + let leaf = planted.trim_start_matches(".sc/").to_string(); + let sub = st + .put(Object::Tree(Tree::new(vec![TreeEntry { + name: leaf, + kind: EntryKind::Blob, + id: blob, + mode: FileMode::FILE, + perms: 0, + }]))) + .unwrap(); + st.put(Object::Tree(Tree::new(vec![ + TreeEntry { + name: ".sc".into(), + kind: EntryKind::Tree, + id: sub, + mode: FileMode::FILE, + perms: 0, + }, + TreeEntry { + name: "readme.txt".into(), + kind: EntryKind::Blob, + id: blob, + mode: FileMode::FILE, + perms: 0, + }, + ]))) + .unwrap() + }; src.commit_snapshot(root, vec![tip], snap.secrets, snap.protection, "w", "plant") .unwrap(); drop(src); From 9c798ac8286966074bc8b26c4d8085ce12bdd909 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 12:54:20 +0200 Subject: [PATCH 07/10] fix(repo): stage approvals until the plan validates, skip relabeled secrets in rewrap rewrap skips a registry entry sealed under another name before opening it, as secret_rotate refuses it: it would otherwise be approved by the registry name and resealed under the sealed name, so a relabeled secret got wraps under another secret's approvals. protect_with_escrow and secret_add_with_escrow take the keys the user named apart from the escrow keys a command appends. protect stages the named keys in memory while it validates the rule and the sealing commit, records them after validation and before either ref moves, and a refusal leaves record, refs and oplog alone. secret add records the named keys before its ref moves. The CLI no longer records after the operation landed. The record is written with atomic_write_durable (fsynced temp file, rename, fsynced directory), as durable as the ref write. rewrap reads the record only for an entry that mints a wrap: a secret that opens, a path re-sealed or rotated, or a target with no wrap yet. A randomized path whose every wrap is reused copies them and needs no approval. The refusal text says what is true: no ref moved and no approval was recorded. sc protect --list, sc secret list, sc branch list and sc policy accept/forget print repository text through sanitize_display_line. --- crates/cli/src/main.rs | 42 +-- crates/cli/tests/policy_accept.rs | 45 ++- crates/repo/src/accepted.rs | 284 ++++++++++++++++--- crates/repo/src/protect_ops.rs | 62 ++-- crates/repo/src/repo.rs | 4 + crates/repo/src/rewrap.rs | 76 +++-- crates/repo/src/secrets.rs | 27 +- docs/THREAT-MODEL.md | 8 +- docs/adr/0059-locally-accepted-recipients.md | 29 +- 9 files changed, 454 insertions(+), 123 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 56283266..11565576 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3006,7 +3006,7 @@ fn run_branch_list(json: bool, identity: Option) -> Result<()> { (true, true) => " (private)".into(), (true, false) => " (private, no access)".into(), }; - println!("{star} {name}{marker}"); + println!("{star} {}{marker}", scl_core::sanitize_display_line(&name)); } Ok(()) } @@ -3294,11 +3294,9 @@ fn run_secret(op: SecretOp) -> Result<()> { let named = resolve_names(&dir, &to)?; let escrows = load_escrows(&recipients_path)?; let pks = append_escrow(named.clone(), &escrows); - repo.secret_add(&name, value.as_bytes(), &pks)?; - // Only the keys named here are recorded as accepted (a key that is - // also escrow included); the escrow keys appended above count from - // `[escrow]` at check time. - repo.accept_keys(&format!("secret:{name}"), &named)?; + // Only the named keys are recorded as accepted, before the ref + // moves; the escrow keys count from `[escrow]` at check time. + repo.secret_add_with_escrow(&name, value.as_bytes(), &named, &escrows)?; println!("added secret {name} for {} recipient(s)", pks.len()); } SecretOp::Grant { name, to, identity } => { @@ -3327,7 +3325,12 @@ fn run_secret(op: SecretOp) -> Result<()> { println!("{}", serde_json::Value::Array(arr)); } else { for info in infos { - println!("{} ({} recipient(s))", info.name, info.recipients); + // A secret name comes from the repository. + println!( + "{} ({} recipient(s))", + scl_core::sanitize_display_line(&info.name), + info.recipients + ); } } } @@ -3424,7 +3427,11 @@ fn run_policy(op: PolicyOp) -> Result<()> { } // The whole batch is checked, then written once. repo.accept_recipients(&scope, &resolved)?; - println!("accepted {} recipient(s) for {scope}", resolved.len()); + println!( + "accepted {} recipient(s) for {}", + resolved.len(), + scl_core::sanitize_display_line(&scope) + ); // A `path:` scope names a rule's prefix exactly. One the tip has no // rule for is recorded all the same (a rule may arrive by a merge), // but it is usually a typo. A private branch has no rule list to read. @@ -3442,10 +3449,11 @@ fn run_policy(op: PolicyOp) -> Result<()> { } PolicyOp::Forget { scope, key } => { let (id, _) = parse_recipient_ref(&key)?; + let shown = scl_core::sanitize_display_line(&scope); if repo.forget_recipient(&scope, &id)? { - println!("forgot {id} for {scope}"); + println!("forgot {id} for {shown}"); } else { - println!("{id} was not accepted for {scope}"); + println!("{id} was not accepted for {shown}"); } } } @@ -4807,7 +4815,11 @@ fn run_protect(prefix: Option, to: Vec, list: bool, json: bool) } for (p, recips) in prefixes { let granted = recips.iter().filter(|r| r.granted).count(); - println!("{p} ({granted} granted)"); + // A rule prefix comes from the repository. + println!( + "{} ({granted} granted)", + scl_core::sanitize_display_line(&p) + ); for r in recips { let state = if r.granted { "granted" } else { "REVOKED" }; println!(" {} {}@e{}", r.id.as_str(), state, r.epoch); @@ -4839,11 +4851,9 @@ fn run_protect(prefix: Option, to: Vec, list: bool, json: bool) let named = resolve_names(&dir, &to)?; let escrows = load_escrows(&recipients_path)?; let pks = append_escrow(named.clone(), &escrows); - let id = repo.protect(&prefix, &pks, None)?; - // Only the keys named here are recorded as accepted (a key that is also - // escrow included); the escrow keys appended above count from `[escrow]` - // at check time. - repo.accept_keys(&format!("path:{prefix}"), &named)?; + // Only the named keys are recorded as accepted, before the refs move; the + // escrow keys count from `[escrow]` at check time. + let id = repo.protect_with_escrow(&prefix, &named, &escrows, None)?; println!( "protected {prefix} for {} recipient(s): {}", pks.len(), diff --git a/crates/cli/tests/policy_accept.rs b/crates/cli/tests/policy_accept.rs index 368e43a5..29826123 100644 --- a/crates/cli/tests/policy_accept.rs +++ b/crates/cli/tests/policy_accept.rs @@ -192,7 +192,7 @@ fn a_fresh_clone_refuses_a_rule_seal_until_the_key_is_accepted() { "sc policy accept path:secret/ --key", "sc revoke --recipient-id", "-- secret/", - "Nothing was written.", + "No ref moved and no approval was recorded.", ] { assert!(err.contains(want), "missing {want:?} in: {err}"); } @@ -405,3 +405,46 @@ fn a_path_scope_with_no_rule_at_the_tip_warns_but_is_recorded() { std::fs::remove_dir_all(&root).unwrap(); std::fs::remove_dir_all(&keys).unwrap(); } + +#[test] +fn listings_and_policy_output_escape_repository_text() { + let root = tmp("escape"); + let keys = tmp("escape-keys"); + let (_, alice_pk) = keygen(&keys, "alice"); + assert!(sc(&root, &["init"]).status.success()); + std::fs::write( + root.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{alice_pk}\"\n"), + ) + .unwrap(); + // A rule prefix is repository data: it can hold an escape sequence. + let prefix = "ev\u{1b}[2Jil/"; + let out = sc(&root, &["protect", prefix, "--to", "alice"]); + assert!(out.status.success(), "{}", stderr(&out)); + + let out = sc(&root, &["protect", "--list"]); + let text = String::from_utf8_lossy(&out.stdout).to_string(); + assert!( + out.status.success() && text.contains("ev\\x1b[2Jil/"), + "{text:?}" + ); + assert!(!text.contains('\u{1b}'), "raw escape in {text:?}"); + + let scope = format!("path:{prefix}"); + let out = sc(&root, &["policy", "accept", &scope, "--key", &alice_pk]); + let text = String::from_utf8_lossy(&out.stdout).to_string(); + assert!(out.status.success(), "{}", stderr(&out)); + assert!( + !text.contains('\u{1b}') && text.contains("\\x1b"), + "{text:?}" + ); + let out = sc(&root, &["policy", "forget", &scope, &alice_pk]); + let text = String::from_utf8_lossy(&out.stdout).to_string(); + assert!( + !text.contains('\u{1b}') && text.contains("\\x1b"), + "{text:?}" + ); + + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index 7b6a4dd4..474411a2 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -168,7 +168,7 @@ pub(crate) fn describe(pairs: &[Unaccepted]) -> String { p.command_lines() )); } - out.push_str("Nothing was written."); + out.push_str("No ref moved and no approval was recorded."); out } @@ -345,9 +345,8 @@ fn write_pairs(layout: &Layout, pairs: &BTreeSet<(String, String)>) -> Result<() .iter() .map(|(s, e)| format!("{}\t{e}\n", esc(s))) .collect(); - let tmp = layout.dot_sc.join("accepted-recipients.tmp"); - std::fs::write(&tmp, body)?; - std::fs::rename(&tmp, layout.accepted_recipients_path())?; + // As durable as the ref write it precedes: fsynced, renamed, parent fsynced. + scl_core::fsutil::atomic_write_durable(&layout.accepted_recipients_path(), body.as_bytes())?; Ok(()) } @@ -365,9 +364,45 @@ fn validate_scope(scope: &str) -> Result<()> { } } +/// Approvals a command is validating but has not recorded yet; dropped, they +/// are gone. See [`Repo::stage_approvals`]. +pub(crate) struct StagedApprovals<'a>(&'a Repo); + +impl Drop for StagedApprovals<'_> { + fn drop(&mut self) { + self.0.staged.lock().unwrap().clear(); + } +} + impl Repo { + /// The record as this repo reads it: the file, plus any approvals staged by + /// the running command. pub(crate) fn accepted(&self) -> Result { - Accepted::load(&self.layout) + let mut accepted = Accepted::load(&self.layout)?; + for (scope, key) in self.staged.lock().unwrap().iter() { + accepted = match scope { + Some(scope) => accepted.with_named(scope, std::slice::from_ref(key)), + None => accepted.with_escrow(std::slice::from_ref(key)), + }; + } + Ok(accepted) + } + + /// Count `named` as accepted for `scope`, and `escrows` as accepted + /// everywhere, while the returned guard lives, without writing the record. + /// A command that must validate a whole plan (every seal it would make) + /// before it records anything stages the keys it was given, validates, then + /// records the named ones with `accept_keys` and only then moves a ref. + pub(crate) fn stage_approvals( + &self, + scope: &str, + named: &[PublicKey], + escrows: &[PublicKey], + ) -> StagedApprovals<'_> { + let mut staged = self.staged.lock().unwrap(); + staged.extend(named.iter().map(|k| (Some(scope.to_string()), k.clone()))); + staged.extend(escrows.iter().map(|k| (None, k.clone()))); + StagedApprovals(self) } /// Record recipients as accepted for `scope` (`sc policy accept`; @@ -412,20 +447,6 @@ impl Repo { self.accept_recipients(scope, &entries) } - /// [`Repo::accept_keys`] for a recipient list a command assembled from what - /// the user named plus the configured escrow keys. An escrow key is never - /// recorded: it counts as accepted from the current `[escrow]` config at - /// check time, so removing it from there takes the acceptance with it. - pub(crate) fn accept_named_keys(&self, scope: &str, keys: &[PublicKey]) -> Result<()> { - let accepted = self.accepted()?; - let named: Vec = keys - .iter() - .filter(|k| !accepted.escrow.contains(k.recipient_id().as_str())) - .cloned() - .collect(); - self.accept_keys(scope, &named) - } - /// Remove every accepted pair of `scope` for this recipient (`sc policy /// forget`, and every local revoke). Returns whether there was one. pub fn forget_recipient(&self, scope: &str, id: &RecipientId) -> Result { @@ -598,7 +619,7 @@ mod tests { w.atk.to_key_string() )) && text.contains(&format!("sc revoke --recipient-id {atk_id} -- secret/sub/")) && text.contains("(UNKNOWN)") - && text.contains("Nothing was written."), + && text.contains("No ref moved and no approval was recorded."), "{text}" ); @@ -844,8 +865,18 @@ mod tests { put(&w.v_root, "docs/y.txt", "y\n"); let tip = w.v.head_tip().unwrap(); let oplog = w.v.oplog().unwrap().len(); + let record = std::fs::read(w.v.layout().accepted_recipients_path()).unwrap(); let pairs = refused(w.v.protect("docs/", std::slice::from_ref(&me), None)); assert_eq!(pairs[0].scope, "path:secret/sub/"); + assert_eq!( + std::fs::read(w.v.layout().accepted_recipients_path()).unwrap(), + record, + "the named key was recorded although the plan was refused" + ); + assert!( + w.v.staged.lock().unwrap().is_empty(), + "a staged approval outlived the command" + ); assert_eq!(w.v.head_tip().unwrap(), tip, "no ref move"); assert_eq!(w.v.oplog().unwrap().len(), oplog, "no oplog record"); assert!(w @@ -1057,10 +1088,20 @@ mod tests { let toml = format!("[escrow]\nkeys = [\"{}\"]\n", escrow.to_key_string()); put(&root, ".sc/recipients.toml", &toml); put(&root, "p/x.txt", "x\n"); - repo.protect("p/", &[me.clone(), escrow.clone()], None) - .unwrap(); - repo.secret_add("S", b"v", &[me.clone(), escrow.clone()]) - .unwrap(); + repo.protect_with_escrow( + "p/", + std::slice::from_ref(&me), + std::slice::from_ref(&escrow), + None, + ) + .unwrap(); + repo.secret_add_with_escrow( + "S", + b"v", + std::slice::from_ref(&me), + std::slice::from_ref(&escrow), + ) + .unwrap(); repo.branch_private( "b", &sk, @@ -1106,8 +1147,31 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// Make `.sc` read-only so the record cannot be written (a read still works) + /// until the guard drops. Refs and objects live in subdirectories, which + /// stay writable: a ref that moved despite the failed record write would + /// show up as a changed tip. + #[cfg(unix)] + struct ReadOnlyDotSc(PathBuf); + #[cfg(unix)] + impl ReadOnlyDotSc { + fn new(dot_sc: &Path) -> Self { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dot_sc, std::fs::Permissions::from_mode(0o555)).unwrap(); + ReadOnlyDotSc(dot_sc.to_path_buf()) + } + } + #[cfg(unix)] + impl Drop for ReadOnlyDotSc { + fn drop(&mut self) { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } + } + // The local approval goes before the ref moves: when the record cannot be // written the revoke fails with nothing moved, and it lands once it can. + #[cfg(unix)] #[test] fn a_revoke_drops_the_approval_before_it_moves_the_ref() { let root = dir("revoke-order"); @@ -1119,26 +1183,24 @@ mod tests { repo.secret_add("S", b"v", &[a.clone(), b.clone()]).unwrap(); repo.branch_private("emb", &sk, std::slice::from_ref(&b), &[]) .unwrap(); - let block = root.join(".sc/accepted-recipients.tmp"); - std::fs::create_dir(&block).unwrap(); - let tip = repo.head_tip().unwrap(); - assert!(repo.revoke("p/", &b.recipient_id()).is_err()); - assert_eq!(repo.head_tip().unwrap(), tip, "path revoke moved the ref"); - assert!(repo.secret_revoke("S", &b.recipient_id()).is_err()); - assert_eq!(repo.head_tip().unwrap(), tip, "secret revoke moved the ref"); - assert_eq!(repo.secret_recipients("S").unwrap().len(), 2); let emb = crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(); - assert!(repo - .branch_revoke("emb", &sk, &b.recipient_id(), std::slice::from_ref(&a)) - .is_err()); - assert_eq!( - crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(), - emb, - "branch revoke moved the ref" - ); - - std::fs::remove_dir(&block).unwrap(); + { + let _ro = ReadOnlyDotSc::new(&repo.layout().dot_sc); + assert!(repo.revoke("p/", &b.recipient_id()).is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "path revoke moved the ref"); + assert!(repo.secret_revoke("S", &b.recipient_id()).is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "secret revoke moved the ref"); + assert_eq!(repo.secret_recipients("S").unwrap().len(), 2); + assert!(repo + .branch_revoke("emb", &sk, &b.recipient_id(), std::slice::from_ref(&a)) + .is_err()); + assert_eq!( + crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(), + emb, + "branch revoke moved the ref" + ); + } repo.revoke("p/", &b.recipient_id()).unwrap(); repo.secret_revoke("S", &b.recipient_id()).unwrap(); assert_eq!(repo.secret_recipients("S").unwrap().len(), 1); @@ -1148,11 +1210,64 @@ mod tests { let acc = repo.accepted().unwrap(); for scope in ["path:p/", "secret:S", "branch:emb"] { assert_eq!(acc.unaccepted(scope, std::slice::from_ref(&b)).len(), 1); + assert!(acc.unaccepted(scope, std::slice::from_ref(&a)).is_empty()); } drop(repo); let _ = std::fs::remove_dir_all(root); } + // The named approvals are recorded before the ref moves, so a record write + // that fails leaves a `protect` or a `secret add` unlanded. + #[cfg(unix)] + #[test] + fn a_failed_record_write_leaves_protect_and_secret_add_unlanded() { + let root = dir("write-first"); + let (_, a) = generate_keypair(); + let (_, escrow) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "q/x.txt", "x\n"); + // A first seal creates `.sc/local-key`, which later commands only read. + repo.protect("q/", std::slice::from_ref(&a), None).unwrap(); + put(&root, "p/x.txt", "x\n"); + let tip = repo.head_tip().unwrap(); + let oplog = repo.oplog().unwrap().len(); + { + let _ro = ReadOnlyDotSc::new(&repo.layout().dot_sc); + assert!(repo + .protect_with_escrow( + "p/", + std::slice::from_ref(&a), + std::slice::from_ref(&escrow), + None + ) + .is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "protect moved the ref"); + assert!(repo + .secret_add_with_escrow( + "S", + b"v", + std::slice::from_ref(&a), + std::slice::from_ref(&escrow) + ) + .is_err()); + assert_eq!(repo.head_tip().unwrap(), tip, "secret add moved the ref"); + } + assert_eq!(repo.oplog().unwrap().len(), oplog); + // Once the record can be written both land, with only the named key recorded. + repo.protect_with_escrow( + "p/", + std::slice::from_ref(&a), + std::slice::from_ref(&escrow), + None, + ) + .unwrap(); + let record = std::fs::read_to_string(repo.layout().accepted_recipients_path()).unwrap(); + assert!(record.contains("path:p/\t"), "{record}"); + assert!(!record.contains(&escrow.to_key_string()), "{record}"); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + // A batch with one entry it cannot record writes none of them. #[test] fn a_batch_with_a_bad_entry_writes_nothing() { @@ -1345,4 +1460,89 @@ mod tests { drop(repo); let _ = std::fs::remove_dir_all(root); } + + // A registry entry sealed under another name is skipped by rewrap, as + // `secret_rotate` refuses it: approving it by the registry name and + // resealing it under the sealed name would hand it the wrong approvals. + #[test] + fn rewrap_skips_a_relabeled_secret_instead_of_resealing_it() { + let root = dir("relabeled"); + let (sk, pk) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + // `pk` is approved for the registry name only. + repo.accept_keys("secret:A", std::slice::from_ref(&pk)) + .unwrap(); + let tip = { + let secret = scl_crypto::seal("B", b"value-of-b", std::slice::from_ref(&pk)); + let sid = repo + .vfs() + .store() + .lock() + .unwrap() + .put(Object::Secret(secret)) + .unwrap(); + let root_id = repo.vfs().write_tree(&[]).unwrap(); + let mut secrets = std::collections::BTreeMap::new(); + secrets.insert("A".to_string(), sid); + repo.commit_snapshot( + root_id, + vec![], + secrets, + scl_core::Protection::default(), + "w", + "plant", + ) + .unwrap() + }; + let before = repo.snapshot(&tip).unwrap().secrets; + + let report = repo + .rewrap(&sk, &[], std::slice::from_ref(&pk), false) + .unwrap(); + assert!(report.secrets_rewrapped.is_empty(), "{report:?}"); + assert_eq!(report.skipped.len(), 1, "{report:?}"); + assert_eq!(report.skipped[0].0, "secret A"); + assert!( + report.skipped[0].1.contains("sealed as \"B\""), + "{:?}", + report.skipped + ); + assert!(report.commit.is_none(), "nothing was resealed"); + assert_eq!(repo.snapshot(&tip).unwrap().secrets, before); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // The record is read when an entry actually mints a wrap: a randomized + // blob whose targets all have a wrap is rebuilt from the existing ones. + #[test] + fn rewrap_reads_the_record_only_for_entries_that_mint_a_wrap() { + let root = dir("rewrap-lazy"); + let (sk, pk) = generate_keypair(); + let (_, other) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", std::slice::from_ref(&pk), None).unwrap(); + let record = repo.layout().accepted_recipients_path(); + std::fs::remove_file(&record).unwrap(); + std::fs::create_dir(&record).unwrap(); + + // Every target already has a wrap: nothing is minted, no record needed. + let report = repo + .rewrap(&sk, &[], std::slice::from_ref(&pk), false) + .unwrap(); + assert_eq!(report.blobs_rewrapped, 1, "{report:?}"); + // A fresh DEK wraps to every target, so the record is read. + let err = repo + .rewrap_with(&sk, &[], std::slice::from_ref(&pk), false, true) + .unwrap_err(); + assert!(matches!(err, Error::Io(_)), "{err}"); + // So does a target with no wrap yet. + let err = repo + .rewrap(&sk, std::slice::from_ref(&other), &[pk], false) + .unwrap_err(); + assert!(matches!(err, Error::Io(_)), "{err}"); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } } diff --git a/crates/repo/src/protect_ops.rs b/crates/repo/src/protect_ops.rs index c617873a..c6c49c84 100644 --- a/crates/repo/src/protect_ops.rs +++ b/crates/repo/src/protect_ops.rs @@ -26,11 +26,28 @@ impl Repo { /// recipient. If nothing matches yet, the rule is still recorded for future /// commits. The `identity` arg is reserved for future re-encrypt symmetry /// (e.g. re-protecting already-committed plaintext) and is unused today. - /// Returns the id of the resulting commit. + /// Returns the id of the resulting commit. Every key in `recipients` counts + /// as named by the caller (see [`Repo::protect_with_escrow`]). pub fn protect( &self, prefix: &str, recipients: &[scl_crypto::PublicKey], + identity: Option<&scl_crypto::SecretKey>, + ) -> Result { + self.protect_with_escrow(prefix, recipients, &[], identity) + } + + /// [`Repo::protect`] with the keys the user `named` apart from the `escrows` + /// a command appends. Both get the rule; only `named` is recorded as + /// accepted (escrow counts from `[escrow]` at check time, ADR-0059). The + /// approvals are staged in memory while the whole plan (the rule and the + /// sealing commit) is validated, then recorded, then the refs move, so a + /// refusal leaves the record and the refs as they were. + pub fn protect_with_escrow( + &self, + prefix: &str, + named: &[scl_crypto::PublicKey], + escrows: &[scl_crypto::PublicKey], _identity: Option<&scl_crypto::SecretKey>, ) -> Result { self.refuse_on_private("sc protect")?; @@ -48,7 +65,8 @@ impl Repo { if crate::rebase_state::in_progress(self.layout()) { return Err(Error::RebaseInProgress); } - crate::secrets::require_recipients(recipients)?; + let recipients = crate::secrets::append_dedup(named.to_vec(), escrows); + crate::secrets::require_recipients(&recipients)?; // Load the tip's protection, add/replace the rule, and persist it as a // policy-only commit (same root) so `commit` below sees the new prefix. let (root, parents, secrets, mut protection) = match self.head_tip()? { @@ -66,7 +84,7 @@ impl Repo { // Existing rule: (re-)grant the named recipients at the next epoch. // Never rebuild the rule wholesale — that would drop tombstones. let epoch = rule.next_epoch(); - for pk in recipients { + for pk in &recipients { rule.set_standing(pk.to_bytes(), epoch, scl_core::RecipientState::Granted); } } @@ -94,10 +112,10 @@ impl Repo { .map(|k| scl_crypto::PublicKey::from_bytes(*k)) .collect(); self.accepted()? - .with_named(&scope, recipients) + .with_named(&scope, named) + .with_escrow(escrows) .require(&scope, &granted)?; } - self.accept_named_keys(&scope, recipients)?; let head = crate::refs::current_branch(self.layout())?; let before = crate::refs::read_branch_tip(self.layout(), &head)?; // Build the rule's snapshot and the sealing commit on top of it before @@ -115,20 +133,26 @@ impl Repo { let files = worktree::read_worktree(&self.layout, &self.tracked_paths()?)?; let mut cache = self.open_protected_cache()?; let message = format!("encrypt under {prefix}"); - let id = self.snapshot_files( - files, - Some(policy_id), - None, - None, - None, - None, - None, - &self.sparse_spec()?, - &self.layout.root, - Some(&mut cache), - "system", - &message, - )?; + let id = { + // The keys it was given count as accepted for this one validation. + let _staged = self.stage_approvals(&scope, named, escrows); + self.snapshot_files( + files, + Some(policy_id), + None, + None, + None, + None, + None, + &self.sparse_spec()?, + &self.layout.root, + Some(&mut cache), + "system", + &message, + )? + }; + // Validated: record the approvals, then move the refs. + self.accept_keys(&scope, named)?; crate::refs::write_branch_tip(self.layout(), &head, &policy_id)?; crate::oplog::record( self.layout(), diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index c3733521..f2685170 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -62,6 +62,9 @@ pub struct AbortReport { pub struct Repo { pub(crate) layout: Layout, pub(crate) vfs: VfsRepo, + /// Approvals the running command is validating but has not recorded + /// (`Repo::stage_approvals`). + pub(crate) staged: std::sync::Mutex, scl_crypto::PublicKey)>>, _lock: RepoLock, } @@ -125,6 +128,7 @@ impl Repo { Ok(Repo { layout, vfs: VfsRepo::new(store), + staged: std::sync::Mutex::new(Vec::new()), _lock: lock, }) } diff --git a/crates/repo/src/rewrap.rs b/crates/repo/src/rewrap.rs index 1dd11cdc..a745e3d2 100644 --- a/crates/repo/src/rewrap.rs +++ b/crates/repo/src/rewrap.rs @@ -110,6 +110,21 @@ impl Repo { } } }; + // The secret is sealed under its own name and the AEAD binds it. An + // entry registered under another name would be approved here by the + // registry name and resealed under the sealed one, so it is skipped + // (as `secret_rotate` refuses it) before anything is opened. + if secret.name != name { + skipped.push(( + format!("secret {name}"), + format!( + "registry entry points at a secret sealed as {:?}; \ + rotate it with --value instead", + secret.name + ), + )); + continue; + } // Resolve current recipient ids to pubkeys from the known pool. let mut targets: Vec = Vec::new(); let mut unresolvable = None; @@ -140,6 +155,18 @@ impl Repo { continue; } let targets = crate::secrets::append_dedup(targets, escrows); + let value = match scl_crypto::open(&secret, identity) { + Ok(v) => v, + Err(_) => { + skipped.push(( + format!("secret {name}"), + "identity cannot open this secret".into(), + )); + continue; + } + }; + // A secret opens, so it gets a fresh seal: that is a wrap to every + // target, and the record is read now. if accepted.is_none() { accepted = Some(self.accepted()?.with_escrow(escrows)); } @@ -154,16 +181,6 @@ impl Repo { )); continue; } - let value = match scl_crypto::open(&secret, identity) { - Ok(v) => v, - Err(_) => { - skipped.push(( - format!("secret {name}"), - "identity cannot open this secret".into(), - )); - continue; - } - }; crate::secrets::require_recipients(&targets)?; if dry_run { secrets_rewrapped.push(name); @@ -263,21 +280,32 @@ impl Repo { target_pks.push(e.clone()); } } - if accepted.is_none() { - accepted = Some(self.accepted()?.with_escrow(escrows)); - } - let pending = accepted - .as_ref() - .expect("loaded above") - .unaccepted(&scope, &target_pks); - if !pending.is_empty() { - skipped.push(( - format!("path {path}"), - crate::accepted::describe_inline(&pending), - )); - continue; - } let convergent = perms & scl_core::RANDOMIZED == 0; + // An entry mints a wrap when it is re-sealed under a fresh DEK, or + // when a target has no wrap yet. Reusing every existing wrap copies + // them and needs no approval, so the record is not read. + let mints_a_wrap = convergent + || rotate + || target_pks.iter().any(|pk| { + !wks.iter() + .any(|w| w.recipient_id == pk.recipient_id().as_str()) + }); + if mints_a_wrap { + if accepted.is_none() { + accepted = Some(self.accepted()?.with_escrow(escrows)); + } + let pending = accepted + .as_ref() + .expect("loaded above") + .unaccepted(&scope, &target_pks); + if !pending.is_empty() { + skipped.push(( + format!("path {path}"), + crate::accepted::describe_inline(&pending), + )); + continue; + } + } if convergent || rotate { // Convergent (pre-P33): eager upgrade. Randomized with // `rotate`: a genuine cutover to a fresh DEK. Either way: diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 79216fa0..58a015cd 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -84,12 +84,27 @@ impl Repo { Ok(id) } - /// Seal `value` to `recipients` and register it under `name`. + /// Seal `value` to `recipients` and register it under `name`. Every key in + /// `recipients` counts as named by the caller (see + /// [`Repo::secret_add_with_escrow`]). pub fn secret_add( &self, name: &str, value: &[u8], recipients: &[PublicKey], + ) -> Result { + self.secret_add_with_escrow(name, value, recipients, &[]) + } + + /// [`Repo::secret_add`] with the keys the user `named` apart from the + /// `escrows` a command appends. Both can read the secret; only `named` is + /// recorded as accepted, and it is recorded before the ref moves. + pub fn secret_add_with_escrow( + &self, + name: &str, + value: &[u8], + named: &[PublicKey], + escrows: &[PublicKey], ) -> Result { self.refuse_on_private("sc secret add")?; // P19-I1: policy ops that move the branch tip via `commit_registry` @@ -106,11 +121,13 @@ impl Repo { return Err(Error::RebaseInProgress); } check_secret_name(name)?; - require_recipients(recipients)?; + let recipients = append_dedup(named.to_vec(), escrows); + require_recipients(&recipients)?; // The caller named these keys, so they are accepted for this secret - // (the escrow keys a command appends are not recorded). - self.accept_named_keys(&crate::accepted::secret_scope(name), recipients)?; - let secret = scl_crypto::seal(name, value, recipients); + // (the escrow keys a command appends are not recorded). Recorded before + // the ref moves, so a failed write leaves nothing landed. + self.accept_keys(&crate::accepted::secret_scope(name), named)?; + let secret = scl_crypto::seal(name, value, &recipients); let id = { let arc = self.store_arc(); let i = arc.lock().unwrap().put(Object::Secret(secret))?; diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index a7b5c7b7..530ed920 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -133,10 +133,12 @@ too, not just the src-control-side metadata. key for `path:`, the recipient id for `secret:` and `branch:`; local `[escrow]` keys count in every scope. The gate is `encrypt_protected`, the one function that turns a rule into wraps, plus - `sc protect` (it checks the rule it changes and builds its sealing commit - before either ref moves), `secret_rotate`, `rewrap` (an entry with an + `sc protect` (it checks the rule it changes, builds its sealing commit with the + named keys staged in memory, records them, then moves the refs), `secret_rotate`, `rewrap` (an entry with an unaccepted key is skipped, the rest commits, the exit code is non-zero) and - `branch_revoke`. The record loads only when something is sealed, so a commit + `branch_revoke`. The record is written durably (fsynced, as durable as the ref + write). `sc rewrap` skips a secret registered under a name other than the one + it is sealed under. The record loads only when something is sealed, so a commit that wraps nothing does not depend on it. Escrow keys are never recorded: they count from the current `[escrow]` section, so removing one withdraws it. A scope in a refusal comes from the repository, so it is escaped and a scope diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md index ff6cc335..770f5519 100644 --- a/docs/adr/0059-locally-accepted-recipients.md +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -47,8 +47,10 @@ is escaped (`%`, tab, newline, carriage return) because a path prefix can hold any byte but NUL. Local `[escrow]` keys from `.sc/recipients.toml` count as accepted in every scope. -It is local state like `.sc/local-key`: written atomically (temp file and -rename) by a command that holds the repo lock, never part of a snapshot, never +It is local state like `.sc/local-key`: written atomically and durably +(`fsutil::atomic_write_durable`: fsynced temp file, rename, fsynced directory, +as durable as the ref write it precedes) by a command that holds the repo lock, +never part of a snapshot, never in a pack, never sent by clone, fetch or push, and not read by `sc gc`. `sc ws` and `sc work` commit through the host repo, so they use the host's record. Its integrity depends on the working-tree path guard (a checkout never writes under @@ -71,13 +73,14 @@ removes the key from the data. A scope is a rule prefix, secret name or branch name, so the repository controls it: every field is escaped with `sanitize_display_line`, and a scope with control characters gets no command at all, only a pointer to `sc protect --list`, `sc secret list` or -`sc branch list`: +`sc branch list` (which, like `sc policy accept` and `forget`, print repository +text through the same escaping): ``` path:secret/sub/ grants a recipient you have not accepted: 3f9a... (UNKNOWN). Accept: sc policy accept path:secret/sub/ --key scl-pk-... --allow-unknown Remove: sc revoke --recipient-id 3f9a... -- secret/sub/ -Nothing was written. +No ref moved and no approval was recorded. ``` Remove is `sc revoke --recipient-id -- `, @@ -93,9 +96,9 @@ carry that copies existing wraps is never gated: |---|---|---| | `protect::encrypt_protected`, the one function that turns a rule's recipients into wraps | `path:` | refuses the whole call, naming every pair | | callers: `snapshot_files` (commit, amend, merge/pick/rebase completion, `sc ws harvest`, `sc work`, `ws refresh`), the clean merge, `replay_commit` (cherry-pick, rebase), `branch_publish` (private-branch protected files) | | inherit it | -| `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit before either ref moves (it advanced the ref before its sealing commit), so a refusal under any rule leaves ref and oplog alone | +| `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit with the named keys staged in memory, records the approvals, and only then moves the refs (it advanced the ref before its sealing commit), so a refusal under any rule leaves refs, oplog and record alone | | `secret_rotate` | `secret:` | refuses on the final recipient set | -| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report) | +| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report). A secret registered under a name other than the one it is sealed under is skipped before it is opened (the registry name would pick the approvals, the sealed name the reseal). The record is read only for an entry that mints a wrap: a secret that opens, a path re-sealed or rotated, or a target with no wrap yet; a randomized path whose every wrap is reused copies them and needs no approval | | `branch_revoke` | `branch:` | refuses on the remaining set | A conflict stop writes plaintext and seals nothing, so it is not gated; its @@ -106,13 +109,13 @@ completion commit is. Only keys the user names on the command line are accepted without asking: `sc protect --to`, `sc grant`, `sc secret add`, `sc secret grant`, `sc secret rotate --to`, `sc branch --private --to` (and the creator's own -key) and `sc branch grant`. The library functions behind them record the keys -they were given, minus any key in the current `[escrow]` (a command appends the -escrow keys to the list it passes in, and those are not the user's choice); the -CLI then records the keys the user named, so a named key that is also escrow -survives its removal from `[escrow]`. `sc secret rotate --to` records from the -CLI because the library cannot tell a named set from one derived from wrap -labels. A key that comes from repository data, by any route, is never +key) and `sc branch grant`. A command passes the keys the user named and the +escrow keys it appends to the library separately (`protect_with_escrow`, +`secret_add_with_escrow`, `branch_private`), and only the named keys are +recorded, before any ref moves, so a named key that is also escrow survives its +removal from `[escrow]` and a failed record write leaves the operation unlanded. +`sc secret rotate --to` records from the CLI, before the rotate, because the +library cannot tell a named set from one derived from wrap labels. A key that comes from repository data, by any route, is never auto-accepted. The local revoke commands remove the pair they revoke, after validation and before the new ref is published, so an interruption leaves a revoke that did not land (retry it), never a landed revoke whose approval From 3ec198ff158ebae65d4cdcd205ca51d043f4bca9 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:06:25 +0200 Subject: [PATCH 08/10] fix(repo): drop the shared staging state, refuse relabeled grants, sync unchanged records protect no longer stages approvals on the Repo handle. snapshot_files_with takes the approval source as a parameter and protect passes the keys it is about to record for that call only, so no other operation on the same handle can see them. snapshot_files keeps its signature and reads the record. secret grant refuses a registry entry sealed under another name before it records an approval or wraps anything, as rotate and rewrap do. rewrap checks a path re-seal against the record only after the ciphertext has opened, so a corrupt blob is skipped as that when the record is unreadable. An accept or forget that changes nothing still fsyncs .sc, so a retry after a failed directory sync cannot report success on an unsynced record. --- crates/repo/src/accepted.rs | 214 ++++++++++++++----- crates/repo/src/protect_ops.rs | 45 ++-- crates/repo/src/repo.rs | 47 +++- crates/repo/src/rewrap.rs | 48 +++-- crates/repo/src/secrets.rs | 11 + docs/THREAT-MODEL.md | 7 +- docs/adr/0059-locally-accepted-recipients.md | 8 +- 7 files changed, 276 insertions(+), 104 deletions(-) diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index 474411a2..75389eb4 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -364,45 +364,10 @@ fn validate_scope(scope: &str) -> Result<()> { } } -/// Approvals a command is validating but has not recorded yet; dropped, they -/// are gone. See [`Repo::stage_approvals`]. -pub(crate) struct StagedApprovals<'a>(&'a Repo); - -impl Drop for StagedApprovals<'_> { - fn drop(&mut self) { - self.0.staged.lock().unwrap().clear(); - } -} - impl Repo { - /// The record as this repo reads it: the file, plus any approvals staged by - /// the running command. + /// The record as this repo reads it. pub(crate) fn accepted(&self) -> Result { - let mut accepted = Accepted::load(&self.layout)?; - for (scope, key) in self.staged.lock().unwrap().iter() { - accepted = match scope { - Some(scope) => accepted.with_named(scope, std::slice::from_ref(key)), - None => accepted.with_escrow(std::slice::from_ref(key)), - }; - } - Ok(accepted) - } - - /// Count `named` as accepted for `scope`, and `escrows` as accepted - /// everywhere, while the returned guard lives, without writing the record. - /// A command that must validate a whole plan (every seal it would make) - /// before it records anything stages the keys it was given, validates, then - /// records the named ones with `accept_keys` and only then moves a ref. - pub(crate) fn stage_approvals( - &self, - scope: &str, - named: &[PublicKey], - escrows: &[PublicKey], - ) -> StagedApprovals<'_> { - let mut staged = self.staged.lock().unwrap(); - staged.extend(named.iter().map(|k| (Some(scope.to_string()), k.clone()))); - staged.extend(escrows.iter().map(|k| (None, k.clone()))); - StagedApprovals(self) + Accepted::load(&self.layout) } /// Record recipients as accepted for `scope` (`sc policy accept`; @@ -434,6 +399,8 @@ impl Repo { pairs.extend(recorded.into_iter().map(|e| (scope.to_string(), e))); if pairs.len() != before { write_pairs(&self.layout, &pairs)?; + } else { + self.sync_unchanged()?; } Ok(()) } @@ -447,6 +414,15 @@ impl Repo { self.accept_recipients(scope, &entries) } + /// A write that changes nothing still has to leave the record durable: an + /// earlier attempt may have renamed the new file and failed before its + /// directory was synced, and a retry then finds the change already in place. + /// Returning success without a sync would let a later durable ref move + /// outlive an approval change that a crash can still lose. + fn sync_unchanged(&self) -> Result<()> { + Ok(scl_core::fsutil::fsync_dir(&self.layout.dot_sc)?) + } + /// Remove every accepted pair of `scope` for this recipient (`sc policy /// forget`, and every local revoke). Returns whether there was one. pub fn forget_recipient(&self, scope: &str, id: &RecipientId) -> Result { @@ -456,6 +432,8 @@ impl Repo { let removed = pairs.len() != before; if removed { write_pairs(&self.layout, &pairs)?; + } else { + self.sync_unchanged()?; } Ok(removed) } @@ -873,10 +851,6 @@ mod tests { record, "the named key was recorded although the plan was refused" ); - assert!( - w.v.staged.lock().unwrap().is_empty(), - "a staged approval outlived the command" - ); assert_eq!(w.v.head_tip().unwrap(), tip, "no ref move"); assert_eq!(w.v.oplog().unwrap().len(), oplog, "no oplog record"); assert!(w @@ -1147,22 +1121,23 @@ mod tests { let _ = std::fs::remove_dir_all(root); } - /// Make `.sc` read-only so the record cannot be written (a read still works) - /// until the guard drops. Refs and objects live in subdirectories, which - /// stay writable: a ref that moved despite the failed record write would - /// show up as a changed tip. + /// Set `.sc` to `mode` until the guard drops. `0o555` makes the record + /// unwritable while it stays readable; refs and objects live in + /// subdirectories, which stay writable, so a ref that moved despite the + /// failed record write would show up as a changed tip. `0o311` leaves it + /// searchable but not openable as a directory, so an fsync of `.sc` fails. #[cfg(unix)] - struct ReadOnlyDotSc(PathBuf); + struct DotScMode(PathBuf); #[cfg(unix)] - impl ReadOnlyDotSc { - fn new(dot_sc: &Path) -> Self { + impl DotScMode { + fn new(dot_sc: &Path, mode: u32) -> Self { use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(dot_sc, std::fs::Permissions::from_mode(0o555)).unwrap(); - ReadOnlyDotSc(dot_sc.to_path_buf()) + std::fs::set_permissions(dot_sc, std::fs::Permissions::from_mode(mode)).unwrap(); + DotScMode(dot_sc.to_path_buf()) } } #[cfg(unix)] - impl Drop for ReadOnlyDotSc { + impl Drop for DotScMode { fn drop(&mut self) { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); @@ -1186,7 +1161,7 @@ mod tests { let tip = repo.head_tip().unwrap(); let emb = crate::refs::read_branch_tip(repo.layout(), "emb").unwrap(); { - let _ro = ReadOnlyDotSc::new(&repo.layout().dot_sc); + let _ro = DotScMode::new(&repo.layout().dot_sc, 0o555); assert!(repo.revoke("p/", &b.recipient_id()).is_err()); assert_eq!(repo.head_tip().unwrap(), tip, "path revoke moved the ref"); assert!(repo.secret_revoke("S", &b.recipient_id()).is_err()); @@ -1232,7 +1207,7 @@ mod tests { let tip = repo.head_tip().unwrap(); let oplog = repo.oplog().unwrap().len(); { - let _ro = ReadOnlyDotSc::new(&repo.layout().dot_sc); + let _ro = DotScMode::new(&repo.layout().dot_sc, 0o555); assert!(repo .protect_with_escrow( "p/", @@ -1545,4 +1520,137 @@ mod tests { drop(repo); let _ = std::fs::remove_dir_all(root); } + + // `secret grant` refuses a registry entry sealed under another name before + // it records an approval or wraps anything, as rotate and rewrap do. + #[test] + fn secret_grant_refuses_a_relabeled_secret() { + let root = dir("grant-relabeled"); + let (sk, pk) = generate_keypair(); + let (_, new) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + let secret = scl_crypto::seal("B", b"value-of-b", std::slice::from_ref(&pk)); + let sid = repo + .vfs() + .store() + .lock() + .unwrap() + .put(Object::Secret(secret)) + .unwrap(); + let root_id = repo.vfs().write_tree(&[]).unwrap(); + let mut secrets = std::collections::BTreeMap::new(); + secrets.insert("A".to_string(), sid); + let tip = repo + .commit_snapshot( + root_id, + vec![], + secrets, + scl_core::Protection::default(), + "w", + "plant", + ) + .unwrap(); + + let err = repo.secret_grant("A", &sk, &new).unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err}"); + assert!(err.to_string().contains("sealed as \"B\""), "{err}"); + assert!( + !repo.layout().accepted_recipients_path().exists(), + "an approval was recorded for a grant that was refused" + ); + assert_eq!(repo.head_tip().unwrap(), Some(tip), "the registry moved"); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // A re-seal checks the approvals after its ciphertext has opened: a corrupt + // blob is skipped as that, and an unreadable record does not abort the run. + #[test] + fn rewrap_skips_a_corrupt_blob_before_it_reads_the_record() { + let root = dir("rewrap-corrupt"); + let (sk, pk) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", std::slice::from_ref(&pk), None).unwrap(); + let tip = repo.head_tip().unwrap().unwrap(); + let snap = repo.snapshot(&tip).unwrap(); + let (bid, mut cipher) = { + let arc = repo.vfs().store(); + let mut store = arc.lock().unwrap(); + let entries = + crate::worktree::tree_file_entries_with_perms(&mut store, snap.root).unwrap(); + let (bid, _, _) = entries["p/x.txt"]; + let Object::Blob(b) = store.get(&bid).unwrap() else { + panic!("not a blob") + }; + (bid, b.to_vec()) + }; + // The wrap still opens; the ciphertext no longer does. + *cipher.last_mut().unwrap() ^= 0xff; + let bad_id = Object::blob(cipher.clone()).id(); + let new_root = repo + .vfs() + .write_tree_with_perms(&[( + "p/x.txt".to_string(), + cipher, + scl_core::FileMode::FILE, + scl_core::PROTECTED | scl_core::RANDOMIZED, + )]) + .unwrap(); + let mut protection = snap.protection.clone(); + let wraps = protection.wrapped[&bid].clone(); + protection.wrapped.insert(bad_id, wraps); + repo.commit_snapshot(new_root, vec![tip], snap.secrets, protection, "w", "x") + .unwrap(); + let record = repo.layout().accepted_recipients_path(); + std::fs::remove_file(&record).unwrap(); + std::fs::create_dir(&record).unwrap(); + + let report = repo + .rewrap_with(&sk, &[], std::slice::from_ref(&pk), false, true) + .unwrap(); + assert_eq!(report.skipped.len(), 1, "{report:?}"); + assert!( + report.skipped[0].1.contains("ciphertext failed to open"), + "{:?}", + report.skipped + ); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // An accept or forget that changes nothing still syncs `.sc`: a retry after + // a failed directory sync must not report success on an unsynced record. + #[cfg(unix)] + #[test] + fn an_unchanged_accept_or_forget_still_syncs_the_directory() { + let root = dir("sync"); + let (_, pk) = generate_keypair(); + let (_, other) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + repo.accept_keys("secret:S", std::slice::from_ref(&pk)) + .unwrap(); + { + let _mode = DotScMode::new(&repo.layout().dot_sc, 0o311); + if std::fs::File::open(&repo.layout().dot_sc).is_ok() { + // Permissions are not enforced here (running as root). + return; + } + let err = repo + .accept_keys("secret:S", std::slice::from_ref(&pk)) + .unwrap_err(); + assert!(matches!(err, Error::Io(_)), "{err}"); + let err = repo + .forget_recipient("secret:S", &other.recipient_id()) + .unwrap_err(); + assert!(matches!(err, Error::Io(_)), "{err}"); + } + repo.accept_keys("secret:S", std::slice::from_ref(&pk)) + .unwrap(); + assert!(!repo + .forget_recipient("secret:S", &other.recipient_id()) + .unwrap()); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } } diff --git a/crates/repo/src/protect_ops.rs b/crates/repo/src/protect_ops.rs index c6c49c84..0242a864 100644 --- a/crates/repo/src/protect_ops.rs +++ b/crates/repo/src/protect_ops.rs @@ -40,9 +40,10 @@ impl Repo { /// [`Repo::protect`] with the keys the user `named` apart from the `escrows` /// a command appends. Both get the rule; only `named` is recorded as /// accepted (escrow counts from `[escrow]` at check time, ADR-0059). The - /// approvals are staged in memory while the whole plan (the rule and the - /// sealing commit) is validated, then recorded, then the refs move, so a - /// refusal leaves the record and the refs as they were. + /// whole plan (the rule and the sealing commit) is validated with `named` + /// and `escrows` counted as accepted for this call only, then `named` is + /// recorded, then the refs move, so a refusal leaves the record and the + /// refs as they were. pub fn protect_with_escrow( &self, prefix: &str, @@ -133,24 +134,28 @@ impl Repo { let files = worktree::read_worktree(&self.layout, &self.tracked_paths()?)?; let mut cache = self.open_protected_cache()?; let message = format!("encrypt under {prefix}"); - let id = { - // The keys it was given count as accepted for this one validation. - let _staged = self.stage_approvals(&scope, named, escrows); - self.snapshot_files( - files, - Some(policy_id), - None, - None, - None, - None, - None, - &self.sparse_spec()?, - &self.layout.root, - Some(&mut cache), - "system", - &message, - )? + // The keys it was given count as accepted for this validation only. + let pending = || { + Ok(self + .accepted()? + .with_named(&scope, named) + .with_escrow(escrows)) }; + let id = self.snapshot_files_with( + files, + Some(policy_id), + None, + None, + None, + None, + None, + &self.sparse_spec()?, + &self.layout.root, + Some(&mut cache), + &pending, + "system", + &message, + )?; // Validated: record the approvals, then move the refs. self.accept_keys(&scope, named)?; crate::refs::write_branch_tip(self.layout(), &head, &policy_id)?; diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index f2685170..5f2c2663 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -62,9 +62,6 @@ pub struct AbortReport { pub struct Repo { pub(crate) layout: Layout, pub(crate) vfs: VfsRepo, - /// Approvals the running command is validating but has not recorded - /// (`Repo::stage_approvals`). - pub(crate) staged: std::sync::Mutex, scl_crypto::PublicKey)>>, _lock: RepoLock, } @@ -128,7 +125,6 @@ impl Repo { Ok(Repo { layout, vfs: VfsRepo::new(store), - staged: std::sync::Mutex::new(Vec::new()), _lock: lock, }) } @@ -332,6 +328,40 @@ impl Repo { Ok(id) } + /// [`Repo::snapshot_files_with`] reading the approvals from the record, which + /// is what every commit-shaped caller wants. + pub(crate) fn snapshot_files( + &self, + files: Vec<(String, Vec, scl_core::FileMode)>, + tip: Option, + merge_head: Option, + pick_head: Option, + decided_root: Option, + pick_registry_base: Option, + parents_override: Option>, + sparse: &crate::sparse::Sparse, + checkout: &Path, + cache: Option<&mut crate::cache::ProtectedCache>, + author: &str, + message: &str, + ) -> Result { + self.snapshot_files_with( + files, + tip, + merge_head, + pick_head, + decided_root, + pick_registry_base, + parents_override, + sparse, + checkout, + cache, + &|| self.accepted(), + author, + message, + ) + } + /// The commit pipeline minus ref movement: split protected/plaintext files, /// scan the plaintext (Err(SecretDetected) on a hit), convergently encrypt /// protected files, carry forward absent still-protected content from @@ -383,7 +413,10 @@ impl Repo { /// `checkout` is the directory `files` was read from (the host root, or a /// workspace's own dir): the case-alias guard asks it whether two /// spellings of a protected path are one file. - pub(crate) fn snapshot_files( + /// `accepted` supplies the approvals the seal gate checks (ADR-0059); it is + /// called only when something is sealed. `protect` passes the keys it is + /// about to record, for this call only. + pub(crate) fn snapshot_files_with( &self, files: Vec<(String, Vec, scl_core::FileMode)>, tip: Option, @@ -395,6 +428,7 @@ impl Repo { sparse: &crate::sparse::Sparse, checkout: &Path, mut cache: Option<&mut crate::cache::ProtectedCache>, + accepted: &dyn Fn() -> Result, author: &str, message: &str, ) -> Result { @@ -691,8 +725,7 @@ impl Repo { } } - let (protected_all, sealed_wrapped) = - crate::protect::encrypt_protected(to_seal, || self.accepted())?; + let (protected_all, sealed_wrapped) = crate::protect::encrypt_protected(to_seal, accepted)?; // Record every freshly sealed path's new blob id into the cache; the // committing caller persists it only after the ref actually moves. if let Some(c) = cache { diff --git a/crates/repo/src/rewrap.rs b/crates/repo/src/rewrap.rs index a745e3d2..894ea038 100644 --- a/crates/repo/src/rewrap.rs +++ b/crates/repo/src/rewrap.rs @@ -284,28 +284,22 @@ impl Repo { // An entry mints a wrap when it is re-sealed under a fresh DEK, or // when a target has no wrap yet. Reusing every existing wrap copies // them and needs no approval, so the record is not read. - let mints_a_wrap = convergent - || rotate - || target_pks.iter().any(|pk| { - !wks.iter() - .any(|w| w.recipient_id == pk.recipient_id().as_str()) - }); - if mints_a_wrap { + let wrap_missing = target_pks.iter().any(|pk| { + !wks.iter() + .any(|w| w.recipient_id == pk.recipient_id().as_str()) + }); + // The record is read at the last moment: a re-seal checks it after + // its ciphertext has opened, so a corrupt blob is skipped as that + // even when the record is unreadable. + let unaccepted = |accepted: &mut Option| -> Result<_> { if accepted.is_none() { - accepted = Some(self.accepted()?.with_escrow(escrows)); + *accepted = Some(self.accepted()?.with_escrow(escrows)); } - let pending = accepted + Ok(accepted .as_ref() .expect("loaded above") - .unaccepted(&scope, &target_pks); - if !pending.is_empty() { - skipped.push(( - format!("path {path}"), - crate::accepted::describe_inline(&pending), - )); - continue; - } - } + .unaccepted(&scope, &target_pks)) + }; if convergent || rotate { // Convergent (pre-P33): eager upgrade. Randomized with // `rotate`: a genuine cutover to a fresh DEK. Either way: @@ -335,6 +329,14 @@ impl Repo { continue; } }; + let pending = unaccepted(&mut accepted)?; + if !pending.is_empty() { + skipped.push(( + format!("path {path}"), + crate::accepted::describe_inline(&pending), + )); + continue; + } if dry_run { if convergent { blobs_resealed += 1; @@ -378,6 +380,16 @@ impl Repo { } continue; } + if wrap_missing { + let pending = unaccepted(&mut accepted)?; + if !pending.is_empty() { + skipped.push(( + format!("path {path}"), + crate::accepted::describe_inline(&pending), + )); + continue; + } + } if dry_run { blobs_rewrapped += 1; continue; diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 58a015cd..c85d34ad 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -175,6 +175,17 @@ impl Repo { _ => return Err(Error::NoSuchSecret(format!("{name} is not a secret"))), } }; + // The AEAD binds the sealed name. An entry registered under another + // name would be approved by the registry name and wrapped as the sealed + // one, so refuse it before recording or wrapping anything, as rotate + // and rewrap do. + if secret.name != name { + return Err(Error::InvalidArgument(format!( + "registry entry {name} points at a secret sealed as {:?}; \ + rotate it with --value instead", + secret.name + ))); + } self.accept_keys( &crate::accepted::secret_scope(name), std::slice::from_ref(new), diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 530ed920..d34ffe2e 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -134,11 +134,12 @@ too, not just the src-control-side metadata. `branch:`; local `[escrow]` keys count in every scope. The gate is `encrypt_protected`, the one function that turns a rule into wraps, plus `sc protect` (it checks the rule it changes, builds its sealing commit with the - named keys staged in memory, records them, then moves the refs), `secret_rotate`, `rewrap` (an entry with an + pending approvals passed to that call's gate only, records them, then moves the + refs), `secret_rotate`, `rewrap` (an entry with an unaccepted key is skipped, the rest commits, the exit code is non-zero) and `branch_revoke`. The record is written durably (fsynced, as durable as the ref - write). `sc rewrap` skips a secret registered under a name other than the one - it is sealed under. The record loads only when something is sealed, so a commit + write). `sc rewrap` skips, and `sc secret grant` refuses, a secret registered under a + name other than the one it is sealed under. The record loads only when something is sealed, so a commit that wraps nothing does not depend on it. Escrow keys are never recorded: they count from the current `[escrow]` section, so removing one withdraws it. A scope in a refusal comes from the repository, so it is escaped and a scope diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md index 770f5519..d2bd49c9 100644 --- a/docs/adr/0059-locally-accepted-recipients.md +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -49,7 +49,9 @@ accepted in every scope. It is local state like `.sc/local-key`: written atomically and durably (`fsutil::atomic_write_durable`: fsynced temp file, rename, fsynced directory, -as durable as the ref write it precedes) by a command that holds the repo lock, +as durable as the ref write it precedes; an accept or forget that changes +nothing still syncs the directory, so a retry after a failed sync does not report +success on an unsynced record) by a command that holds the repo lock, never part of a snapshot, never in a pack, never sent by clone, fetch or push, and not read by `sc gc`. `sc ws` and `sc work` commit through the host repo, so they use the host's record. Its @@ -96,9 +98,9 @@ carry that copies existing wraps is never gated: |---|---|---| | `protect::encrypt_protected`, the one function that turns a rule's recipients into wraps | `path:` | refuses the whole call, naming every pair | | callers: `snapshot_files` (commit, amend, merge/pick/rebase completion, `sc ws harvest`, `sc work`, `ws refresh`), the clean merge, `replay_commit` (cherry-pick, rebase), `branch_publish` (private-branch protected files) | | inherit it | -| `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit with the named keys staged in memory, records the approvals, and only then moves the refs (it advanced the ref before its sealing commit), so a refusal under any rule leaves refs, oplog and record alone | +| `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit with the pending approvals passed to that call's seal gate only (no state shared with other operations on the handle), records them, and only then moves the refs (it advanced the ref before its sealing commit), so a refusal under any rule leaves refs, oplog and record alone | | `secret_rotate` | `secret:` | refuses on the final recipient set | -| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report). A secret registered under a name other than the one it is sealed under is skipped before it is opened (the registry name would pick the approvals, the sealed name the reseal). The record is read only for an entry that mints a wrap: a secret that opens, a path re-sealed or rotated, or a target with no wrap yet; a randomized path whose every wrap is reused copies them and needs no approval | +| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report). A secret registered under a name other than the one it is sealed under is skipped before it is opened (the registry name would pick the approvals, the sealed name the reseal); `secret grant` and `secret rotate` refuse it the same way. The record is read only for an entry that mints a wrap, and for a re-seal only after its ciphertext has opened (a corrupt blob is skipped as that whatever the record's state): a secret that opens, a path re-sealed or rotated, or a target with no wrap yet; a randomized path whose every wrap is reused copies them and needs no approval | | `branch_revoke` | `branch:` | refuses on the remaining set | A conflict stop writes plaintext and seals nothing, so it is not gated; its From e7dc8e5d8f757657bfdb7c79507e8e88975a92d5 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:25:41 +0200 Subject: [PATCH 09/10] fix(repo): authenticate a grant's secret, record approvals after authorization, lock the record secret grant opens the secret with the identity before it records or wraps anything. The registry key and the name in the secret's metadata are both repository data and can be made to agree, but the AEAD binds the name the secret was sealed under, so an edited name fails to open and the grant is refused. grant, secret grant and secret rotate --to record the named key only after the identity is authorized and the operation validated, still before the ref moves. secret_rotate_with takes the named keys as call-local approvals, and the CLI passes them instead of recording first, so a refused command leaves no approval. accept and forget read, change and write the record under .sc/index.lock, so callers on one handle cannot lose each other's change. ADR-0059 records the declined residual: an interruption after the approval write and before the ref move leaves an approval for a key the user named on that command. --- crates/cli/src/main.rs | 18 +- crates/repo/src/accepted.rs | 172 +++++++++++++++++-- crates/repo/src/protect_ops.rs | 11 +- crates/repo/src/secrets.rs | 48 +++++- docs/THREAT-MODEL.md | 6 +- docs/adr/0059-locally-accepted-recipients.md | 20 ++- 6 files changed, 228 insertions(+), 47 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 11565576..368888f7 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3349,6 +3349,7 @@ fn run_secret(op: SecretOp) -> Result<()> { let dir = load_recipients(&recipients_path)?; let escrows = load_escrows(&recipients_path)?; // Recipient set: explicit --to, else the secret's current recipients. + let mut named: Vec = Vec::new(); let pks = if to.is_empty() { let ids = repo.secret_recipients(&name)?; // Pool = named recipients + escrow, so an escrow-only id resolves. @@ -3356,13 +3357,14 @@ fn run_secret(op: SecretOp) -> Result<()> { pool.extend(escrows.iter().cloned()); resolve_ids_to_pubkeys(&ids, &pool)? } else { - // Named on the command line, so accepted for this secret. The - // derived set above is not: it comes from the secret's own - // wrap labels, and `secret_rotate` refuses one with a key - // this clone never accepted. - let named = resolve_names(&dir, &to)?; - repo.accept_keys(&format!("secret:{name}"), &named)?; - named + // Named on the command line, so accepted for this secret, but + // recorded by `secret_rotate_with` only once the rotate has + // validated (a refused command records nothing). The derived + // set above is not: it comes from the secret's own wrap labels, + // and `secret_rotate_with` refuses one with a key this clone + // never accepted. + named = resolve_names(&dir, &to)?; + named.clone() }; let pks = append_escrow(pks, &escrows); let new_value = value.as_deref().map(|s| s.as_bytes()); @@ -3370,7 +3372,7 @@ fn run_secret(op: SecretOp) -> Result<()> { Some(_) => None, // sealing a new value needs no decryption None => Some(load_identity(identity)?), }; - repo.secret_rotate(&name, new_value, &pks, identity.as_ref())?; + repo.secret_rotate_with(&name, new_value, &pks, &named, identity.as_ref())?; println!("rotated secret {name} for {} recipient(s)", pks.len()); eprintln!( "note: rotation cuts off future reads via the current registry; the old \ diff --git a/crates/repo/src/accepted.rs b/crates/repo/src/accepted.rs index 75389eb4..bc432e16 100644 --- a/crates/repo/src/accepted.rs +++ b/crates/repo/src/accepted.rs @@ -394,15 +394,18 @@ impl Repo { (false, _) => id.to_string(), }); } - let mut pairs = read_pairs(&self.layout)?; - let before = pairs.len(); - pairs.extend(recorded.into_iter().map(|e| (scope.to_string(), e))); - if pairs.len() != before { - write_pairs(&self.layout, &pairs)?; - } else { - self.sync_unchanged()?; - } - Ok(()) + // Read, change and write under one lock, or two callers on this handle + // could each read the old record and one change would be lost. + crate::lock::with_index_lock(&self.layout, || { + let mut pairs = read_pairs(&self.layout)?; + let before = pairs.len(); + pairs.extend(recorded.into_iter().map(|e| (scope.to_string(), e))); + if pairs.len() != before { + write_pairs(&self.layout, &pairs) + } else { + self.sync_unchanged() + } + }) } /// [`Repo::accept_recipients`] for keys the user named on the command line. @@ -426,16 +429,18 @@ impl Repo { /// Remove every accepted pair of `scope` for this recipient (`sc policy /// forget`, and every local revoke). Returns whether there was one. pub fn forget_recipient(&self, scope: &str, id: &RecipientId) -> Result { - let mut pairs = read_pairs(&self.layout)?; - let before = pairs.len(); - pairs.retain(|(s, e)| s != scope || entry_id(s, e).as_ref() != Some(id)); - let removed = pairs.len() != before; - if removed { - write_pairs(&self.layout, &pairs)?; - } else { - self.sync_unchanged()?; - } - Ok(removed) + crate::lock::with_index_lock(&self.layout, || { + let mut pairs = read_pairs(&self.layout)?; + let before = pairs.len(); + pairs.retain(|(s, e)| s != scope || entry_id(s, e).as_ref() != Some(id)); + let removed = pairs.len() != before; + if removed { + write_pairs(&self.layout, &pairs)?; + } else { + self.sync_unchanged()?; + } + Ok(removed) + }) } } @@ -1653,4 +1658,133 @@ mod tests { drop(repo); let _ = std::fs::remove_dir_all(root); } + + // Two names the repository controls can be made to agree: the metadata name + // of a secret sealed under another name is edited to match the registry. + // The AEAD still binds the name it was sealed under, so `secret grant`, + // which opens the secret with the identity, refuses it. + #[test] + fn secret_grant_refuses_a_secret_whose_name_metadata_was_edited() { + let root = dir("grant-edited"); + let (sk, pk) = generate_keypair(); + let (_, new) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + let mut secret = scl_crypto::seal("B", b"value-of-b", std::slice::from_ref(&pk)); + secret.name = "A".to_string(); + let sid = repo + .vfs() + .store() + .lock() + .unwrap() + .put(Object::Secret(secret)) + .unwrap(); + let root_id = repo.vfs().write_tree(&[]).unwrap(); + let mut secrets = std::collections::BTreeMap::new(); + secrets.insert("A".to_string(), sid); + let tip = repo + .commit_snapshot( + root_id, + vec![], + secrets, + scl_core::Protection::default(), + "w", + "plant", + ) + .unwrap(); + + let err = repo.secret_grant("A", &sk, &new).unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err}"); + assert!( + err.to_string().contains("does not open under that name"), + "{err}" + ); + assert!(!repo.layout().accepted_recipients_path().exists()); + assert_eq!(repo.head_tip().unwrap(), Some(tip), "the registry moved"); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // A refused grant or rotate leaves the record alone: the named key is + // recorded only after the identity is authorized and the operation validated. + #[test] + fn a_refused_grant_or_rotate_records_no_approval() { + let root = dir("refused-approval"); + let (sk, a) = generate_keypair(); + let (wrong, _) = generate_keypair(); + let (_, new) = generate_keypair(); + let repo = Repo::init(&root).unwrap(); + put(&root, "p/x.txt", "x\n"); + repo.protect("p/", std::slice::from_ref(&a), None).unwrap(); + repo.secret_add("S", b"v", std::slice::from_ref(&a)) + .unwrap(); + let record = || std::fs::read(repo.layout().accepted_recipients_path()).unwrap(); + let before = record(); + + assert!(matches!( + repo.grant("p/", &wrong, &new).unwrap_err(), + Error::NotAuthorized(_) + )); + assert_eq!( + record(), + before, + "a refused path grant recorded an approval" + ); + assert!(repo.secret_grant("S", &wrong, &new).is_err()); + assert_eq!( + record(), + before, + "a refused secret grant recorded an approval" + ); + let both = [a.clone(), new.clone()]; + assert!(repo + .secret_rotate_with("S", None, &both, std::slice::from_ref(&new), Some(&wrong)) + .is_err()); + assert_eq!(record(), before, "a refused rotate recorded an approval"); + assert!(repo + .secret_rotate_with("NOPE", None, &both, std::slice::from_ref(&new), Some(&sk)) + .is_err()); + assert_eq!(record(), before, "a rotate of nothing recorded an approval"); + + // With the right identity each lands and records the named key. + repo.grant("p/", &sk, &new).unwrap(); + repo.secret_grant("S", &sk, &new).unwrap(); + let acc = repo.accepted().unwrap(); + for scope in ["path:p/", "secret:S"] { + assert!(acc.unaccepted(scope, std::slice::from_ref(&new)).is_empty()); + } + let (_, third) = generate_keypair(); + let set = [a.clone(), new.clone(), third.clone()]; + repo.secret_rotate_with("S", None, &set, std::slice::from_ref(&third), Some(&sk)) + .unwrap(); + assert!(repo + .accepted() + .unwrap() + .unaccepted("secret:S", std::slice::from_ref(&third)) + .is_empty()); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } + + // The record is read, changed and written under one lock: callers on one + // handle cannot lose each other's change. + #[test] + fn concurrent_accepts_on_one_handle_all_land() { + let root = dir("concurrent"); + let repo = Repo::init(&root).unwrap(); + let keys: Vec = (0..32).map(|_| generate_keypair().1).collect(); + std::thread::scope(|s| { + for chunk in keys.chunks(8) { + let repo = &repo; + s.spawn(move || { + for k in chunk { + repo.accept_keys("secret:S", std::slice::from_ref(k)) + .unwrap(); + } + }); + } + }); + assert_eq!(repo.accepted().unwrap().pairs.len(), keys.len()); + drop(repo); + let _ = std::fs::remove_dir_all(root); + } } diff --git a/crates/repo/src/protect_ops.rs b/crates/repo/src/protect_ops.rs index 0242a864..f2fa3af7 100644 --- a/crates/repo/src/protect_ops.rs +++ b/crates/repo/src/protect_ops.rs @@ -237,11 +237,6 @@ impl Repo { .position(|p| p.prefix == prefix) .ok_or_else(|| Error::NotProtected(prefix.to_string()))?; - // The caller named `new`, so it is accepted for this prefix. - self.accept_keys( - &crate::accepted::path_scope(prefix), - std::slice::from_ref(new), - )?; let protected_ids = self.protected_blob_ids_under(root, &protection, prefix)?; let authorized_id = authorized.public().recipient_id().to_string(); let new_id = new.recipient_id().to_string(); @@ -270,6 +265,12 @@ impl Repo { .push(new_wk); } + // Every unwrap above authorized the identity: only now is the named key + // recorded, before the ref moves. + self.accept_keys( + &crate::accepted::path_scope(prefix), + std::slice::from_ref(new), + )?; let rule = &mut protection.prefixes[rule_idx]; let epoch = rule.next_epoch(); rule.set_standing(new.to_bytes(), epoch, scl_core::RecipientState::Granted); diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index c85d34ad..26a81c65 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -175,10 +175,11 @@ impl Repo { _ => return Err(Error::NoSuchSecret(format!("{name} is not a secret"))), } }; - // The AEAD binds the sealed name. An entry registered under another - // name would be approved by the registry name and wrapped as the sealed - // one, so refuse it before recording or wrapping anything, as rotate - // and rewrap do. + // The AEAD binds the sealed name. Two names the repository controls + // (the registry key and the one in the secret's metadata) can be made + // to agree, so also open the secret with the identity: it opens only if + // it was really sealed under that name. Refuse before recording or + // wrapping anything, as rotate and rewrap do. if secret.name != name { return Err(Error::InvalidArgument(format!( "registry entry {name} points at a secret sealed as {:?}; \ @@ -186,11 +187,23 @@ impl Repo { secret.name ))); } + match scl_crypto::open(&secret, authorized) { + Ok(_) => {} + Err(scl_crypto::Error::Decrypt) => { + return Err(Error::InvalidArgument(format!( + "registry entry {name} does not open under that name (it was sealed \ + under another name, or is corrupt); rotate it with --value instead" + ))) + } + Err(e) => return Err(e.into()), + } + let regranted = scl_crypto::rewrap_for(&secret, authorized, new)?; + // The identity is authorized and the secret is sound: only now is the + // named key recorded, before the ref moves. self.accept_keys( &crate::accepted::secret_scope(name), std::slice::from_ref(new), )?; - let regranted = scl_crypto::rewrap_for(&secret, authorized, new)?; let new_id = { let arc = self.store_arc(); let i = arc.lock().unwrap().put(Object::Secret(regranted))?; @@ -271,6 +284,22 @@ impl Repo { new_value: Option<&[u8]>, recipients: &[PublicKey], identity: Option<&SecretKey>, + ) -> Result { + self.secret_rotate_with(name, new_value, recipients, &[], identity) + } + + /// [`Repo::secret_rotate`] for a recipient set the user partly `named` on + /// the command line. The named keys count as accepted for this call only, + /// and are recorded once the secret has been found, opened (or the value + /// supplied) and the set checked, just before the ref moves. A refused + /// command records nothing. + pub fn secret_rotate_with( + &self, + name: &str, + new_value: Option<&[u8]>, + recipients: &[PublicKey], + named: &[PublicKey], + identity: Option<&SecretKey>, ) -> Result { self.refuse_on_private("sc secret rotate")?; // P21: same in-progress guard as `secret_add` — see its comment. @@ -285,10 +314,12 @@ impl Repo { } require_recipients(recipients)?; // The set may come from the secret's own wrap labels (repository - // data), so every key must be accepted for it (ADR-0059). A caller - // that named the keys accepts them first (`accept_keys`). + // data), so every key must be accepted for it (ADR-0059): by the record, + // by escrow, or by being named in this very call. + let scope = crate::accepted::secret_scope(name); self.accepted()? - .require(&crate::accepted::secret_scope(name), recipients)?; + .with_named(&scope, named) + .require(&scope, recipients)?; let mut reg = self.registry()?; let sid = *reg .get(name) @@ -327,6 +358,7 @@ impl Repo { } }; + self.accept_keys(&scope, named)?; let sealed = scl_crypto::seal(name, plaintext, recipients); let new_id = { let arc = self.store_arc(); diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index d34ffe2e..861fb7d2 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -139,7 +139,11 @@ too, not just the src-control-side metadata. unaccepted key is skipped, the rest commits, the exit code is non-zero) and `branch_revoke`. The record is written durably (fsynced, as durable as the ref write). `sc rewrap` skips, and `sc secret grant` refuses, a secret registered under a - name other than the one it is sealed under. The record loads only when something is sealed, so a commit + name other than the one it is sealed under (grant also opens the secret with the + identity, since the AEAD binds the sealed name and the metadata name can be edited). + The named key of a grant or rotate is recorded only after the identity is + authorized. An interruption after the approval write and before the ref move can + leave an approval for a key the user named on that command (accepted). The record loads only when something is sealed, so a commit that wraps nothing does not depend on it. Escrow keys are never recorded: they count from the current `[escrow]` section, so removing one withdraws it. A scope in a refusal comes from the repository, so it is escaped and a scope diff --git a/docs/adr/0059-locally-accepted-recipients.md b/docs/adr/0059-locally-accepted-recipients.md index d2bd49c9..73abc9b5 100644 --- a/docs/adr/0059-locally-accepted-recipients.md +++ b/docs/adr/0059-locally-accepted-recipients.md @@ -51,8 +51,9 @@ It is local state like `.sc/local-key`: written atomically and durably (`fsutil::atomic_write_durable`: fsynced temp file, rename, fsynced directory, as durable as the ref write it precedes; an accept or forget that changes nothing still syncs the directory, so a retry after a failed sync does not report -success on an unsynced record) by a command that holds the repo lock, -never part of a snapshot, never +success on an unsynced record) by a command that holds the repo lock and +reads, changes and writes the record under the short `.sc/index.lock` (so callers +on one handle cannot lose each other's change), never part of a snapshot, never in a pack, never sent by clone, fetch or push, and not read by `sc gc`. `sc ws` and `sc work` commit through the host repo, so they use the host's record. Its integrity depends on the working-tree path guard (a checkout never writes under @@ -100,7 +101,7 @@ carry that copies existing wraps is never gated: | callers: `snapshot_files` (commit, amend, merge/pick/rebase completion, `sc ws harvest`, `sc work`, `ws refresh`), the clean merge, `replay_commit` (cherry-pick, rebase), `branch_publish` (private-branch protected files) | | inherit it | | `sc protect` | `path:` | validates the candidate rule before anything moves (even with nothing to seal), then builds the rule's snapshot and the sealing commit with the pending approvals passed to that call's seal gate only (no state shared with other operations on the handle), records them, and only then moves the refs (it advanced the ref before its sealing commit), so a refusal under any rule leaves refs, oplog and record alone | | `secret_rotate` | `secret:` | refuses on the final recipient set | -| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report). A secret registered under a name other than the one it is sealed under is skipped before it is opened (the registry name would pick the approvals, the sealed name the reseal); `secret grant` and `secret rotate` refuse it the same way. The record is read only for an entry that mints a wrap, and for a re-seal only after its ciphertext has opened (a corrupt blob is skipped as that whatever the record's state): a secret that opens, a path re-sealed or rotated, or a target with no wrap yet; a randomized path whose every wrap is reused copies them and needs no approval | +| `rewrap` (secrets and protected paths) | `secret:`, `path:` | an entry with an unaccepted key is skipped and reported, the rest is committed, the exit code is non-zero (ADR-0027 skip-and-report). A secret registered under a name other than the one it is sealed under is skipped before it is opened (the registry name would pick the approvals, the sealed name the reseal); `secret grant` and `secret rotate` refuse it the same way, and `secret grant` also opens the secret with the identity, because two names the repository controls can be made to agree and only the AEAD binds the name the secret was sealed under. The record is read only for an entry that mints a wrap, and for a re-seal only after its ciphertext has opened (a corrupt blob is skipped as that whatever the record's state): a secret that opens, a path re-sealed or rotated, or a target with no wrap yet; a randomized path whose every wrap is reused copies them and needs no approval | | `branch_revoke` | `branch:` | refuses on the remaining set | A conflict stop writes plaintext and seals nothing, so it is not gated; its @@ -116,9 +117,12 @@ escrow keys it appends to the library separately (`protect_with_escrow`, `secret_add_with_escrow`, `branch_private`), and only the named keys are recorded, before any ref moves, so a named key that is also escrow survives its removal from `[escrow]` and a failed record write leaves the operation unlanded. -`sc secret rotate --to` records from the CLI, before the rotate, because the -library cannot tell a named set from one derived from wrap labels. A key that comes from repository data, by any route, is never -auto-accepted. The local revoke commands remove the pair they revoke, after +`sc secret rotate --to` passes its named keys to `secret_rotate_with`, because +the library cannot tell a named set from one derived from wrap labels. The named +key of `grant`, `secret grant` and `secret rotate --to` is recorded only after the +identity is authorized and the operation validated, still before the ref moves, +so a refused command leaves no approval. A key that comes from repository data, +by any route, is never auto-accepted. The local revoke commands remove the pair they revoke, after validation and before the new ref is published, so an interruption leaves a revoke that did not land (retry it), never a landed revoke whose approval outlives it. @@ -194,6 +198,10 @@ stays 6. keys; the cure is to revoke or accept, never silent. - **`sc policy status` and `--all`** (list the record, accept every pending pair) are not built. +- **An interruption after the approval write and before the ref move leaves an + approval.** It is for a key the user named on that very command, so it + reflects their own choice in this clone; journaling the pair with the ref move + is out of proportion. - **The printed Remove command does not always work.** `sc revoke` refuses to revoke a rule's last recipient (the attacker's own narrower rule: run `sc grant --to ` first) and refuses while a merge, pick or From 8ec36dffc40bd9ee5bc2bd6ed689515173c735ce Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 13:35:44 +0200 Subject: [PATCH 10/10] fix(cli): sc protect --list exits quietly on a closed pipe --- crates/cli/src/main.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 368888f7..c18fe37e 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -4818,13 +4818,14 @@ fn run_protect(prefix: Option, to: Vec, list: bool, json: bool) for (p, recips) in prefixes { let granted = recips.iter().filter(|r| r.granted).count(); // A rule prefix comes from the repository. - println!( + // `print_line` exits quietly when the reader closes the pipe (`| grep -q`). + print_line(&format!( "{} ({granted} granted)", scl_core::sanitize_display_line(&p) - ); + )); for r in recips { let state = if r.granted { "granted" } else { "REVOKED" }; - println!(" {} {}@e{}", r.id.as_str(), state, r.epoch); + print_line(&format!(" {} {}@e{}", r.id.as_str(), state, r.epoch)); } } return Ok(());