From f380785b63517601caa5707a83b0969c2df66748 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:15:41 +0200 Subject: [PATCH 1/6] fix(secrets): validate secret names at add and injection The secret registry is repository data and secret_add needs no key, so a writer could register a secret sealed to a victim under LD_PRELOAD, PATH, NODE_OPTIONS and similar, and sc run would inject it into the child. The registry key was also never compared with the name the secret was sealed under, so one value could be served under another name. One rule in secrets.rs: [A-Za-z_][A-Za-z0-9_]*, minus a deny list of loader and program-selection variables and the LD_, DYLD_, GIT_CONFIG and SC_ prefixes. secret_add refuses a failing name. secret_values, which every injecting path goes through (sc run, --secrets-fd, sc ws run --with-secrets, sc work --with-secrets), refuses the whole run before decrypting anything when a key fails the rule or differs from the sealed name. THREAT-MODEL records the residual: a writer can still replace the value of an allowed name. The rewrap tests and demo used db-pass and api-key, which the rule refuses; they are now DB_PASS and API_KEY. --- CLAUDE.md | 2 +- crates/repo/src/rewrap.rs | 8 +- crates/repo/src/secrets.rs | 188 ++++++++++++++++++++++++++++++++++++- demo/run_rewrap_demo.sh | 20 ++-- docs/THREAT-MODEL.md | 14 +++ 5 files changed, 214 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b2d40e57..8ad9200b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -120,7 +120,7 @@ the code, those win. | Phase | Current state | ADR | |---|---|---| | P1 | In-RAM copy-on-write virtual worktrees; bounded blob budget + LRU eviction, optional spill; zero disk residue | [0005](docs/adr/0005-in-ram-vfs-over-fuse.md), [0006](docs/adr/0006-memory-budget-and-eviction.md) | -| P2 | Committed secrets: per-secret DEK (XChaCha20-Poly1305) wrapped per X25519 recipient; secrets are env vars, never files — `checkout` never materializes them; `sc run` injects into a child env, or onto a descriptor with `--secrets-fd N` (unix) | [0008](docs/adr/0008-committed-secrets-envelope-encryption.md), [0009](docs/adr/0009-key-management-and-authorization.md), [0010](docs/adr/0010-secret-registry-and-opaque-wrapped-dek.md), [0052](docs/adr/0052-secret-injection-by-fd.md) | +| P2 | Committed secrets: per-secret DEK (XChaCha20-Poly1305) wrapped per X25519 recipient; secrets are env vars, never files — `checkout` never materializes them; names are `[A-Za-z_][A-Za-z0-9_]*` minus loader/PATH/`SC_` variables, enforced at add and again at injection (a registry key must equal the sealed name); `sc run` injects into a child env, or onto a descriptor with `--secrets-fd N` (unix) | [0008](docs/adr/0008-committed-secrets-envelope-encryption.md), [0009](docs/adr/0009-key-management-and-authorization.md), [0010](docs/adr/0010-secret-registry-and-opaque-wrapped-dek.md), [0052](docs/adr/0052-secret-injection-by-fd.md) | | P3 | Persistent `.sc/` repo: loose objects, branches, symbolic HEAD, single-writer lock, working tree; write-out paths restore the recorded executable bit (unix; #242; special bits are always cleared, `sc resolve` restores the chosen side's mode, and a swallowed chmod warns once; #243) | [0011](docs/adr/0011-persistent-store-and-working-tree.md) | | P4 | Snapshot-DAG three-way merge; ff when possible; conflict markers + `.theirs` sidecars | [0012](docs/adr/0012-three-way-merge.md) | | P5 | Commit-time secret scanner (pattern + entropy) hard-rejects plaintext secrets; `sc scan` preview; hash-scoped allowlist | [0017](docs/adr/0017-secret-scanner.md) | diff --git a/crates/repo/src/rewrap.rs b/crates/repo/src/rewrap.rs index ae2cfeda..02cab7b9 100644 --- a/crates/repo/src/rewrap.rs +++ b/crates/repo/src/rewrap.rs @@ -20,7 +20,7 @@ pub struct RewrapReport { /// Already-randomized protected blobs re-sealed under a fresh DEK because /// the run asked to rotate (`rewrap_with` / `sc rewrap --rotate`). pub blobs_rotated: usize, - /// (entry label e.g. "secret db-pass" / "path secret/db.txt", reason) + /// (entry label e.g. "secret DB_PASS" / "path secret/db.txt", reason) pub skipped: Vec<(String, String)>, /// The commit id; None on --dry-run or when nothing needed rewrapping. pub commit: Option, @@ -470,9 +470,9 @@ mod tests { let repo = Repo::init(&root).unwrap(); let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); let (_esc_sk, esc_pk) = scl_crypto::generate_keypair(); - repo.secret_add("db-pass", b"hunter2", std::slice::from_ref(&alice_pk)) + repo.secret_add("DB_PASS", b"hunter2", std::slice::from_ref(&alice_pk)) .unwrap(); - repo.secret_add("api-key", b"tok", std::slice::from_ref(&alice_pk)) + repo.secret_add("API_KEY", b"tok", std::slice::from_ref(&alice_pk)) .unwrap(); let tip_before = repo.head_tip().unwrap().unwrap(); @@ -491,7 +491,7 @@ mod tests { // ONE commit: new tip's sole parent is the old tip. assert_eq!(repo.snapshot(&commit).unwrap().parents, vec![tip_before]); // Both secrets now sealed to alice + escrow. - for name in ["db-pass", "api-key"] { + for name in ["DB_PASS", "API_KEY"] { let rids = repo.secret_recipients(name).unwrap(); assert_eq!(rids.len(), 2, "{name} must gain the escrow key"); assert!(rids.contains(&esc_pk.recipient_id())); diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index e4850a51..0e40eb3f 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -105,6 +105,7 @@ impl Repo { if crate::rebase_state::in_progress(self.layout()) { return Err(Error::RebaseInProgress); } + check_secret_name(name)?; require_recipients(recipients)?; let secret = scl_crypto::seal(name, value, recipients); let id = { @@ -370,9 +371,12 @@ impl Repo { identity: &SecretKey, strict: bool, ) -> Result>)>> { - let reg = self.registry()?; - let mut out = Vec::new(); - for (name, id) in reg { + // The registry is repository data any writer can edit, so nothing is + // decrypted until every entry has a name that may be injected and + // points at a secret sealed under that same name. + let mut entries = Vec::new(); + for (name, id) in self.registry()? { + check_secret_name(&name)?; let obj = { let arc = self.store_arc(); let o = arc.lock().unwrap().get(&id)?; @@ -382,6 +386,18 @@ impl Repo { Object::Secret(s) => s, _ => continue, }; + // The AEAD binds `secret.name`; without this check a value sealed + // as `B` could be served under the registry key `A`. + if secret.name != name { + return Err(Error::InvalidArgument(format!( + "registry entry {name} points at a secret sealed as {:?}; refusing to run", + secret.name + ))); + } + entries.push((name, secret)); + } + let mut out = Vec::new(); + for (name, secret) in entries { match scl_crypto::open(&secret, identity) { // Pin the type explicitly: if `scl_crypto::open` ever stops // returning `Zeroizing>`, this line fails to compile. @@ -635,6 +651,80 @@ fn feed_pipe( } } +/// Variables that change how a process loads code or which program runs; a +/// secret may not be registered or injected under one of these names. +const DENIED_NAMES: &[&str] = &[ + "PATH", + "IFS", + "ENV", + "BASH_ENV", + "SHELLOPTS", + "BASHOPTS", + "PS4", + "PROMPT_COMMAND", + "NODE_OPTIONS", + "NODE_PATH", + "PYTHONPATH", + "PYTHONHOME", + "PYTHONSTARTUP", + "PYTHONINSPECT", + "PYTHONUSERBASE", + "PERL5OPT", + "PERL5LIB", + "PERLLIB", + "RUBYOPT", + "RUBYLIB", + "JAVA_TOOL_OPTIONS", + "_JAVA_OPTIONS", + "JDK_JAVA_OPTIONS", + "CLASSPATH", + "GIT_SSH", + "GIT_SSH_COMMAND", + "GIT_EXEC_PATH", + "GIT_ASKPASS", + "SSH_ASKPASS", + "EDITOR", + "VISUAL", + "PAGER", + "HOME", + "SHELL", + "TMPDIR", +]; + +/// Prefixes denied for the same reason, plus `SC_` (sc's own knobs, such as +/// `SC_SSH` and `SC_GIT`). +const DENIED_PREFIXES: &[&str] = &["LD_", "DYLD_", "GIT_CONFIG", "SC_"]; + +/// The one secret-name rule: `[A-Za-z_][A-Za-z0-9_]*`, and not a variable that +/// changes how the child loads code or which program it runs. Applied when a +/// secret is added and again at injection, because the registry is repository +/// data a writer can edit without any key (THREAT-MODEL, committed secrets). +/// Matching is case-sensitive, except on Windows where environment variable +/// names are not. +pub(crate) fn check_secret_name(name: &str) -> Result<()> { + let mut chars = name.chars(); + let shape_ok = chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); + let key = if cfg!(windows) { + name.to_ascii_uppercase() + } else { + name.to_string() + }; + if !shape_ok + || DENIED_NAMES.contains(&key.as_str()) + || DENIED_PREFIXES.iter().any(|p| key.starts_with(p)) + { + return Err(Error::InvalidArgument(format!( + "secret name {name:?} is not allowed: use [A-Za-z_][A-Za-z0-9_]* and not a \ + variable that changes how a process loads code or which program runs \ + (PATH, LD_*, DYLD_*, NODE_OPTIONS, GIT_CONFIG*, SC_*, ...)" + ))); + } + Ok(()) +} + /// Refuse an empty recipient set on every seal/wrap path (`secret_add`, /// `secret_rotate`, `protect`): sealing to nobody silently mints a value that /// can never be decrypted — always a caller mistake, never intent. @@ -1028,6 +1118,98 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// Plant `name -> secret sealed as `sealed_as`` in the registry the way a + /// writer without any key can: through the store, bypassing `secret_add`. + fn plant(repo: &Repo, name: &str, sealed_as: &str, value: &[u8], pk: &PublicKey) { + let secret = scl_crypto::seal(sealed_as, value, std::slice::from_ref(pk)); + let id = repo + .store() + .lock() + .unwrap() + .put(Object::Secret(secret)) + .unwrap(); + let mut reg = repo.registry().unwrap(); + reg.insert(name.to_string(), id); + repo.commit_registry(reg, "mallory", "plant", "plant") + .unwrap(); + } + + #[test] + fn secret_add_enforces_the_name_rule() { + let root = tmp_root("name-rule"); + let (_sk, pk) = scl_crypto::generate_keypair(); + let repo = Repo::init(&root).unwrap(); + for bad in [ + "LD_PRELOAD", + "DYLD_INSERT_LIBRARIES", + "PATH", + "NODE_OPTIONS", + "GIT_CONFIG_COUNT", + "SC_GIT", + "a-b", + "1X", + "", + "A=B", + ] { + assert!( + matches!( + repo.secret_add(bad, b"v", std::slice::from_ref(&pk)), + Err(Error::InvalidArgument(_)) + ), + "{bad:?} must be refused" + ); + } + assert!(repo.registry().unwrap().is_empty()); + repo.secret_add("DATABASE_URL", b"v", std::slice::from_ref(&pk)) + .unwrap(); + repo.secret_add("_x9", b"v", std::slice::from_ref(&pk)) + .unwrap(); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn injection_refuses_a_planted_denied_name_and_starts_no_child() { + let root = tmp_root("planted"); + let (sk, pk) = scl_crypto::generate_keypair(); + let repo = Repo::init(&root).unwrap(); + repo.secret_add("DB_URL", b"v", std::slice::from_ref(&pk)) + .unwrap(); + plant(&repo, "LD_PRELOAD", "LD_PRELOAD", b"/tmp/evil.so", &pk); + + let marker = root.join("child-ran"); + let cmd = [ + "sh".to_string(), + "-c".to_string(), + format!("touch {}", marker.display()), + ]; + let err = repo.run(&sk, &cmd).unwrap_err(); + assert!(err.to_string().contains("LD_PRELOAD"), "{err}"); + assert!(!marker.exists(), "no child may start"); + assert!(repo.secret_values(&sk, false).is_err()); + assert!(repo.secret_env(&sk, true).is_err()); + #[cfg(unix)] + { + assert!(repo.run_with_secrets_fd(&sk, &cmd, 3).is_err()); + assert!(!marker.exists(), "no child may start (fd mode)"); + } + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn injection_refuses_a_registry_key_that_differs_from_the_sealed_name() { + let root = tmp_root("relabel"); + let (sk, pk) = scl_crypto::generate_keypair(); + let repo = Repo::init(&root).unwrap(); + plant(&repo, "A", "B", b"value-of-b", &pk); + let err = repo.secret_values(&sk, false).unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err}"); + assert!(err.to_string().contains('A'), "{err}"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn secret_add_grant_revoke_rotate_append_oplog_records() { let root = tmp_root("oplog-secret"); diff --git a/demo/run_rewrap_demo.sh b/demo/run_rewrap_demo.sh index eee74f27..07b49db2 100755 --- a/demo/run_rewrap_demo.sh +++ b/demo/run_rewrap_demo.sh @@ -46,9 +46,9 @@ printf '[recipients]\nalice = "%s"\nbob = "%s"\nescrow = "%s"\n' \ "$alice_pk" "$bob_pk" "$escrow_pk" > .sc/recipients.toml # 1. A pre-escrow secret, sealed to alice only. -"$SC" secret add db-pass --to alice --value hunter2 >/dev/null -"$SC" secret list --json | grep -q '"name":"db-pass","recipients":1' \ - || fail "db-pass must start with exactly 1 recipient (alice)" +"$SC" secret add DB_PASS --to alice --value hunter2 >/dev/null +"$SC" secret list --json | grep -q '"name":"DB_PASS","recipients":1' \ + || fail "DB_PASS must start with exactly 1 recipient (alice)" # 2. Escrow: add a break-glass recipient key and confirm it's recorded. "$SC" escrow add escrow >/dev/null @@ -89,11 +89,11 @@ grep -q "skipped (no key)" "$work/pre-rewrap-switch.err" \ # AND strips bob's re-attached wrap from the protected blob, in one commit. rewrap_out=$("$SC" rewrap --identity "$keys/alice" 2>"$work/rewrap.err") echo "$rewrap_out" | grep -q "rewrapped 1 secret(s)" \ - || fail "rewrap must report exactly 1 secret rewrapped (db-pass), got: $rewrap_out" + || fail "rewrap must report exactly 1 secret rewrapped (DB_PASS), got: $rewrap_out" echo "$rewrap_out" | grep -Eq "rewrapped 1 secret\(s\), [1-9][0-9]* protected blob" \ || fail "rewrap must report at least 1 protected blob rewrapped, got: $rewrap_out" -"$SC" secret list --json | grep -q '"name":"db-pass","recipients":2' \ - || fail "db-pass must now show 2 recipients (alice + escrow)" +"$SC" secret list --json | grep -q '"name":"DB_PASS","recipients":2' \ + || fail "DB_PASS must now show 2 recipients (alice + escrow)" # 5. ONE UNDO REVERTS THE WHOLE SWEEP. This check must run with NO other # oplog-recording command in between: `sc switch` is itself an oplog @@ -102,14 +102,14 @@ echo "$rewrap_out" | grep -Eq "rewrapped 1 secret\(s\), [1-9][0-9]* protected bl # would undo that switch instead of the rewrap. Verified BEFORE the R1 # strip check below, which does need a switch. "$SC" undo >/dev/null -"$SC" secret list --json | grep -q '"name":"db-pass","recipients":1' \ - || fail "undo must restore db-pass to its pre-rewrap 1 recipient" +"$SC" secret list --json | grep -q '"name":"DB_PASS","recipients":1' \ + || fail "undo must restore DB_PASS to its pre-rewrap 1 recipient" # `sc undo` again = redo (documented in CLAUDE.md): back to the fully # rewrapped tip, so the R1 strip check below runs against the real # post-rewrap state. "$SC" undo >/dev/null -"$SC" secret list --json | grep -q '"name":"db-pass","recipients":2' \ - || fail "second undo (= redo) must restore db-pass to 2 recipients" +"$SC" secret list --json | grep -q '"name":"DB_PASS","recipients":2' \ + || fail "second undo (= redo) must restore DB_PASS to 2 recipients" # 6. THE R1 STRIP: bob's identity, which decrypted this same path a moment # ago (step 3's precondition), must now fail to decrypt the post-rewrap diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 20e3baab..3e23a9d7 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -39,6 +39,20 @@ too, not just the src-control-side metadata. same-user process can still read the child's descriptor table, and the child decides what to do with what it read. Env stays the default for `sc run`, `sc work --with-secrets` and `sc ws run --with-secrets`. +- **The registry is repository data, so injection validates it.** `secret_add` + needs no key: any writer can register a secret sealed to your public key under + any name. A secret name must therefore match `[A-Za-z_][A-Za-z0-9_]*` and not + be a variable that changes how a process loads code or which program runs + (`PATH`, `LD_*`, `DYLD_*`, `NODE_OPTIONS`, `GIT_CONFIG*`, `SC_*`, and the other + names in `secrets.rs`). `secret_add` refuses such a name, and every injecting + path (`sc run`, `--secrets-fd`, `sc ws run --with-secrets`, + `sc work --with-secrets`) refuses the whole run, before decrypting anything and + before any child starts, when a registry key fails the rule or differs from the + `name` the secret was sealed under (the AEAD binds that name). **Residual:** a + writer can still replace the value of an allowed name (say `DATABASE_URL`) with + one sealed to you, so the child connects where the writer chose. The registry + is not authenticated; review registry changes like code, and use `sc verify + --require` on the commits you run from. - **Rotation ≠ erasure:** `sc secret rotate` re-seals under a fresh DEK and cuts off future reads through the current registry, but the old ciphertext object remains reachable and decryptable by anyone who kept the old DEK. `sc secret From 87f9d9ed785f23842ec671e156568e68a1032389 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:27:22 +0200 Subject: [PATCH 2/6] fix(secrets): widen the deny list to loader, interpreter and toolchain families --- crates/repo/src/secrets.rs | 61 +++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 0e40eb3f..e5a98a35 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -689,11 +689,53 @@ const DENIED_NAMES: &[&str] = &[ "HOME", "SHELL", "TMPDIR", + "GCONV_PATH", + "GLIBC_TUNABLES", + "HOSTALIASES", + "LOCALDOMAIN", + "RES_OPTIONS", + "NLSPATH", + "ZDOTDIR", + "CDPATH", + "BROWSER", + "RUSTFLAGS", + "RUSTDOCFLAGS", + "RUSTC_WRAPPER", + "GOFLAGS", + "MAKEFLAGS", + "MFLAGS", + "SSL_CERT_FILE", + "SSL_CERT_DIR", ]; /// Prefixes denied for the same reason, plus `SC_` (sc's own knobs, such as -/// `SC_SSH` and `SC_GIT`). -const DENIED_PREFIXES: &[&str] = &["LD_", "DYLD_", "GIT_CONFIG", "SC_"]; +/// `SC_SSH` and `SC_GIT`). A deny list cannot be complete: it covers the +/// loader, shell, interpreter and toolchain families; the registry itself is +/// still unauthenticated repository data (docs/THREAT-MODEL.md). +const DENIED_PREFIXES: &[&str] = &[ + "LD_", + "DYLD_", + "GIT_", + "SC_", + "MALLOC_", + "PYTHON", + "PERL", + "RUBY", + "NODE_", + "LESS", + "CARGO_", + "RUSTC_", + "JAVA_", + "BASH_", + "NPM_CONFIG_", +]; + +/// Names a denied prefix would catch but that are ordinary credentials, not +/// loader or interpreter knobs. +const ALLOWED_EXCEPTIONS: &[&str] = &["NODE_AUTH_TOKEN", "CARGO_REGISTRY_TOKEN"]; + +/// Suffixes that name a program a tool runs (`GIT_PAGER`, `SVN_EDITOR`, ...). +const DENIED_SUFFIXES: &[&str] = &["PAGER", "EDITOR"]; /// The one secret-name rule: `[A-Za-z_][A-Za-z0-9_]*`, and not a variable that /// changes how the child loads code or which program it runs. Applied when a @@ -714,12 +756,14 @@ pub(crate) fn check_secret_name(name: &str) -> Result<()> { }; if !shape_ok || DENIED_NAMES.contains(&key.as_str()) - || DENIED_PREFIXES.iter().any(|p| key.starts_with(p)) + || (DENIED_PREFIXES.iter().any(|p| key.starts_with(p)) + && !ALLOWED_EXCEPTIONS.contains(&key.as_str())) + || DENIED_SUFFIXES.iter().any(|s| key.ends_with(s)) { return Err(Error::InvalidArgument(format!( "secret name {name:?} is not allowed: use [A-Za-z_][A-Za-z0-9_]* and not a \ variable that changes how a process loads code or which program runs \ - (PATH, LD_*, DYLD_*, NODE_OPTIONS, GIT_CONFIG*, SC_*, ...)" + (PATH, LD_*, DYLD_*, GIT_*, NODE_*, PYTHON*, *PAGER, *EDITOR, SC_*, ...)" ))); } Ok(()) @@ -1146,6 +1190,11 @@ mod tests { "NODE_OPTIONS", "GIT_CONFIG_COUNT", "SC_GIT", + "GIT_PAGER", + "GLIBC_TUNABLES", + "PYTHONWARNINGS", + "MALLOC_CONF", + "SVN_EDITOR", "a-b", "1X", "", @@ -1164,6 +1213,10 @@ mod tests { .unwrap(); repo.secret_add("_x9", b"v", std::slice::from_ref(&pk)) .unwrap(); + repo.secret_add("NODE_AUTH_TOKEN", b"v", std::slice::from_ref(&pk)) + .unwrap(); + repo.secret_add("GITHUB_TOKEN", b"v", std::slice::from_ref(&pk)) + .unwrap(); drop(repo); std::fs::remove_dir_all(&root).unwrap(); } From f3b666a533b88a745926bd709c45542140a5eb15 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:28:25 +0200 Subject: [PATCH 3/6] fix(secrets): match names case-insensitively, skip bad registry names, guard rotate Uppercase the name before every deny check on every platform, since tools read npm_config_*, http_proxy and similar in any case. Widen the deny list with compiler, proxy, CA-bundle, cloud and container config variables and the XDG_, OPENSSL_, DOTNET_, CORECLR_, COR_, GEM_, LUA_, PIP_, UV_ and YARN_ prefixes, and the _OPTS and ASKPASS suffixes. Injection now skips a registry entry whose name fails the rule, with a stderr warning and without opening it, in strict and non-strict mode. A legacy name such as db-pass or a planted one no longer stops every run. A key that differs from the sealed name still refuses the run, and secret rotate without --value refuses it too instead of re-sealing it under the registry key. --- CLAUDE.md | 2 +- crates/repo/src/secrets.rs | 252 +++++++++++++++++++++++++++++-------- docs/THREAT-MODEL.md | 28 +++-- 3 files changed, 217 insertions(+), 65 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8ad9200b..358a76e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -120,7 +120,7 @@ the code, those win. | Phase | Current state | ADR | |---|---|---| | P1 | In-RAM copy-on-write virtual worktrees; bounded blob budget + LRU eviction, optional spill; zero disk residue | [0005](docs/adr/0005-in-ram-vfs-over-fuse.md), [0006](docs/adr/0006-memory-budget-and-eviction.md) | -| P2 | Committed secrets: per-secret DEK (XChaCha20-Poly1305) wrapped per X25519 recipient; secrets are env vars, never files — `checkout` never materializes them; names are `[A-Za-z_][A-Za-z0-9_]*` minus loader/PATH/`SC_` variables, enforced at add and again at injection (a registry key must equal the sealed name); `sc run` injects into a child env, or onto a descriptor with `--secrets-fd N` (unix) | [0008](docs/adr/0008-committed-secrets-envelope-encryption.md), [0009](docs/adr/0009-key-management-and-authorization.md), [0010](docs/adr/0010-secret-registry-and-opaque-wrapped-dek.md), [0052](docs/adr/0052-secret-injection-by-fd.md) | +| P2 | Committed secrets: per-secret DEK (XChaCha20-Poly1305) wrapped per X25519 recipient; secrets are env vars, never files — `checkout` never materializes them; names are `[A-Za-z_][A-Za-z0-9_]*` minus loader/PATH/`SC_`/proxy-style variables (case-insensitive), enforced at add and again at injection (a bad name is skipped with a warning; a registry key must equal the sealed name); `sc run` injects into a child env, or onto a descriptor with `--secrets-fd N` (unix) | [0008](docs/adr/0008-committed-secrets-envelope-encryption.md), [0009](docs/adr/0009-key-management-and-authorization.md), [0010](docs/adr/0010-secret-registry-and-opaque-wrapped-dek.md), [0052](docs/adr/0052-secret-injection-by-fd.md) | | P3 | Persistent `.sc/` repo: loose objects, branches, symbolic HEAD, single-writer lock, working tree; write-out paths restore the recorded executable bit (unix; #242; special bits are always cleared, `sc resolve` restores the chosen side's mode, and a swallowed chmod warns once; #243) | [0011](docs/adr/0011-persistent-store-and-working-tree.md) | | P4 | Snapshot-DAG three-way merge; ff when possible; conflict markers + `.theirs` sidecars | [0012](docs/adr/0012-three-way-merge.md) | | P5 | Commit-time secret scanner (pattern + entropy) hard-rejects plaintext secrets; `sc scan` preview; hash-scoped allowlist | [0017](docs/adr/0017-secret-scanner.md) | diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index e5a98a35..302f8ebd 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -271,6 +271,15 @@ impl Repo { _ => return Err(Error::NoSuchSecret(format!("{name} is not a secret"))), } }; + // Re-sealing under the registry key would launder a relabeled + // entry into a validly sealed one. + 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 + ))); + } recovered = scl_crypto::open(&secret, id)?; &recovered[..] } @@ -372,11 +381,17 @@ impl Repo { strict: bool, ) -> Result>)>> { // The registry is repository data any writer can edit, so nothing is - // decrypted until every entry has a name that may be injected and - // points at a secret sealed under that same name. + // decrypted until every entry has been vetted. An entry whose name may + // not be injected (planted, or registered by an older CLI that took any + // name) is skipped with a warning and never opened, so one bad entry + // does not block `sc run`; one that points at a secret sealed under a + // different name refuses the whole run. let mut entries = Vec::new(); for (name, id) in self.registry()? { - check_secret_name(&name)?; + if check_secret_name(&name).is_err() { + eprintln!("warning: secret name {name:?} is not allowed; skipping"); + continue; + } let obj = { let arc = self.store_arc(); let o = arc.lock().unwrap().get(&id)?; @@ -651,10 +666,15 @@ fn feed_pipe( } } -/// Variables that change how a process loads code or which program runs; a -/// secret may not be registered or injected under one of these names. +/// Variables that change how a process loads code, which program runs, or where +/// a tool reads its config or trust roots; a secret may not be registered or +/// injected under one of these names. A deny list cannot be complete: the +/// registry itself is still unauthenticated repository data +/// (docs/THREAT-MODEL.md). Compared in uppercase (see [`check_secret_name`]). const DENIED_NAMES: &[&str] = &[ + // Shell and program lookup. "PATH", + "PATHEXT", "IFS", "ENV", "BASH_ENV", @@ -662,6 +682,32 @@ const DENIED_NAMES: &[&str] = &[ "BASHOPTS", "PS4", "PROMPT_COMMAND", + "ZDOTDIR", + "CDPATH", + "SHELL", + "COMSPEC", + "PSMODULEPATH", + // User directories and what the user's tools launch. + "HOME", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "TMPDIR", + "EDITOR", + "VISUAL", + "PAGER", + "BROWSER", + "VIMINIT", + "EXINIT", + // Dynamic loader and libc. + "LD", + "GCONV_PATH", + "GLIBC_TUNABLES", + "HOSTALIASES", + "LOCALDOMAIN", + "RES_OPTIONS", + "NLSPATH", + // Interpreters. "NODE_OPTIONS", "NODE_PATH", "PYTHONPATH", @@ -669,55 +715,79 @@ const DENIED_NAMES: &[&str] = &[ "PYTHONSTARTUP", "PYTHONINSPECT", "PYTHONUSERBASE", + "PYTEST_ADDOPTS", "PERL5OPT", "PERL5LIB", "PERLLIB", "RUBYOPT", "RUBYLIB", + "BUNDLE_GEMFILE", + "GEMRC", + "PHPRC", + "PHP_INI_SCAN_DIR", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS", "CLASSPATH", - "GIT_SSH", - "GIT_SSH_COMMAND", - "GIT_EXEC_PATH", - "GIT_ASKPASS", - "SSH_ASKPASS", - "EDITOR", - "VISUAL", - "PAGER", - "HOME", - "SHELL", - "TMPDIR", - "GCONV_PATH", - "GLIBC_TUNABLES", - "HOSTALIASES", - "LOCALDOMAIN", - "RES_OPTIONS", - "NLSPATH", - "ZDOTDIR", - "CDPATH", - "BROWSER", + // Compilers and build tools. + "RUSTC", + "RUSTDOC", "RUSTFLAGS", "RUSTDOCFLAGS", "RUSTC_WRAPPER", + "CC", + "CXX", + "AR", "GOFLAGS", + "GOPROXY", + "GOENV", + "GOTOOLCHAIN", + "GONOSUMDB", + "GOPRIVATE", "MAKEFLAGS", "MFLAGS", + "MAKEFILES", + "GNUMAKEFLAGS", + "CONFIG_SITE", + // Git, ssh and other programs a tool spawns. + "GIT_SSH", + "GIT_SSH_COMMAND", + "GIT_EXEC_PATH", + "GIT_ASKPASS", + "SSH_ASKPASS", + "RSYNC_RSH", + "TAR_OPTIONS", + "PSQLRC", + "MYSQL_HOME", + // Network and trust: where a tool connects and whom it trusts. + "HTTP_PROXY", + "HTTPS_PROXY", + "ALL_PROXY", + "NO_PROXY", + "FTP_PROXY", "SSL_CERT_FILE", "SSL_CERT_DIR", + "CURL_CA_BUNDLE", + "REQUESTS_CA_BUNDLE", + "AWS_CA_BUNDLE", + // Cloud and container tooling config. + "KUBECONFIG", + "AWS_CONFIG_FILE", + "AWS_SHARED_CREDENTIALS_FILE", + "DOCKER_CONFIG", + "DOCKER_HOST", + "TF_CLI_CONFIG_FILE", ]; /// Prefixes denied for the same reason, plus `SC_` (sc's own knobs, such as -/// `SC_SSH` and `SC_GIT`). A deny list cannot be complete: it covers the -/// loader, shell, interpreter and toolchain families; the registry itself is -/// still unauthenticated repository data (docs/THREAT-MODEL.md). +/// `SC_SSH` and `SC_GIT`). const DENIED_PREFIXES: &[&str] = &[ "LD_", "DYLD_", + "MALLOC_", "GIT_", "SC_", - "MALLOC_", + "BASH_", "PYTHON", "PERL", "RUBY", @@ -726,34 +796,44 @@ const DENIED_PREFIXES: &[&str] = &[ "CARGO_", "RUSTC_", "JAVA_", - "BASH_", "NPM_CONFIG_", + "XDG_", + "OPENSSL_", + "DOTNET_", + "CORECLR_", + "COR_", + "GEM_", + "LUA_", + "PIP_", + "UV_", + "YARN_", ]; /// Names a denied prefix would catch but that are ordinary credentials, not /// loader or interpreter knobs. -const ALLOWED_EXCEPTIONS: &[&str] = &["NODE_AUTH_TOKEN", "CARGO_REGISTRY_TOKEN"]; +const ALLOWED_EXCEPTIONS: &[&str] = &[ + "NODE_AUTH_TOKEN", + "CARGO_REGISTRY_TOKEN", + "YARN_NPM_AUTH_TOKEN", +]; -/// Suffixes that name a program a tool runs (`GIT_PAGER`, `SVN_EDITOR`, ...). -const DENIED_SUFFIXES: &[&str] = &["PAGER", "EDITOR"]; +/// Suffixes that name a program or options a tool runs (`GIT_PAGER`, +/// `SVN_EDITOR`, `MAVEN_OPTS`, `SUDO_ASKPASS`, ...). +const DENIED_SUFFIXES: &[&str] = &["PAGER", "EDITOR", "_OPTS", "ASKPASS"]; /// The one secret-name rule: `[A-Za-z_][A-Za-z0-9_]*`, and not a variable that /// changes how the child loads code or which program it runs. Applied when a /// secret is added and again at injection, because the registry is repository /// data a writer can edit without any key (THREAT-MODEL, committed secrets). -/// Matching is case-sensitive, except on Windows where environment variable -/// names are not. +/// Every deny check compares the uppercased name on every platform: some tools +/// read their variables case-insensitively (`npm_config_*`, `http_proxy`). pub(crate) fn check_secret_name(name: &str) -> Result<()> { let mut chars = name.chars(); let shape_ok = chars .next() .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); - let key = if cfg!(windows) { - name.to_ascii_uppercase() - } else { - name.to_string() - }; + let key = name.to_ascii_uppercase(); if !shape_ok || DENIED_NAMES.contains(&key.as_str()) || (DENIED_PREFIXES.iter().any(|p| key.starts_with(p)) @@ -762,8 +842,9 @@ pub(crate) fn check_secret_name(name: &str) -> Result<()> { { return Err(Error::InvalidArgument(format!( "secret name {name:?} is not allowed: use [A-Za-z_][A-Za-z0-9_]* and not a \ - variable that changes how a process loads code or which program runs \ - (PATH, LD_*, DYLD_*, GIT_*, NODE_*, PYTHON*, *PAGER, *EDITOR, SC_*, ...)" + variable that changes how a process loads code or which program runs, in any \ + letter case (PATH, LD_*, DYLD_*, GIT_*, NODE_*, PYTHON*, *_OPTS, *PAGER, \ + *EDITOR, SC_*, proxy and CA-bundle variables, ...)" ))); } Ok(()) @@ -1195,6 +1276,25 @@ mod tests { "PYTHONWARNINGS", "MALLOC_CONF", "SVN_EDITOR", + // Case-insensitive: tools read these in any case. + "npm_config_script_shell", + "http_proxy", + "ld_preload", + "Path", + "node_options", + // Newer families. + "RUSTC", + "CC", + "LD", + "KUBECONFIG", + "HTTPS_PROXY", + "XDG_CONFIG_HOME", + "OPENSSL_CONF", + "PIP_INDEX_URL", + "UV_INDEX_URL", + "YARN_RC_FILENAME", + "MAVEN_OPTS", + "SUDO_ASKPASS", "a-b", "1X", "", @@ -1215,41 +1315,85 @@ mod tests { .unwrap(); repo.secret_add("NODE_AUTH_TOKEN", b"v", std::slice::from_ref(&pk)) .unwrap(); - repo.secret_add("GITHUB_TOKEN", b"v", std::slice::from_ref(&pk)) - .unwrap(); + for ok in [ + "GITHUB_TOKEN", + "YARN_NPM_AUTH_TOKEN", + "CARGO_REGISTRY_TOKEN", + ] { + repo.secret_add(ok, b"v", std::slice::from_ref(&pk)) + .unwrap(); + } drop(repo); std::fs::remove_dir_all(&root).unwrap(); } #[test] - fn injection_refuses_a_planted_denied_name_and_starts_no_child() { + fn injection_skips_a_planted_or_legacy_bad_name_and_never_opens_it() { let root = tmp_root("planted"); let (sk, pk) = scl_crypto::generate_keypair(); + let (_other_sk, other_pk) = scl_crypto::generate_keypair(); let repo = Repo::init(&root).unwrap(); repo.secret_add("DB_URL", b"v", std::slice::from_ref(&pk)) .unwrap(); - plant(&repo, "LD_PRELOAD", "LD_PRELOAD", b"/tmp/evil.so", &pk); + // Sealed to someone else: strict mode would fail with "not a + // recipient" if injection tried to open any of these. + for bad in ["LD_PRELOAD", "npm_config_script_shell", "db-pass"] { + plant(&repo, bad, bad, b"/tmp/evil", &other_pk); + } + for strict in [true, false] { + let values = repo.secret_values(&sk, strict).unwrap(); + let names: Vec<&str> = values.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["DB_URL"], "strict={strict}"); + } let marker = root.join("child-ran"); let cmd = [ "sh".to_string(), "-c".to_string(), - format!("touch {}", marker.display()), + format!( + "test -z \"$LD_PRELOAD\" && test -z \"$npm_config_script_shell\" \ + && test \"$DB_URL\" = v && touch {}", + marker.display() + ), ]; - let err = repo.run(&sk, &cmd).unwrap_err(); - assert!(err.to_string().contains("LD_PRELOAD"), "{err}"); - assert!(!marker.exists(), "no child may start"); - assert!(repo.secret_values(&sk, false).is_err()); - assert!(repo.secret_env(&sk, true).is_err()); + assert_eq!(repo.run(&sk, &cmd).unwrap(), 0); + assert!(marker.exists(), "the child ran with only the good secret"); #[cfg(unix)] { - assert!(repo.run_with_secrets_fd(&sk, &cmd, 3).is_err()); - assert!(!marker.exists(), "no child may start (fd mode)"); + // fd mode: the payload on fd 3 holds exactly the one good record. + let fd_cmd = [ + "sh".to_string(), + "-c".to_string(), + "out=$(tr '\\0' '\\n' <&3); test \"$out\" = DB_URL=v".to_string(), + ]; + assert_eq!(repo.run_with_secrets_fd(&sk, &fd_cmd, 3).unwrap(), 0); } drop(repo); std::fs::remove_dir_all(&root).unwrap(); } + #[test] + fn rotate_without_value_refuses_a_relabeled_entry() { + let root = tmp_root("rot-relabel"); + let (sk, pk) = scl_crypto::generate_keypair(); + let repo = Repo::init(&root).unwrap(); + plant(&repo, "A", "B", b"value-of-b", &pk); + let err = repo + .secret_rotate("A", None, std::slice::from_ref(&pk), Some(&sk)) + .unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err}"); + // The entry is untouched, so injection still refuses it. + assert!(repo.secret_values(&sk, false).is_err()); + // An explicit value is the repair path: sealed afresh under "A". + repo.secret_rotate("A", Some(b"fresh"), std::slice::from_ref(&pk), None) + .unwrap(); + let values = repo.secret_values(&sk, false).unwrap(); + assert_eq!(values.len(), 1); + assert_eq!(&values[0].1[..], b"fresh"); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn injection_refuses_a_registry_key_that_differs_from_the_sealed_name() { let root = tmp_root("relabel"); diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 3e23a9d7..4d7aea66 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -42,17 +42,25 @@ too, not just the src-control-side metadata. - **The registry is repository data, so injection validates it.** `secret_add` needs no key: any writer can register a secret sealed to your public key under any name. A secret name must therefore match `[A-Za-z_][A-Za-z0-9_]*` and not - be a variable that changes how a process loads code or which program runs - (`PATH`, `LD_*`, `DYLD_*`, `NODE_OPTIONS`, `GIT_CONFIG*`, `SC_*`, and the other - names in `secrets.rs`). `secret_add` refuses such a name, and every injecting + be a variable that changes how a process loads code, which program runs, or + where a tool reads its config or trust roots (`PATH`, `LD_*`, `DYLD_*`, + `NODE_OPTIONS`, `GIT_*`, `SC_*`, proxy and CA-bundle variables, and the other + names in `secrets.rs`; a deny list, so not complete). The match is + case-insensitive on every platform, since tools such as npm read + `npm_config_*` in any case. `secret_add` refuses such a name. Every injecting path (`sc run`, `--secrets-fd`, `sc ws run --with-secrets`, - `sc work --with-secrets`) refuses the whole run, before decrypting anything and - before any child starts, when a registry key fails the rule or differs from the - `name` the secret was sealed under (the AEAD binds that name). **Residual:** a - writer can still replace the value of an allowed name (say `DATABASE_URL`) with - one sealed to you, so the child connects where the writer chose. The registry - is not authenticated; review registry changes like code, and use `sc verify - --require` on the commits you run from. + `sc work --with-secrets`) validates the registry before the requested command + starts (`sc work`'s preflight can start an ssh transport on a lazy clone + 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 + 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 + (say `DATABASE_URL`) with one sealed to you, so the child connects where the + writer chose. The registry is not authenticated; review registry changes like + code, and use `sc verify --require` on the commits you run from. - **Rotation ≠ erasure:** `sc secret rotate` re-seals under a fresh DEK and cuts off future reads through the current registry, but the old ciphertext object remains reachable and decryptable by anyone who kept the old DEK. `sc secret From 41d7e5a571e532087fc58a061b24b9e497932db5 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:29:48 +0200 Subject: [PATCH 4/6] fix(secrets): allow the rubygems credential names --- crates/repo/src/secrets.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 302f8ebd..1e08850c 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -815,6 +815,8 @@ const ALLOWED_EXCEPTIONS: &[&str] = &[ "NODE_AUTH_TOKEN", "CARGO_REGISTRY_TOKEN", "YARN_NPM_AUTH_TOKEN", + "GEM_HOST_API_KEY", + "RUBYGEMS_API_KEY", ]; /// Suffixes that name a program or options a tool runs (`GIT_PAGER`, @@ -1318,6 +1320,8 @@ mod tests { for ok in [ "GITHUB_TOKEN", "YARN_NPM_AUTH_TOKEN", + "GEM_HOST_API_KEY", + "RUBYGEMS_API_KEY", "CARGO_REGISTRY_TOKEN", ] { repo.secret_add(ok, b"v", std::slice::from_ref(&pk)) From 5b38ab09827aa72712643400be2e6ece8e355baa Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:35:18 +0200 Subject: [PATCH 5/6] fix(secrets): refuse a relabeled entry even under a skipped name --- crates/repo/src/secrets.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 1e08850c..4ee4cd00 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -388,10 +388,6 @@ impl Repo { // different name refuses the whole run. let mut entries = Vec::new(); for (name, id) in self.registry()? { - if check_secret_name(&name).is_err() { - eprintln!("warning: secret name {name:?} is not allowed; skipping"); - continue; - } let obj = { let arc = self.store_arc(); let o = arc.lock().unwrap().get(&id)?; @@ -409,6 +405,12 @@ impl Repo { secret.name ))); } + // Checked after the binding, so a relabeled entry refuses even + // when its key is one that would be skipped. + if check_secret_name(&name).is_err() { + eprintln!("warning: secret name {name:?} is not allowed; skipping"); + continue; + } entries.push((name, secret)); } let mut out = Vec::new(); @@ -1409,6 +1411,17 @@ mod tests { assert!(err.to_string().contains('A'), "{err}"); drop(repo); std::fs::remove_dir_all(&root).unwrap(); + + // A relabel under a key that would be skipped still refuses. + let root = tmp_root("relabel-denied"); + let repo = Repo::init(&root).unwrap(); + plant(&repo, "LD_PRELOAD", "DB_URL", b"x", &pk); + assert!(matches!( + repo.secret_values(&sk, false), + Err(Error::InvalidArgument(_)) + )); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); } #[test] From 51c1c8b7f089a25fea53fbb0dbc32ce7f3c147f1 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:37:03 +0200 Subject: [PATCH 6/6] fix(secrets): quote the registry key in the relabel error --- crates/repo/src/secrets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 4ee4cd00..ee0a9c75 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -401,7 +401,7 @@ impl Repo { // as `B` could be served under the registry key `A`. if secret.name != name { return Err(Error::InvalidArgument(format!( - "registry entry {name} points at a secret sealed as {:?}; refusing to run", + "registry entry {name:?} points at a secret sealed as {:?}; refusing to run", secret.name ))); }