From 1c594493a634d2088d152cf1dd2b73853cec7eb4 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 08:32:07 +0300 Subject: [PATCH 1/3] fix(repo): run the protected cache cacheless where .sc/local-key cannot be restricted On non-unix targets there is no owner-only create path for the key, so create no .sc/local-key, ignore any existing one, persist no cache file, and warn once on stderr. Spurious re-seals, never incorrectness. Refs #214 --- CLAUDE.md | 3 +- ROADMAP.md | 9 +- crates/repo/src/cache.rs | 139 +++++++++++++++--- crates/repo/src/repo.rs | 38 +++++ docs/THREAT-MODEL.md | 10 ++ .../0043-randomized-protected-encryption.md | 3 +- 6 files changed, 177 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7c22a353..c90d7867 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -199,7 +199,8 @@ transport-adjacent. The rest, imperatively: - **`.sc/local-key` and the per-checkout protected caches (`.sc/protected-cache`, `.sc/ws/cache-`) are never committed and never transferred.** Cache saves are best-effort and ordered after ref moves; a - cache failure may cause a spurious re-seal but never incorrectness. + cache failure may cause a spurious re-seal but never incorrectness. On + non-unix targets no key is created and the cache is off (#214). - **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 8ee5352b..6fb91816 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -795,10 +795,11 @@ scale-&-reach horizon): `sc resolve --theirs` protected path keeps their ciphertext instead of re-sealing; their wrap list must be in the unioned protection, and a lookup gap on a partial clone just seals. -- **Non-unix local-key fallback (P33 final-review follow-on).** `.sc/local-key` - 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. +- **Non-unix local-key fallback — shipped (#214).** Where `.sc/local-key` cannot + be restricted to its owner (non-unix) no key file is created and the protected + cache runs cacheless with a one-time warning (spurious re-seals, never + incorrect). Still deferred: a real Windows ACL path that would keep the cache + on; the cacheless branch is unverified on a Windows host. - **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 diff --git a/crates/repo/src/cache.rs b/crates/repo/src/cache.rs index 8a33f612..9e59a2dc 100644 --- a/crates/repo/src/cache.rs +++ b/crates/repo/src/cache.rs @@ -7,6 +7,9 @@ //! The tag is `blake3::keyed_hash(local_key, plaintext)` under a random //! per-repo key (`.sc/local-key`, 0600), so the cache file alone leaks //! nothing — it does not reintroduce the equality oracle this phase closes. +//! Where the key file's permissions cannot be restricted (non-unix; #214) no +//! key file is created and no cache is read or written: see +//! [`can_restrict_permissions`]. //! A lost/stale/corrupt cache degrades to spurious re-seals, never //! incorrectness and never a hard error. //! @@ -31,16 +34,64 @@ use scl_core::ObjectId; use crate::error::{Error, Result}; use crate::layout::Layout; +/// Whether `.sc/local-key` can be created readable by its owner only. Only +/// unix can (`mode(0o600)` from the first byte); there is no Windows ACL path +/// (#214), so elsewhere the cache runs cacheless rather than leave the key +/// world-readable. Tests force `false` via `FORCE_CACHELESS` to exercise it. +fn can_restrict_permissions() -> bool { + #[cfg(test)] + if FORCE_CACHELESS.with(|f| f.get()) { + return false; + } + cfg!(unix) +} + +#[cfg(test)] +thread_local! { + static FORCE_CACHELESS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Test seam: make this thread behave like a non-unix target. +#[cfg(test)] +pub(crate) fn force_cacheless_for_test(on: bool) { + FORCE_CACHELESS.with(|f| f.set(on)); +} + +/// Print the cacheless warning the first time `flag` is unset; `true` iff it +/// printed. The flag is a parameter so a test can use a private one. +fn warn_cacheless_once(flag: &std::sync::atomic::AtomicBool) -> bool { + if flag.swap(true, std::sync::atomic::Ordering::Relaxed) { + return false; + } + eprintln!( + "warning: this platform cannot restrict .sc/local-key to its owner; the \ + protected-file cache is disabled (unchanged protected files will be \ + re-sealed on each commit and may show as modified)" + ); + true +} + /// Load (minting if absent) the per-repo random cache key. The key file is /// the only hard-error surface here: if it can't be created/read, the cache /// cannot be safely keyed, so surface it rather than running unkeyed. /// +/// When permissions cannot be restricted (see [`can_restrict_permissions`]) +/// this touches no file: it warns once and returns a fresh in-memory key, and +/// [`ProtectedCache::open`] then drops its path so nothing keyed by that +/// throwaway key is read or persisted. A pre-existing `.sc/local-key` is +/// ignored in that mode. +/// /// Mirrors the serve-TLS key discipline (`crates/tlsio/src/identity.rs`): /// the file is created 0600 from its first byte via `create_new`, so there /// is never a window where the key sits at default permissions. A /// concurrent minter losing the `create_new` race falls through to reading /// the winner's file rather than erroring or clobbering it. pub(crate) fn local_key(layout: &Layout) -> Result<[u8; 32]> { + if !can_restrict_permissions() { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + warn_cacheless_once(&WARNED); + return Ok(*blake3::hash(scl_crypto::random_hex(32).as_bytes()).as_bytes()); + } let path = layout.local_key_path(); let hex_str = match std::fs::read_to_string(&path) { Ok(s) => s.trim().to_string(), @@ -65,26 +116,25 @@ pub(crate) fn local_key(layout: &Layout) -> Result<[u8; 32]> { .map_err(|_| Error::InvalidArgument("malformed .sc/local-key".into())) } -#[cfg(unix)] -fn write_key_0600(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(path)?; - f.write_all(bytes) -} - -#[cfg(not(unix))] +/// Create the key file owner-only from its first byte. Unreachable off unix: +/// `local_key` goes cacheless first. fn write_key_0600(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - use std::io::Write; - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(path)?; - f.write_all(bytes) + #[cfg(unix)] + { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path)?; + f.write_all(bytes) + } + #[cfg(not(unix))] + { + let _ = (path, bytes); + Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) + } } #[derive(Clone, Copy, Debug, PartialEq)] @@ -151,6 +201,9 @@ fn is_plain_file(root: &Path, rel: &str) -> bool { impl ProtectedCache { pub(crate) fn open(key: [u8; 32], root: PathBuf, path: Option) -> ProtectedCache { + // Cacheless platform: `key` is a throwaway, so a persisted file could + // never be matched or reused; keep the cache in memory only. + let path = path.filter(|_| can_restrict_permissions()); let mut entries = BTreeMap::new(); if let Some(p) = &path { if let Ok(text) = std::fs::read_to_string(p) { @@ -322,6 +375,54 @@ mod tests { cleanup(&layout); } + #[test] + fn cacheless_mints_no_key_and_persists_nothing() { + FORCE_CACHELESS.with(|f| f.set(true)); + let layout = tmp("cacheless"); + let key = local_key(&layout).unwrap(); + assert_ne!(key, local_key(&layout).unwrap(), "throwaway key per call"); + assert!(!layout.local_key_path().exists(), "no key file"); + + let abs = layout.root.join("secret.txt"); + std::fs::write(&abs, b"v1").unwrap(); + let id = ObjectId::of(b"cipher-of-v1"); + let mut c = ProtectedCache::open( + key, + layout.root.clone(), + Some(layout.protected_cache_path()), + ); + c.record("secret.txt", b"v1", id); + assert_eq!(c.unchanged("secret.txt", b"v1"), Some(id), "in-process hit"); + c.save().unwrap(); + assert!(!layout.protected_cache_path().exists(), "nothing persisted"); + + // A cache file left by a unix run is not consulted. + FORCE_CACHELESS.with(|f| f.set(false)); + let mut c = ProtectedCache::open( + key, + layout.root.clone(), + Some(layout.protected_cache_path()), + ); + c.record("secret.txt", b"v1", id); + c.save().unwrap(); + FORCE_CACHELESS.with(|f| f.set(true)); + let c = ProtectedCache::open( + key, + layout.root.clone(), + Some(layout.protected_cache_path()), + ); + assert_eq!(c.unchanged("secret.txt", b"v1"), None); + FORCE_CACHELESS.with(|f| f.set(false)); + cleanup(&layout); + } + + #[test] + fn cacheless_warning_prints_once() { + let flag = std::sync::atomic::AtomicBool::new(false); + assert!(warn_cacheless_once(&flag)); + assert!(!warn_cacheless_once(&flag)); + } + #[test] fn tag_is_authoritative_for_hits_and_misses() { let layout = tmp("hits"); diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 5e960e96..1a17dbda 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -4608,6 +4608,44 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + #[test] + fn cacheless_platform_commits_correctly_without_a_key_file() { + // #214: where `.sc/local-key` cannot be restricted, no key or cache + // file is created and protected files re-seal on each commit (never + // incorrectly): the sealed blobs still decrypt to the plaintext. + crate::cache::force_cacheless_for_test(true); + let root = tmp_root("p33-cacheless"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", std::slice::from_ref(&alice_pk), None) + .unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/x"), b"top secret").unwrap(); + let c1 = repo.commit("alice", "one").unwrap(); + std::fs::write(root.join("readme.md"), b"hello").unwrap(); + let c2 = repo.commit("alice", "two").unwrap(); + for c in [&c1, &c2] { + let id = p33_entry_id(&repo, c, "secret/x"); + let bytes = p33_blob_bytes(&repo, &id); + let snap = repo.snapshot(c).unwrap(); + let got = crate::protect::decrypt_with( + &bytes, + &id, + &[&snap.protection], + &alice_sk, + "secret/x", + ) + .unwrap(); + assert_eq!(&got[..], b"top secret"); + } + assert!(!repo.layout().local_key_path().exists()); + assert!(!repo.layout().protected_cache_path().exists()); + + crate::cache::force_cacheless_for_test(false); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn protect_grant_and_revoke_append_oplog_records() { let root = tmp_root("oplog-protect"); diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index ba8d9ed0..51c5061a 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -81,6 +81,16 @@ too, not just the src-control-side metadata. protected blob under a fresh key (ADR-0051), whereas a plain `sc rewrap` only replaces wrap lists and leaves the key a revoked holder already has. History keeps the old wraps and ciphertext regardless. +- **Local cache key is unix-only (P33, #214):** the unchanged-detection cache is + keyed by `.sc/local-key`, created `0600` from its first byte. Leaking that key + lets a local reader test guesses against cached plaintext tags. Only unix can + restrict the file this way; on a non-unix target `sc` creates no key file, + ignores any existing one, reads and writes no `.sc/protected-cache` or + `.sc/ws/cache-`, and prints a one-time stderr warning. It runs cacheless: + unchanged protected files re-seal on each commit (new random ciphertext ids) + and `status` may list them as modified, but results are never incorrect. The + non-unix branch is compiled but unverified on a real Windows host; there is no + ACL hardening. ## Private branches (`sc branch --private` / `sc branch publish`) — ADR-0044 diff --git a/docs/adr/0043-randomized-protected-encryption.md b/docs/adr/0043-randomized-protected-encryption.md index b3bedabc..edcc25d9 100644 --- a/docs/adr/0043-randomized-protected-encryption.md +++ b/docs/adr/0043-randomized-protected-encryption.md @@ -101,7 +101,8 @@ file changed. Detection is a per-checkout stat cache (`crates/repo/src/cache.rs` - `.sc/local-key`: 32 random bytes, mode **0600 from first byte** (via `OpenOptions::create_new` + `mode(0o600)`, so the file is never briefly world-readable between creation and permission-setting), created lazily, - **never committed, never transferred**. The per-checkout cache file itself + **never committed, never transferred**. Off unix (#214) no key file is made + and the cache runs cacheless with a one-time warning. The per-checkout cache file itself (below) is written via `atomic_write_durable`. - Per-checkout cache files: `.sc/protected-cache` for the main working tree; `.sc/ws/cache-` per ws workspace (see below). Each entry is From f3a1e43eb3b09eadb776754b520b246b7063c097 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 08:42:06 +0300 Subject: [PATCH 2/3] fix(repo): delete a legacy local-key when cacheless; document the status gate gap Refs #214 --- crates/repo/src/cache.rs | 8 ++++++-- docs/THREAT-MODEL.md | 12 ++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/repo/src/cache.rs b/crates/repo/src/cache.rs index 9e59a2dc..7f387177 100644 --- a/crates/repo/src/cache.rs +++ b/crates/repo/src/cache.rs @@ -79,7 +79,7 @@ fn warn_cacheless_once(flag: &std::sync::atomic::AtomicBool) -> bool { /// this touches no file: it warns once and returns a fresh in-memory key, and /// [`ProtectedCache::open`] then drops its path so nothing keyed by that /// throwaway key is read or persisted. A pre-existing `.sc/local-key` is -/// ignored in that mode. +/// deleted in that mode. /// /// Mirrors the serve-TLS key discipline (`crates/tlsio/src/identity.rs`): /// the file is created 0600 from its first byte via `create_new`, so there @@ -90,6 +90,9 @@ pub(crate) fn local_key(layout: &Layout) -> Result<[u8; 32]> { if !can_restrict_permissions() { static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); warn_cacheless_once(&WARNED); + // An earlier build may have left a world-readable key; the cache is + // off, so drop it rather than leave it guessable-against. + let _ = std::fs::remove_file(layout.local_key_path()); return Ok(*blake3::hash(scl_crypto::random_hex(32).as_bytes()).as_bytes()); } let path = layout.local_key_path(); @@ -379,9 +382,10 @@ mod tests { fn cacheless_mints_no_key_and_persists_nothing() { FORCE_CACHELESS.with(|f| f.set(true)); let layout = tmp("cacheless"); + std::fs::write(layout.local_key_path(), "legacy").unwrap(); let key = local_key(&layout).unwrap(); assert_ne!(key, local_key(&layout).unwrap(), "throwaway key per call"); - assert!(!layout.local_key_path().exists(), "no key file"); + assert!(!layout.local_key_path().exists(), "legacy key removed"); let abs = layout.root.join("secret.txt"); std::fs::write(&abs, b"v1").unwrap(); diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 51c5061a..27cfccef 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -85,12 +85,16 @@ too, not just the src-control-side metadata. keyed by `.sc/local-key`, created `0600` from its first byte. Leaking that key lets a local reader test guesses against cached plaintext tags. Only unix can restrict the file this way; on a non-unix target `sc` creates no key file, - ignores any existing one, reads and writes no `.sc/protected-cache` or + deletes any existing one (it may have been created world-readable by an earlier + build), reads and writes no `.sc/protected-cache` or `.sc/ws/cache-`, and prints a one-time stderr warning. It runs cacheless: unchanged protected files re-seal on each commit (new random ciphertext ids) - and `status` may list them as modified, but results are never incorrect. The - non-unix branch is compiled but unverified on a real Windows host; there is no - ACL hardening. + and `status` lists every authorized randomized protected file as modified, so + the clean-tree gates (switch, merge, ...) refuse while one is checked out. No + wrong data is committed, but this is a known usability gap on those targets. The + non-unix branch has not been compiled or run on a Windows host; there is no + ACL hardening. A unix filesystem that ignores mode bits (vfat, exFAT, some + network mounts) is not detected. ## Private branches (`sc branch --private` / `sc branch publish`) — ADR-0044 From 5f79ed34e5bef3982cf7e99b49c8e0a531fdfa24 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 08:53:14 +0300 Subject: [PATCH 3/3] fix(repo): warn once instead of going cacheless when local-key cannot be restricted Rework of the #214 approach: cacheless made status and the clean-tree gates refuse for non-unix users with protected files. Keep the key and caches, and warn once when a cache holds a protected entry. Windows ACL stays deferred. Refs #214 --- CLAUDE.md | 5 +- ROADMAP.md | 11 +- crates/repo/src/cache.rs | 134 ++++++++---------- crates/repo/src/repo.rs | 38 ----- docs/THREAT-MODEL.md | 27 ++-- .../0043-randomized-protected-encryption.md | 6 +- 6 files changed, 86 insertions(+), 135 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c90d7867..2a8fd673 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -199,8 +199,9 @@ transport-adjacent. The rest, imperatively: - **`.sc/local-key` and the per-checkout protected caches (`.sc/protected-cache`, `.sc/ws/cache-`) are never committed and never transferred.** Cache saves are best-effort and ordered after ref moves; a - cache failure may cause a spurious re-seal but never incorrectness. On - non-unix targets no key is created and the cache is off (#214). + cache failure may cause a spurious re-seal but never incorrectness. The key + is owner-only on unix only; non-unix keeps default permissions and warns once + (#214, ACL deferred). - **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 6fb91816..59b31d23 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -795,11 +795,12 @@ scale-&-reach horizon): `sc resolve --theirs` protected path keeps their ciphertext instead of re-sealing; their wrap list must be in the unioned protection, and a lookup gap on a partial clone just seals. -- **Non-unix local-key fallback — shipped (#214).** Where `.sc/local-key` cannot - be restricted to its owner (non-unix) no key file is created and the protected - cache runs cacheless with a one-time warning (spurious re-seals, never - incorrect). Still deferred: a real Windows ACL path that would keep the cache - on; the cacheless branch is unverified on a Windows host. +- **Non-unix local-key permissions (#214, P33 follow-on).** `.sc/local-key` is + minted 0600-from-first-byte on unix only. On a non-unix target it keeps default + permissions and `sc` warns once when a cache holds a protected entry (the + exposure is bounded; see THREAT-MODEL.md). Deferred: an owner-only Windows ACL + (`windows-sys` is already in `Cargo.lock`) and a manual check on a real Windows + host. - **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 diff --git a/crates/repo/src/cache.rs b/crates/repo/src/cache.rs index 7f387177..88034aea 100644 --- a/crates/repo/src/cache.rs +++ b/crates/repo/src/cache.rs @@ -7,11 +7,11 @@ //! The tag is `blake3::keyed_hash(local_key, plaintext)` under a random //! per-repo key (`.sc/local-key`, 0600), so the cache file alone leaks //! nothing — it does not reintroduce the equality oracle this phase closes. -//! Where the key file's permissions cannot be restricted (non-unix; #214) no -//! key file is created and no cache is read or written: see -//! [`can_restrict_permissions`]. //! A lost/stale/corrupt cache degrades to spurious re-seals, never //! incorrectness and never a hard error. +//! Where the key file cannot be made owner-only (non-unix; #214) it is +//! still written with default permissions and a one-time warning is printed +//! once the cache holds a protected entry: see [`can_restrict_permissions`]. //! //! **The keyed tag is the sole authority for a hit.** `mtime_ns`/`size` are //! recorded for documentation (when the entry was observed) and as a @@ -36,11 +36,11 @@ use crate::layout::Layout; /// Whether `.sc/local-key` can be created readable by its owner only. Only /// unix can (`mode(0o600)` from the first byte); there is no Windows ACL path -/// (#214), so elsewhere the cache runs cacheless rather than leave the key -/// world-readable. Tests force `false` via `FORCE_CACHELESS` to exercise it. +/// yet (#214), so elsewhere the key keeps default permissions and a warning is +/// printed. Tests force `false` via `force_unrestricted_for_test`. fn can_restrict_permissions() -> bool { #[cfg(test)] - if FORCE_CACHELESS.with(|f| f.get()) { + if FORCE_UNRESTRICTED.with(|f| f.get()) { return false; } cfg!(unix) @@ -48,53 +48,49 @@ fn can_restrict_permissions() -> bool { #[cfg(test)] thread_local! { - static FORCE_CACHELESS: std::cell::Cell = const { std::cell::Cell::new(false) }; + static FORCE_UNRESTRICTED: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Test seam: make this thread behave like a non-unix target. #[cfg(test)] -pub(crate) fn force_cacheless_for_test(on: bool) { - FORCE_CACHELESS.with(|f| f.set(on)); +pub(crate) fn force_unrestricted_for_test(on: bool) { + FORCE_UNRESTRICTED.with(|f| f.set(on)); } -/// Print the cacheless warning the first time `flag` is unset; `true` iff it -/// printed. The flag is a parameter so a test can use a private one. -fn warn_cacheless_once(flag: &std::sync::atomic::AtomicBool) -> bool { +/// Print the unrestricted-key warning the first time `flag` is unset; `true` +/// iff it printed. The flag is a parameter so a test can use a private one. +fn warn_unrestricted_once(flag: &std::sync::atomic::AtomicBool) -> bool { if flag.swap(true, std::sync::atomic::Ordering::Relaxed) { return false; } eprintln!( - "warning: this platform cannot restrict .sc/local-key to its owner; the \ - protected-file cache is disabled (unchanged protected files will be \ - re-sealed on each commit and may show as modified)" + "warning: this platform cannot restrict .sc/local-key to its owner; other \ + local users may be able to read it and test guesses against the \ + protected-file cache tags (the protected plaintext checked out in the \ + working tree is equally readable by default)" ); true } +/// Warn (once per process) when a cache that holds protected entries is +/// backed by a key whose permissions could not be restricted. +fn warn_if_unrestricted(has_entries: bool) { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if has_entries && !can_restrict_permissions() { + warn_unrestricted_once(&WARNED); + } +} + /// Load (minting if absent) the per-repo random cache key. The key file is /// the only hard-error surface here: if it can't be created/read, the cache /// cannot be safely keyed, so surface it rather than running unkeyed. /// -/// When permissions cannot be restricted (see [`can_restrict_permissions`]) -/// this touches no file: it warns once and returns a fresh in-memory key, and -/// [`ProtectedCache::open`] then drops its path so nothing keyed by that -/// throwaway key is read or persisted. A pre-existing `.sc/local-key` is -/// deleted in that mode. -/// /// Mirrors the serve-TLS key discipline (`crates/tlsio/src/identity.rs`): /// the file is created 0600 from its first byte via `create_new`, so there /// is never a window where the key sits at default permissions. A /// concurrent minter losing the `create_new` race falls through to reading /// the winner's file rather than erroring or clobbering it. pub(crate) fn local_key(layout: &Layout) -> Result<[u8; 32]> { - if !can_restrict_permissions() { - static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - warn_cacheless_once(&WARNED); - // An earlier build may have left a world-readable key; the cache is - // off, so drop it rather than leave it guessable-against. - let _ = std::fs::remove_file(layout.local_key_path()); - return Ok(*blake3::hash(scl_crypto::random_hex(32).as_bytes()).as_bytes()); - } let path = layout.local_key_path(); let hex_str = match std::fs::read_to_string(&path) { Ok(s) => s.trim().to_string(), @@ -119,25 +115,27 @@ pub(crate) fn local_key(layout: &Layout) -> Result<[u8; 32]> { .map_err(|_| Error::InvalidArgument("malformed .sc/local-key".into())) } -/// Create the key file owner-only from its first byte. Unreachable off unix: -/// `local_key` goes cacheless first. +#[cfg(unix)] fn write_key_0600(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - #[cfg(unix)] - { - use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(path)?; - f.write_all(bytes) - } - #[cfg(not(unix))] - { - let _ = (path, bytes); - Err(std::io::Error::from(std::io::ErrorKind::Unsupported)) - } + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path)?; + f.write_all(bytes) +} + +/// Non-unix: default (inherited) permissions; see [`can_restrict_permissions`]. +#[cfg(not(unix))] +fn write_key_0600(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + f.write_all(bytes) } #[derive(Clone, Copy, Debug, PartialEq)] @@ -204,9 +202,6 @@ fn is_plain_file(root: &Path, rel: &str) -> bool { impl ProtectedCache { pub(crate) fn open(key: [u8; 32], root: PathBuf, path: Option) -> ProtectedCache { - // Cacheless platform: `key` is a throwaway, so a persisted file could - // never be matched or reused; keep the cache in memory only. - let path = path.filter(|_| can_restrict_permissions()); let mut entries = BTreeMap::new(); if let Some(p) = &path { if let Ok(text) = std::fs::read_to_string(p) { @@ -242,6 +237,9 @@ impl ProtectedCache { } } } + if path.is_some() { + warn_if_unrestricted(!entries.is_empty()); + } ProtectedCache { key, root, @@ -309,6 +307,7 @@ impl ProtectedCache { let Some(path) = &self.path else { return Ok(()); }; + warn_if_unrestricted(!self.entries.is_empty()); let mut out = String::new(); for (p, e) in &self.entries { if !is_plain_file(&self.root, p) { @@ -379,13 +378,12 @@ mod tests { } #[test] - fn cacheless_mints_no_key_and_persists_nothing() { - FORCE_CACHELESS.with(|f| f.set(true)); - let layout = tmp("cacheless"); - std::fs::write(layout.local_key_path(), "legacy").unwrap(); + fn unrestricted_key_still_persists_and_hits() { + force_unrestricted_for_test(true); + let layout = tmp("unrestricted"); let key = local_key(&layout).unwrap(); - assert_ne!(key, local_key(&layout).unwrap(), "throwaway key per call"); - assert!(!layout.local_key_path().exists(), "legacy key removed"); + assert_eq!(key, local_key(&layout).unwrap(), "key persisted"); + assert!(layout.local_key_path().exists()); let abs = layout.root.join("secret.txt"); std::fs::write(&abs, b"v1").unwrap(); @@ -396,35 +394,23 @@ mod tests { Some(layout.protected_cache_path()), ); c.record("secret.txt", b"v1", id); - assert_eq!(c.unchanged("secret.txt", b"v1"), Some(id), "in-process hit"); - c.save().unwrap(); - assert!(!layout.protected_cache_path().exists(), "nothing persisted"); - - // A cache file left by a unix run is not consulted. - FORCE_CACHELESS.with(|f| f.set(false)); - let mut c = ProtectedCache::open( - key, - layout.root.clone(), - Some(layout.protected_cache_path()), - ); - c.record("secret.txt", b"v1", id); c.save().unwrap(); - FORCE_CACHELESS.with(|f| f.set(true)); + assert!(layout.protected_cache_path().exists(), "cache persisted"); let c = ProtectedCache::open( key, layout.root.clone(), Some(layout.protected_cache_path()), ); - assert_eq!(c.unchanged("secret.txt", b"v1"), None); - FORCE_CACHELESS.with(|f| f.set(false)); + assert_eq!(c.unchanged("secret.txt", b"v1"), Some(id), "hit survives"); + force_unrestricted_for_test(false); cleanup(&layout); } #[test] - fn cacheless_warning_prints_once() { + fn unrestricted_warning_prints_once() { let flag = std::sync::atomic::AtomicBool::new(false); - assert!(warn_cacheless_once(&flag)); - assert!(!warn_cacheless_once(&flag)); + assert!(warn_unrestricted_once(&flag)); + assert!(!warn_unrestricted_once(&flag)); } #[test] diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 1a17dbda..5e960e96 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -4608,44 +4608,6 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } - #[test] - fn cacheless_platform_commits_correctly_without_a_key_file() { - // #214: where `.sc/local-key` cannot be restricted, no key or cache - // file is created and protected files re-seal on each commit (never - // incorrectly): the sealed blobs still decrypt to the plaintext. - crate::cache::force_cacheless_for_test(true); - let root = tmp_root("p33-cacheless"); - let repo = Repo::init(&root).unwrap(); - let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); - repo.protect("secret/", std::slice::from_ref(&alice_pk), None) - .unwrap(); - std::fs::create_dir_all(root.join("secret")).unwrap(); - std::fs::write(root.join("secret/x"), b"top secret").unwrap(); - let c1 = repo.commit("alice", "one").unwrap(); - std::fs::write(root.join("readme.md"), b"hello").unwrap(); - let c2 = repo.commit("alice", "two").unwrap(); - for c in [&c1, &c2] { - let id = p33_entry_id(&repo, c, "secret/x"); - let bytes = p33_blob_bytes(&repo, &id); - let snap = repo.snapshot(c).unwrap(); - let got = crate::protect::decrypt_with( - &bytes, - &id, - &[&snap.protection], - &alice_sk, - "secret/x", - ) - .unwrap(); - assert_eq!(&got[..], b"top secret"); - } - assert!(!repo.layout().local_key_path().exists()); - assert!(!repo.layout().protected_cache_path().exists()); - - crate::cache::force_cacheless_for_test(false); - drop(repo); - std::fs::remove_dir_all(&root).unwrap(); - } - #[test] fn protect_grant_and_revoke_append_oplog_records() { let root = tmp_root("oplog-protect"); diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 27cfccef..eaff8843 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -81,20 +81,19 @@ too, not just the src-control-side metadata. protected blob under a fresh key (ADR-0051), whereas a plain `sc rewrap` only replaces wrap lists and leaves the key a revoked holder already has. History keeps the old wraps and ciphertext regardless. -- **Local cache key is unix-only (P33, #214):** the unchanged-detection cache is - keyed by `.sc/local-key`, created `0600` from its first byte. Leaking that key - lets a local reader test guesses against cached plaintext tags. Only unix can - restrict the file this way; on a non-unix target `sc` creates no key file, - deletes any existing one (it may have been created world-readable by an earlier - build), reads and writes no `.sc/protected-cache` or - `.sc/ws/cache-`, and prints a one-time stderr warning. It runs cacheless: - unchanged protected files re-seal on each commit (new random ciphertext ids) - and `status` lists every authorized randomized protected file as modified, so - the clean-tree gates (switch, merge, ...) refuse while one is checked out. No - wrong data is committed, but this is a known usability gap on those targets. The - non-unix branch has not been compiled or run on a Windows host; there is no - ACL hardening. A unix filesystem that ignores mode bits (vfat, exFAT, some - network mounts) is not detected. +- **Local cache key is owner-only on unix only (P33, #214):** the + unchanged-detection cache is keyed by `.sc/local-key`, created `0600` from its + first byte. Only unix can do that; on a non-unix target the key and the cache + files are written with inherited default permissions, and `sc` prints a + one-time stderr warning once a cache holds a protected entry. The exposure is + small: checkout already writes protected plaintext into the working tree with + default permissions on every platform, and the cache holds tags only for files + whose plaintext is on disk, so a reader of the key could read that plaintext + directly. What remains is the tags of the last-committed version of a file + edited since, and stale entries until the next save. The real fix is an + owner-only Windows ACL (`windows-sys` is already a transitive dependency); it is + unverified without a Windows host and tracked in ROADMAP.md. A unix filesystem + that ignores mode bits (vfat, exFAT, some network mounts) is not detected. ## Private branches (`sc branch --private` / `sc branch publish`) — ADR-0044 diff --git a/docs/adr/0043-randomized-protected-encryption.md b/docs/adr/0043-randomized-protected-encryption.md index edcc25d9..1818cea8 100644 --- a/docs/adr/0043-randomized-protected-encryption.md +++ b/docs/adr/0043-randomized-protected-encryption.md @@ -101,8 +101,10 @@ file changed. Detection is a per-checkout stat cache (`crates/repo/src/cache.rs` - `.sc/local-key`: 32 random bytes, mode **0600 from first byte** (via `OpenOptions::create_new` + `mode(0o600)`, so the file is never briefly world-readable between creation and permission-setting), created lazily, - **never committed, never transferred**. Off unix (#214) no key file is made - and the cache runs cacheless with a one-time warning. The per-checkout cache file itself + **never committed, never transferred**. Non-unix targets cannot restrict it + (#214): it keeps default permissions with a one-time warning, because checkout + already writes the same plaintext to the working tree with default + permissions (see THREAT-MODEL.md). The per-checkout cache file itself (below) is written via `atomic_write_durable`. - Per-checkout cache files: `.sc/protected-cache` for the main working tree; `.sc/ws/cache-` per ws workspace (see below). Each entry is