diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 92b31e0b..389e5a41 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -95,7 +95,10 @@ cargo run --bin sc -- secret add --to --value cargo run --bin sc -- secret grant --to --identity cargo run --bin sc -- secret revoke --recipient-id cargo run --bin sc -- secret list -cargo run --bin sc -- run -- [args…] # inject decrypted secrets + run command +cargo run --bin sc -- run [--secrets-fd N] -- [args…] # inject decrypted secrets + run command; + # --secrets-fd N (unix, N in 3..=1023) passes them on fd N as + # NUL-terminated NAME=VALUE records instead of env vars + # (SC_SECRETS_FD names N); ADR-0052 cargo run --bin sc -- gc # pack reachable objects + prune unreachable cargo run --bin sc -- gc --prune-expire 7d # custom grace window cargo run --bin sc -- export --to # write current branch history to Git diff --git a/CLAUDE.md b/CLAUDE.md index 12182958..d51c8f1f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -231,6 +231,10 @@ transport-adjacent. The rest, imperatively: - **Secret injection is an authorized local process context, NOT isolation:** same-user processes, crash dumps, and shell wrappers can observe the child env. The parent's buffer is zeroized; the child's copy cannot be. + `sc run --secrets-fd N` (ADR-0052, unix) keeps the secrets out of the + environment (they arrive on fd N as NUL-terminated `NAME=VALUE` records, + `SC_SECRETS_FD` names it): hygiene against env dumps and inheritance, still + not isolation. `sc ws run` and `sc work --with-secrets` use the environment. - **Sparse is checkout-only** and has one disk-hygiene boundary: an in-sparse conflict co-occurring with an out-of-sparse protected/plain clean change can leave that out-of-sparse plaintext on disk until the next materializing @@ -264,8 +268,7 @@ transport-adjacent. The rest, imperatively: Deferred work is tracked in **`ROADMAP.md` → Deferred** (single source of truth — do not re-list items here). Notable standing entries: transparent lazy-fetch for partial clones, per-case gap-tolerant merge/replay on partial -clones, fd/stdin -secret injection, CA-path validation alongside TOFU pinning, and pin-management +clones, CA-path validation alongside TOFU pinning, and pin-management UX (`sc tls`). ## Agent skills diff --git a/ROADMAP.md b/ROADMAP.md index 63c7449a..ce07e441 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -799,11 +799,10 @@ scale-&-reach horizon): is minted 0600-from-first-byte via a unix-only `OpenOptions::mode` call; there is no non-unix fallback today, so the key file is left world-readable on a non-unix target. A non-unix permission-hardening path is deferred. -- **fd/stdin secret injection (P28).** `sc run` hands decrypted secrets to - the child via its environment — observable by same-user processes, - crash dumps, and shell wrappers, per the tightened threat-model wording. - An alternative injection path (an fd or stdin the child reads instead of - inheriting an env var) would shrink that exposure and is deferred. +- **fd secret injection — shipped (ADR-0052).** `sc run --secrets-fd N` hands the + secrets to the command on a descriptor (NUL-terminated `NAME=VALUE` records) + instead of its environment. Not built: the same mode for `sc ws run` and + `sc work --with-secrets`, and a stdin variant. - **`--max-object-size` operator config knob (P28).** `MAX_OBJECT_SIZE` (256 MiB) is a compile-time constant anchoring every untrusted-length guard; letting an operator raise or lower it per-deployment is deferred. diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 71aa530c..326ef67c 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -245,10 +245,18 @@ enum Cmd { /// Injected secrets are visible to the child and any same-user process, /// crash dump, or shell wrapper — an authorized local-process boundary, /// not isolation. + /// + /// With `--secrets-fd N` the secrets stay out of the environment: they + /// arrive on file descriptor N as NUL-terminated NAME=VALUE records (read + /// to EOF), and SC_SECRETS_FD=N names it. Run { /// Identity file (default ~/.sc/identity or $SC_IDENTITY). #[arg(long)] identity: Option, + /// Hand the secrets to the command on this file descriptor (3 to + /// 1023) instead of in its environment. Unix only. + #[arg(long, value_name = "FD")] + secrets_fd: Option, /// Command and args after `--`. #[arg(last = true, required = true)] cmd: Vec, @@ -951,7 +959,11 @@ fn main() -> Result<()> { identity, } => run_rebase(target, r#continue, abort, &resolve_author(author), identity), Cmd::Secret { op } => run_secret(op), - Cmd::Run { identity, cmd } => run_run(identity, cmd), + Cmd::Run { + identity, + secrets_fd, + cmd, + } => run_run(identity, secrets_fd, cmd), Cmd::Work { agents, name, @@ -3080,10 +3092,13 @@ fn run_escrow(op: EscrowOp) -> Result<()> { Ok(()) } -fn run_run(identity: Option, cmd: Vec) -> Result<()> { +fn run_run(identity: Option, secrets_fd: Option, cmd: Vec) -> Result<()> { let repo = open_repo()?; let sk = load_identity(identity)?; - let code = repo.run(&sk, &cmd)?; + let code = match secrets_fd { + Some(fd) => repo.run_with_secrets_fd(&sk, &cmd, fd)?, + None => repo.run(&sk, &cmd)?, + }; // `process::exit` skips destructors, so the repo's RepoLock would never run // its Drop and `.sc/lock` would leak — bricking the next `sc` command with a // spurious `Locked` error. Drop the repo (releasing the lock) before exiting. diff --git a/crates/cli/tests/secrets_fd.rs b/crates/cli/tests/secrets_fd.rs new file mode 100644 index 00000000..556cf69f --- /dev/null +++ b/crates/cli/tests/secrets_fd.rs @@ -0,0 +1,347 @@ +//! `sc run --secrets-fd N` (ADR-0052): secrets reach the command on a file +//! descriptor instead of in its environment. +#![cfg(unix)] + +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; + +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 sc_stdin(dir: &Path, args: &[&str], input: &[u8]) -> std::process::Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_sc")) + .args(args) + .current_dir(dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("sc spawns"); + child.stdin.take().unwrap().write_all(input).unwrap(); + child.wait_with_output().expect("sc runs") +} + +fn tmp(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("scl-cli-secrets-fd-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A repo with `secrets` (name, value) sealed to alice; returns +/// (repo, alice's identity file, keys dir). +fn repo_with( + tag: &str, + secrets: &[(&str, Vec)], +) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) { + let root = tmp(tag); + let keys = tmp(&format!("{tag}-keys")); + let id = keys.join("alice.id"); + let out = sc(&keys, &["keygen", "--out", id.to_str().unwrap()]); + assert!(out.status.success()); + let pk = String::from_utf8_lossy(&out.stdout) + .lines() + .find(|l| l.contains("public key")) + .and_then(|l| l.split_whitespace().find(|w| w.starts_with("scl-pk-"))) + .expect("public key") + .to_string(); + let repo = root.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + assert!(sc(&repo, &["init"]).status.success()); + std::fs::write( + repo.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{pk}\"\n"), + ) + .unwrap(); + for (name, value) in secrets { + let out = sc_stdin(&repo, &["secret", "add", name, "--to", "alice"], value); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + } + (repo, id, keys) +} + +fn run_fd(repo: &Path, id: &Path, fd: &str, shell: &str) -> std::process::Output { + sc( + repo, + &[ + "run", + "--identity", + id.to_str().unwrap(), + "--secrets-fd", + fd, + "--", + "sh", + "-c", + shell, + ], + ) +} + +/// The secrets arrive on the descriptor as NUL-terminated NAME=VALUE records +/// and are absent from the environment, which only names the descriptor. +#[test] +fn secrets_arrive_on_the_fd_and_not_in_the_environment() { + let (repo, id, keys) = repo_with( + "basic", + &[ + ("DB_URL", b"postgres://x".to_vec()), + ("API_KEY", b"k-123".to_vec()), + ], + ); + let out = run_fd( + &repo, + &id, + "3", + r#"test -z "${DB_URL+set}" && test -z "${API_KEY+set}" && test "$SC_SECRETS_FD" = 3 && cat <&3"#, + ); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let records: Vec<&[u8]> = out + .stdout + .split(|b| *b == 0) + .filter(|r| !r.is_empty()) + .collect(); + let mut got: Vec = records + .iter() + .map(|r| String::from_utf8_lossy(r).into_owned()) + .collect(); + got.sort(); + assert_eq!(got, ["API_KEY=k-123", "DB_URL=postgres://x"]); + assert!(out.stdout.ends_with(&[0]), "every record is NUL-terminated"); + + // The environment of a plain run still carries them (unchanged default). + let plain = sc( + &repo, + &[ + "run", + "--identity", + id.to_str().unwrap(), + "--", + "sh", + "-c", + "test \"$API_KEY\" = k-123", + ], + ); + assert!(plain.status.success()); + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// Any descriptor from 3 up works, and 0, 1, 2 and out-of-range numbers are +/// refused before anything runs. +#[test] +fn the_descriptor_number_is_honoured_and_validated() { + let (repo, id, keys) = repo_with("fdnum", &[("S", b"v".to_vec())]); + let out = run_fd(&repo, &id, "9", r#"test "$SC_SECRETS_FD" = 9 && cat <&9"#); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(out.stdout, b"S=v\0"); + + for bad in ["0", "1", "2", "-1", "1024"] { + let out = run_fd(&repo, &id, bad, "echo ran"); + assert!(!out.status.success(), "fd {bad} must be refused"); + assert!( + !String::from_utf8_lossy(&out.stdout).contains("ran"), + "the command must not run for fd {bad}" + ); + } + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A payload larger than the pipe buffer reaches the child whole, and a child +/// that never reads it does not hang the parent. +#[test] +fn a_large_payload_is_delivered_and_an_unread_one_does_not_hang() { + let big = vec![b'x'; 300_000]; + let (repo, id, keys) = repo_with("big", &[("BIG", big)]); + let out = run_fd(&repo, &id, "3", "wc -c <&3"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let n: usize = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap(); + assert_eq!(n, "BIG=".len() + 300_000 + 1); + + // The child exits without reading: sc must still return. + let mut child = Command::new(env!("CARGO_BIN_EXE_sc")) + .args([ + "run", + "--identity", + id.to_str().unwrap(), + "--secrets-fd", + "3", + "--", + "true", + ]) + .current_dir(&repo) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let start = std::time::Instant::now(); + let status = loop { + if let Some(s) = child.try_wait().unwrap() { + break s; + } + if start.elapsed() > std::time::Duration::from_secs(30) { + let _ = child.kill(); + panic!("sc run hung with an unread payload"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + }; + assert!(status.success()); + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A value that cannot be framed (it holds a NUL byte) is refused, naming the +/// secret, and the command does not run. +#[test] +fn a_secret_holding_a_nul_byte_is_refused() { + let (repo, id, keys) = repo_with("nul", &[("BAD", b"a\0b".to_vec())]); + let out = run_fd(&repo, &id, "3", "echo ran"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("BAD") && err.contains("NUL"), "{err}"); + assert!(!String::from_utf8_lossy(&out.stdout).contains("ran")); + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// Whatever descriptor is asked for, a command that cannot be executed fails +/// with its real error: the requested number must not clobber the descriptor +/// the standard library uses to report an exec failure. +#[test] +fn a_missing_command_reports_its_error_for_every_nearby_descriptor() { + let (repo, id, keys) = repo_with("noexec", &[("S", b"v".to_vec())]); + for fd in 3..=12 { + let out = sc( + &repo, + &[ + "run", + "--identity", + id.to_str().unwrap(), + "--secrets-fd", + &fd.to_string(), + "--", + "/definitely/not/a/command", + ], + ); + assert!(!out.status.success(), "fd {fd}: must fail"); + let err = String::from_utf8_lossy(&out.stderr).to_lowercase(); + assert!( + err.contains("no such file") || err.contains("not found"), + "fd {fd}: expected the exec error, got {err:?}" + ); + } + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A descendant that keeps the descriptor open after the command exits cannot +/// keep `sc run` (or the unread payload) alive. +#[test] +fn a_grandchild_holding_the_descriptor_does_not_pin_sc_run() { + let (repo, id, keys) = repo_with("grandchild", &[("BIG", vec![b'x'; 300_000])]); + let start = std::time::Instant::now(); + // The shell backgrounds a sleeper that inherits fd 3, never reads it, and exits. + let out = run_fd(&repo, &id, "3", "sleep 30 >/dev/null 2>&1 & exit 0"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!( + start.elapsed() < std::time::Duration::from_secs(15), + "sc run waited on the grandchild: {:?}", + start.elapsed() + ); + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A name that cannot be framed (empty, or holding `=`) is refused before the +/// command runs, whether or not `secret add` let it be registered. +#[test] +fn a_secret_name_that_cannot_be_framed_is_refused() { + let root = tmp("badname"); + let keys = tmp("badname-keys"); + let id = keys.join("alice.id"); + let out = sc(&keys, &["keygen", "--out", id.to_str().unwrap()]); + let pk = String::from_utf8_lossy(&out.stdout) + .lines() + .find(|l| l.contains("public key")) + .and_then(|l| l.split_whitespace().find(|w| w.starts_with("scl-pk-"))) + .unwrap() + .to_string(); + let repo = root.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + assert!(sc(&repo, &["init"]).status.success()); + std::fs::write( + repo.join(".sc/recipients.toml"), + format!("[recipients]\nalice = \"{pk}\"\n"), + ) + .unwrap(); + let add = sc_stdin(&repo, &["secret", "add", "TOKEN=x", "--to", "alice"], b"v"); + if add.status.success() { + let out = run_fd(&repo, &id, "3", "echo ran"); + assert!(!out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("cannot be framed"), "{err}"); + assert!(!String::from_utf8_lossy(&out.stdout).contains("ran")); + } else { + // Registration already refuses it: nothing to frame, nothing to leak. + eprintln!("secret add refuses '=' in a name; the framing check is a backstop"); + } + std::fs::remove_dir_all(&root).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} + +/// A secret name already set in the caller's environment is removed from the +/// child's: the value delivered on the descriptor is the only one it sees. +#[test] +fn an_inherited_value_for_a_delivered_name_is_removed_from_the_environment() { + let (repo, id, keys) = repo_with("inherit", &[("DB_URL", b"real".to_vec())]); + let out = Command::new(env!("CARGO_BIN_EXE_sc")) + .args([ + "run", + "--identity", + id.to_str().unwrap(), + "--secrets-fd", + "3", + "--", + "sh", + "-c", + r#"test -z "${DB_URL+set}" && cat <&3"#, + ]) + .current_dir(&repo) + .env("DB_URL", "stale-from-the-caller") + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(out.stdout, b"DB_URL=real\0"); + std::fs::remove_dir_all(repo.parent().unwrap()).unwrap(); + std::fs::remove_dir_all(&keys).unwrap(); +} diff --git a/crates/repo/src/secrets.rs b/crates/repo/src/secrets.rs index 3d43fbd6..e4850a51 100644 --- a/crates/repo/src/secrets.rs +++ b/crates/repo/src/secrets.rs @@ -337,8 +337,41 @@ impl Repo { identity: &SecretKey, strict: bool, ) -> Result> { - let reg = self.registry()?; let mut envs: Vec<(String, OsString)> = Vec::new(); + for (name, plaintext) in self.secret_values(identity, strict)? { + // The `OsString` produced below is the unavoidable hand-off: + // injecting a secret into a child's environment is an + // authorized LOCAL PROCESS context, NOT strong isolation — the + // decrypted secret is observable by same-user processes, crash + // dumps, and shell wrappers through the child environment. That + // copy is fundamentally un-zeroizable (the kernel owns it once + // the child is spawned) and is the accepted boundary, not a + // defect. `sc run --secrets-fd` avoids it (ADR-0052). + #[cfg(unix)] + let val = { + use std::os::unix::ffi::OsStrExt; + std::ffi::OsStr::from_bytes(&plaintext).to_os_string() + }; + #[cfg(not(unix))] + let val = OsString::from( + std::str::from_utf8(&plaintext) + .map_err(|_| Error::InvalidArgument(format!("secret {name} not UTF-8")))?, + ); + envs.push((name, val)); + } + Ok(envs) + } + + /// The decrypted values behind [`Repo::secret_env`], still in zeroizing + /// buffers: the one place registered secrets are opened for a process. + /// Same `strict` contract. + pub(crate) fn secret_values( + &self, + identity: &SecretKey, + strict: bool, + ) -> Result>)>> { + let reg = self.registry()?; + let mut out = Vec::new(); for (name, id) in reg { let obj = { let arc = self.store_arc(); @@ -350,34 +383,11 @@ impl Repo { _ => continue, }; match scl_crypto::open(&secret, identity) { + // Pin the type explicitly: if `scl_crypto::open` ever stops + // returning `Zeroizing>`, this line fails to compile. Ok(plaintext) => { - // Pin the type explicitly: if `scl_crypto::open` ever stops - // returning `Zeroizing>`, this line fails to compile. - // The `OsStr::from_bytes` below reads directly out of this - // buffer — no intermediate plain `Vec`/`String` copy — so the - // parent-side plaintext stays zeroized until `plaintext` - // drops at the end of this iteration. - // - // The `OsString` produced below is the unavoidable hand-off: - // injecting a secret into a child's environment is an - // authorized LOCAL PROCESS context, NOT strong isolation — - // the decrypted secret is observable by same-user processes, - // crash dumps, and shell wrappers through the child - // environment. That copy is fundamentally un-zeroizable (the - // kernel owns it once the child is spawned) and is the - // accepted boundary, not a defect. let plaintext: scl_crypto::Zeroizing> = plaintext; - #[cfg(unix)] - let val = { - use std::os::unix::ffi::OsStrExt; - std::ffi::OsStr::from_bytes(&plaintext).to_os_string() - }; - #[cfg(not(unix))] - let val = - OsString::from(std::str::from_utf8(&plaintext).map_err(|_| { - Error::InvalidArgument(format!("secret {name} not UTF-8")) - })?); - envs.push((name, val)); + out.push((name, plaintext)); } Err(scl_crypto::Error::NotARecipient) if strict => { return Err(Error::InvalidArgument(format!( @@ -390,7 +400,7 @@ impl Repo { Err(e) => return Err(e.into()), } } - Ok(envs) + Ok(out) } /// Decrypt all secrets the `identity` can read, inject into the environment, @@ -411,6 +421,218 @@ impl Repo { let status = command.status()?; Ok(status.code().unwrap_or(1)) } + + /// Like [`Repo::run`], but the secrets never enter the child's + /// environment: they are written to a pipe whose read end the child + /// inherits as file descriptor `fd` (ADR-0052). The payload is + /// NUL-terminated `NAME=VALUE` records, the shape of + /// `/proc//environ`; the child reads to EOF. The values therefore do + /// not show up in `/proc//environ`, are not inherited by every + /// descendant through the environment, and the parent's copy stays in a + /// zeroizing buffer. `SC_SECRETS_FD` (not a secret) tells the child which + /// descriptor to read. This is still an authorized local-process context, + /// not isolation: a same-user process can read the child's fd table, and + /// the child decides what happens to what it read. + /// + /// A payload larger than the pipe buffer (64 KiB on Linux) is delivered only + /// while the command is running: once it exits the writer stops, so a + /// command that backgrounds its consumer must read before it exits (a + /// smaller payload already sits whole in the pipe and survives). + /// + /// `fd` must be between 3 and 1023; a secret whose value holds a NUL byte is + /// refused (it could not be framed, and could not be an environment + /// value either). Unix only. + #[cfg(unix)] + pub fn run_with_secrets_fd( + &self, + identity: &SecretKey, + cmd: &[String], + fd: i32, + ) -> Result { + use std::os::fd::{AsRawFd, OwnedFd}; + use std::os::unix::process::CommandExt; + + self.refuse_on_private("sc run")?; + if !(3..=1023).contains(&fd) { + return Err(Error::InvalidArgument(format!( + "--secrets-fd must be between 3 and 1023 (0, 1 and 2 are stdin, stdout and stderr), got {fd}" + ))); + } + let (exe, args) = cmd + .split_first() + .ok_or_else(|| Error::InvalidArgument("empty command".into()))?; + + let values = self.secret_values(identity, false)?; + // Names are framed as `NAME=`: an empty one, or one holding `=` or NUL, + // would corrupt the record or forge another. + if let Some((name, _)) = values + .iter() + .find(|(n, _)| n.is_empty() || n.bytes().any(|b| b == b'=' || b == 0)) + { + return Err(Error::InvalidArgument(format!( + "secret name {name:?} cannot be framed for --secrets-fd (empty, or it holds '=' or NUL)" + ))); + } + if let Some((name, _)) = values.iter().find(|(_, v)| v.contains(&0)) { + return Err(Error::InvalidArgument(format!( + "secret {name} holds a NUL byte and cannot be framed for --secrets-fd" + ))); + } + // One allocation of the exact size: a Vec that grows moves, and the + // freed old buffer would keep plaintext that `Zeroizing` never wipes. + let total: usize = values.iter().map(|(n, v)| n.len() + 1 + v.len() + 1).sum(); + let mut payload: scl_crypto::Zeroizing> = + scl_crypto::Zeroizing::new(Vec::with_capacity(total)); + for (name, value) in &values { + payload.extend_from_slice(name.as_bytes()); + payload.push(b'='); + payload.extend_from_slice(value); + payload.push(0); + } + // The names delivered here must not also reach the child through an + // environment variable the caller already had set. + let delivered: Vec = values.iter().map(|(n, _)| n.clone()).collect(); + drop(values); + + let (reader, writer) = std::io::pipe()?; + let reader: OwnedFd = reader.into(); + let raw = reader.as_raw_fd(); + // `fd` may be a descriptor `std` would pick for its own exec-error pipe + // while it spawns, which the pre_exec dup2 below would then clobber. + // Hold `fd` open (close-on-exec) across the spawn when it is free; when + // it is already taken the probe lands higher and nothing needs holding. + let _reserved = reserve_fd(fd); + let mut command = Command::new(exe); + command.args(args); + for name in &delivered { + command.env_remove(name); + } + command.env("SC_SECRETS_FD", fd.to_string()); + // SAFETY: the closure only calls dup2 and fcntl, both async-signal-safe. + // The pipe's read end is close-on-exec, so it needs to land on `fd` + // (dup2 clears the flag on the copy) or have the flag cleared where it + // already is; the write end is close-on-exec and never reaches the child. + unsafe { + command.pre_exec(move || { + if raw == fd { + if libc::fcntl(fd, libc::F_SETFD, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + } else if libc::dup2(raw, fd) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let mut child = command.spawn()?; + // Only the child holds a read end now; a child that exits unread + // breaks the pipe and ends the writer instead of blocking it. + drop(reader); + drop(_reserved); + // The write end is non-blocking and fed by its own thread, so a payload + // larger than the pipe buffer cannot block the parent before the child + // has read it, and the thread stops once the child is gone even if a + // grandchild still holds the read end open (it is joined below, so the + // zeroizing buffer is wiped before this returns). + if set_nonblocking(&writer).is_err() { + let _ = child.kill(); + let _ = child.wait(); + return Err(Error::Io(std::io::Error::last_os_error())); + } + let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let thread_done = std::sync::Arc::clone(&done); + let spawned = std::thread::Builder::new() + .name("sc-secrets-fd".into()) + .spawn(move || feed_pipe(writer, payload, &thread_done)); + let feeder = match spawned { + Ok(h) => h, + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(Error::Io(e)); + } + }; + let status = child.wait(); + done.store(true, std::sync::atomic::Ordering::Release); + let _ = feeder.join(); + Ok(status?.code().unwrap_or(1)) + } + + /// `--secrets-fd` needs POSIX file descriptors. + #[cfg(not(unix))] + pub fn run_with_secrets_fd(&self, _: &SecretKey, _: &[String], _: i32) -> Result { + Err(Error::InvalidArgument( + "--secrets-fd is only available on unix".into(), + )) + } +} + +/// Hold descriptor `fd` open (close-on-exec) if it is free: a probe at the +/// lowest free descriptor at or above `fd` lands exactly on `fd` only when +/// nothing else has it. The held descriptor is closed when dropped. +#[cfg(unix)] +fn reserve_fd(fd: i32) -> Option { + use std::os::fd::{FromRawFd, OwnedFd}; + // SAFETY: opens /dev/null read-only and wraps the new descriptors, each + // owned exactly once. + unsafe { + let null = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC); + if null < 0 { + return None; + } + let null = OwnedFd::from_raw_fd(null); + let probe = libc::fcntl( + std::os::fd::AsRawFd::as_raw_fd(&null), + libc::F_DUPFD_CLOEXEC, + fd, + ); + if probe < 0 { + return None; + } + let probe = OwnedFd::from_raw_fd(probe); + (std::os::fd::AsRawFd::as_raw_fd(&probe) == fd).then_some(probe) + } +} + +/// Make the pipe's write end non-blocking (its own open file description, so +/// the child's read end is unaffected). +#[cfg(unix)] +fn set_nonblocking(w: &std::io::PipeWriter) -> std::io::Result<()> { + use std::os::fd::AsRawFd; + // SAFETY: fcntl on a descriptor this PipeWriter owns. + unsafe { + let fl = libc::fcntl(w.as_raw_fd(), libc::F_GETFL); + if fl < 0 || libc::fcntl(w.as_raw_fd(), libc::F_SETFL, fl | libc::O_NONBLOCK) < 0 { + return Err(std::io::Error::last_os_error()); + } + } + Ok(()) +} + +/// Write `payload` to the non-blocking pipe until it is all in, the reader is +/// gone, or `done` is set (the child exited): then the buffer is wiped on drop. +#[cfg(unix)] +fn feed_pipe( + mut w: std::io::PipeWriter, + payload: scl_crypto::Zeroizing>, + done: &std::sync::atomic::AtomicBool, +) { + use std::io::Write; + let mut off = 0; + while off < payload.len() { + match w.write(&payload[off..]) { + Ok(0) => return, + Ok(n) => off += n, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + if done.load(std::sync::atomic::Ordering::Acquire) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(_) => return, // the reader is gone (EPIPE) + } + } } /// Refuse an empty recipient set on every seal/wrap path (`secret_add`, diff --git a/demo/run_lifecycle_demo.sh b/demo/run_lifecycle_demo.sh index a8b5a33c..43891e64 100755 --- a/demo/run_lifecycle_demo.sh +++ b/demo/run_lifecycle_demo.sh @@ -38,6 +38,11 @@ OUT="$(SC_IDENTITY="$KEYS/escrow" "$SC" run -- sh -c 'printf %s "$DB_URL"')" [ "$OUT" = "v1" ] || { echo "FAIL: escrow did not recover rotated value ($OUT)"; exit 1; } echo " DB_URL=$OUT" +# ADR-0052: the same secret on a file descriptor, not in the environment. +FD_OUT="$(SC_IDENTITY="$KEYS/escrow" "$SC" run --secrets-fd 3 -- sh -c 'test -z "${DB_URL+set}" && cat <&3 | tr "\0" "\n"')" +[ "$FD_OUT" = "DB_URL=v1" ] || { echo "FAIL: --secrets-fd did not deliver the secret on fd 3 ($FD_OUT)"; exit 1; } +echo " --secrets-fd 3: $FD_OUT (not in the environment)" + echo echo "OK: rotation + escrow verified" echo "caveat: rotation cuts off future registry reads; the old ciphertext remains in history." diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index d4dc6252..46a877cd 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -28,18 +28,17 @@ too, not just the src-control-side metadata. wrappers can observe the plaintext through the child environment; this is fundamental to env-var injection. The parent's intermediate buffer is zeroized (best-effort), the child copy is not. -- **Re-affirmed (map ticket #31): fd/stdin injection stays deferred.** The - security claim for a non-env injection mode is mostly illusory against the - named adversary — a same-user attacker who can read the identity key file - and `.sc/` directly decrypts everything regardless of injection mechanism; - what fd/stdin would actually remove is *accidental* propagation (env dumps, - inheritance by grandchildren), which is hygiene, not attack surface. Env - stays the default contract for `sc run`, `sc work --with-secrets`, and `sc - ws run --with-secrets` alike. Revisit triggers: real committed-secret use in - agent sessions, or an observed env-leak incident class (agents dumping env - into logs or committed files) — at which point an additive fd-pipe opt-in - mode is the presumptive shape, since deferring an *additional* mode carries - no lock-in cost. +- **`sc run --secrets-fd N` (ADR-0052) is the opt-in non-env mode.** The earlier + re-affirmation (map ticket #31) kept fd injection deferred because the security + claim against a same-user attacker is mostly illusory: that attacker can read + the identity key file and `.sc/` directly and decrypt everything whatever the + injection mechanism. What a descriptor removes is *accidental* propagation: the + values are not in `/proc//environ`, not in an env dump a script or agent + logs, and not inherited by every descendant through the environment; the + parent's copy stays in a zeroizing buffer. It is hygiene, not isolation: a + 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`. - **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 diff --git a/docs/adr/0052-secret-injection-by-fd.md b/docs/adr/0052-secret-injection-by-fd.md new file mode 100644 index 00000000..54252c5a --- /dev/null +++ b/docs/adr/0052-secret-injection-by-fd.md @@ -0,0 +1,39 @@ +# ADR-0052: Secret injection by file descriptor (`sc run --secrets-fd`) + +- **Status:** Accepted (built) +- **Date:** 2026-10-19 +- **Builds on:** ADR-0008/0009 (committed secrets), ADR-0019 (secret lifecycle); the threat model's "fd/stdin injection stays deferred" note + +## Context + +`sc run` injects decrypted secrets as child-process environment variables. The threat model records that this is an authorized local-process context, not isolation, and that fd/stdin injection was deferred with an additive fd-pipe opt-in named as the presumptive shape. The honest claim for a descriptor is narrow: against a same-user attacker who can read the identity key and `.sc/` it changes nothing. What it removes is accidental propagation: values in `/proc//environ`, in an env dump that a script or an agent writes to a log or a committed file, and in the environment of every descendant. + +## Decision + +`sc run --secrets-fd N -- cmd` (`Repo::run_with_secrets_fd`, unix only): + +- The parent opens a pipe and gives the child the read end as descriptor `N`; the secrets are **not** put in the child's environment. `SC_SECRETS_FD=N` (not a secret) tells the child where to read. +- The payload is NUL-terminated `NAME=VALUE` records, the shape of `/proc//environ`, read to EOF. A shell can use `tr '\0' '\n' <&3` or `xargs -0`. +- `N` must be 3 to 1023. Descriptors 0, 1 and 2 are refused: the command keeps its stdio. +- A secret whose value holds a NUL byte, or whose name is empty or holds `=` or NUL, is refused before anything runs (it cannot be framed, and a forged record would otherwise reach the child). +- The write end is close-on-exec and never reaches the child; the read end is placed by `dup2` in `pre_exec` (or has close-on-exec cleared if it already sits at `N`). The parent drops its read end after the spawn, so a child that exits unread breaks the pipe. +- The requested descriptor is held open (close-on-exec) across the spawn when it is free, so the standard library cannot pick it for its own exec-error pipe and have the `dup2` clobber it; without that, asking for the descriptor `std` happens to choose makes a failed `exec` abort the child instead of reporting the error. +- The write end is non-blocking and fed by its own thread, so a payload larger than the pipe buffer cannot block the parent before the child has read it. The thread stops when the child has exited (the parent sets a flag and joins it), so a child that never reads does not hang `sc run` and a grandchild that keeps the descriptor open cannot pin the thread or the plaintext buffer. The payload is allocated once at its exact size, because a growing `Vec` leaves freed copies that `Zeroizing` never wipes, and the thread's drop wipes it. +- A descendant that inherits the descriptor and keeps it can still read it: closing or sealing the descriptor is the consumer's job. +- A payload larger than the pipe buffer (64 KiB on Linux) is delivered only while the command is running. Once the command exits the writer stops, so a command that daemonizes a consumer must read before it exits; waiting for a reader that may never come would pin the writer and the plaintext (the grandchild case). A smaller payload sits whole in the pipe and survives the exit. +- A secret name already present in the caller's environment is removed from the child's, so the descriptor holds the only value. +- The decrypted values now stay in `Zeroizing` buffers from `secret_values` all the way to the pipe; the environment path converts them to `OsString` as before (the un-zeroizable hand-off the threat model already names). + +## Not decided here + +`sc ws run --with-secrets` and `sc work --with-secrets` keep the environment, and there is no stdin variant (it would take the command's stdin). Both are additive and can follow if a user needs them. + +## Consequences + +- The default contract does not change: without the flag `sc run` behaves exactly as before. +- It is hygiene, not isolation. A same-user process can read the child's descriptor table, and the child decides what to do with what it read; a child that re-exports its secrets into its own environment has undone the benefit. +- Unix only. Other targets refuse the flag with a clear error. + +## Tests + +`crates/cli/tests/secrets_fd.rs`: the secrets arrive on the descriptor as framed records and are absent from the environment, which names the descriptor; the default environment path is unchanged; another descriptor number works and 0, 1, 2, -1 and 1024 are refused before the command runs; a 300 kB payload arrives whole; a child that never reads, and a grandchild that keeps the descriptor, do not hang `sc run`; a missing command reports its real error for every nearby descriptor number; a NUL-bearing value and an unframeable name are refused. diff --git a/docs/adr/README.md b/docs/adr/README.md index 75b6325c..6f3f16db 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -62,6 +62,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0049](0049-merge-on-partial-clones.md) | Merge on partial clones | Proposed (37c-i to 37c-iv built) | 37c | | [0050](0050-sessions-on-partial-clones.md) | Agent sessions on partial clones | Accepted | 37d | | [0051](0051-rotate-protected-paths.md) | Rotating protected paths (`sc rewrap --rotate`) | Accepted | — | +| [0052](0052-secret-injection-by-fd.md) | Secret injection by file descriptor (`sc run --secrets-fd`) | Accepted | — | 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,