From 9adae999bb896c5eba7aad4c5514017c028028ac Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 08:57:14 +0200 Subject: [PATCH 1/7] Reject symlinked directories in prompt write-back Rollback write-back only checked the leaf of each prompt path for a symlink, so a symlinked prompts directory or subdirectory could redirect writes and the orphan sweep outside the prompts root. It now refuses to run when prompts or any existing parent directory below the repo is a symlink, checked before and after creating directories, and the sweep refuses a symlinked root. The temp file used for atomic replacement is now created exclusively with a unique name that tree entries cannot use, so entries such as a.tmp and a.txt no longer collide and a planted link is never followed. --- crates/agenticd/src/rollback/writeback.rs | 250 +++++++++++++++++++++- 1 file changed, 244 insertions(+), 6 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index f525a7cf..76ee998d 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -18,6 +18,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use agentic_core::{Commit, Hash, ObjectKind}; use anyhow::{anyhow, Context}; @@ -41,13 +42,21 @@ use crate::server::DaemonState; /// outside the prompts directory), and the actual write is done as /// write-to-temp + atomic rename so a concurrent attacker can't plant a /// symlink between the unlink and the write. (Copilot review on PR #51.) +/// +/// Ancestor directories get the same treatment: `/prompts` and every +/// existing directory between it and a write target must not be a symlink +/// ([`reject_symlinked_dirs`]), checked before and after `create_dir_all`, +/// so a planted directory link can't redirect writes or the orphan sweep +/// outside the prompts root. pub(super) fn restore_prompts( state: &DaemonState, repo: &Path, prompts_hash: &Hash, ) -> anyhow::Result<()> { let dir = repo.join("prompts"); + reject_symlinked_dirs(repo, &dir)?; std::fs::create_dir_all(&dir)?; + reject_symlinked_dirs(repo, &dir)?; let tree = load_tree(state, prompts_hash)?; let mut wanted: BTreeSet = BTreeSet::new(); @@ -55,7 +64,9 @@ pub(super) fn restore_prompts( validate_tree_entry_name(name)?; let path = dir.join(name); if let Some(parent) = path.parent() { + reject_symlinked_dirs(repo, parent)?; std::fs::create_dir_all(parent)?; + reject_symlinked_dirs(repo, parent)?; } let blob = load_blob(state, &r.hash)?; write_blob_safely(&path, &blob.bytes)?; @@ -66,6 +77,47 @@ pub(super) fn restore_prompts( Ok(()) } +/// Fail if any existing component of `target` below `base` is a symlink. +/// `base` itself (and anything above it) is trusted: the repo root may +/// legitimately live under a symlinked path. Components that don't exist +/// yet are fine; any other `symlink_metadata` error propagates. +fn reject_symlinked_dirs(base: &Path, target: &Path) -> anyhow::Result<()> { + let mut cur = base.to_path_buf(); + for component in target.strip_prefix(base)?.components() { + cur.push(component); + match std::fs::symlink_metadata(&cur) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(anyhow!( + "refusing prompt write-back: {} is a symlink", + cur.display() + )); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => { + return Err(e).with_context(|| format!("inspecting {}", cur.display())); + } + } + } + Ok(()) +} + +/// Marker in temp file names. Tree entry names containing it are rejected +/// by [`validate_tree_entry_name`], so a temp name never equals an entry. +const TMP_MARKER: &str = ".agentic-tmp-"; +static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// Create `tmp` with `O_EXCL` semantics (`create_new`): fails if anything, +/// including a planted symlink, already exists there, and never follows one. +fn write_new_file(tmp: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(tmp)?; + f.write_all(bytes) +} + /// Write `bytes` to `path` safely: /// /// 1. If `path` already exists as a symlink, unlink it. Any other @@ -74,7 +126,8 @@ pub(super) fn restore_prompts( /// of the destination, since the attack we're defending against /// is a redirected write. Only `NotFound` is benign (the file /// doesn't exist yet, which is the common case). -/// 2. Write the new bytes to a sibling `.tmp` file, then atomically +/// 2. Write the new bytes to a uniquely named sibling temp file (created +/// exclusively, so a pre-planted symlink is never followed), then atomically /// `rename(2)` it over `path`. This closes the TOCTOU window /// between the symlink unlink and the regular file write: even if /// an attacker re-plants a symlink at `path` between steps, the @@ -99,11 +152,25 @@ fn write_blob_safely(path: &Path, bytes: &[u8]) -> anyhow::Result<()> { }); } } - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, bytes).with_context(|| format!("writing temp file {}", tmp.display()))?; - std::fs::rename(&tmp, path) - .with_context(|| format!("renaming {} → {}", tmp.display(), path.display()))?; - Ok(()) + let file_name = path + .file_name() + .ok_or_else(|| anyhow!("prompt path {} has no file name", path.display()))? + .to_string_lossy(); + let tmp = path.with_file_name(format!( + ".{file_name}{TMP_MARKER}{}-{}", + std::process::id(), + TMP_COUNTER.fetch_add(1, Ordering::Relaxed) + )); + let result = write_new_file(&tmp, bytes) + .with_context(|| format!("writing temp file {}", tmp.display())) + .and_then(|()| { + std::fs::rename(&tmp, path) + .with_context(|| format!("renaming {} → {}", tmp.display(), path.display())) + }); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result } /// Reject tree entry names that would escape the prompts directory or @@ -119,6 +186,12 @@ fn validate_tree_entry_name(name: &str) -> anyhow::Result<()> { } for component in Path::new(name).components() { match component { + Component::Normal(c) if c.to_string_lossy().contains(TMP_MARKER) => { + return Err(anyhow!( + "tree entry name {:?} uses the reserved temp-file marker {TMP_MARKER:?}", + name + )); + } Component::Normal(_) => {} _ => { return Err(anyhow!( @@ -140,7 +213,17 @@ fn validate_tree_entry_name(name: &str) -> anyhow::Result<()> { /// review on PR #51: the prior `ft.is_file()` branch silently left /// dangling symlinks behind even though the docs claimed everything /// not in the target tree is removed). +/// +/// Refuses to run on a symlinked `here` and never recurses through one +/// (`DirEntry::file_type` doesn't follow links, so a symlinked directory +/// is unlinked as an orphan, not descended into). fn sweep_orphans(root: &Path, here: &Path, wanted: &BTreeSet) -> anyhow::Result<()> { + if std::fs::symlink_metadata(here)?.file_type().is_symlink() { + return Err(anyhow!( + "refusing prompt sweep: {} is a symlink", + here.display() + )); + } for entry in std::fs::read_dir(here)? { let entry = entry?; let path = entry.path(); @@ -373,4 +456,159 @@ mod tests { .file_type() .is_file()); } + + #[test] + fn validate_rejects_reserved_temp_marker() { + let err = validate_tree_entry_name("dir/.a.md.agentic-tmp-1-0").unwrap_err(); + assert!(err.to_string().contains("reserved temp-file marker")); + } + + // Build a DaemonState over a fresh object store, commit `files` as a + // prompts tree, and return (state, tree hash, repo dir guard). + async fn state_with_prompts(files: &[(&str, &[u8])]) -> (DaemonState, Hash, tempfile::TempDir) { + use agentic_core::{Blob, FsObjectStore, Object, ObjectStore, Tree, TypedRef}; + use std::sync::Arc; + let repo = tempfile::tempdir().unwrap(); + let agentic_dir = repo.path().join(".agentic"); + std::fs::create_dir_all(agentic_dir.join("objects")).unwrap(); + let store: Arc = + Arc::new(FsObjectStore::open(agentic_dir.join("objects")).unwrap()); + let mut tree = Tree::new(); + for (name, bytes) in files { + let hash = store.put(&Object::Blob(Blob::new(bytes.to_vec()))).unwrap(); + tree.insert( + *name, + TypedRef { + kind: ObjectKind::Blob, + hash, + }, + ); + } + let tree_hash = store.put(&Object::Tree(tree)).unwrap(); + let state = DaemonState::open( + repo.path().to_path_buf(), + agentic_dir, + store, + None, + Vec::new(), + Vec::new(), + Arc::new(crate::peer_auth::PeerAuthPolicy::InsecureAllowAny), + ) + .await + .unwrap(); + (state, tree_hash, repo) + } + + // Outside dir pre-populated with a file the sweep would delete if it + // followed a link, plus a name the tree would write. + #[cfg(unix)] + fn outside_dir() -> tempfile::TempDir { + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep.txt"), b"outside").unwrap(); + outside + } + + #[cfg(unix)] + fn assert_outside_untouched(outside: &Path) { + let mut names: Vec<_> = std::fs::read_dir(outside) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert_eq!(names, vec!["keep.txt"], "outside dir must be untouched"); + assert_eq!(std::fs::read(outside.join("keep.txt")).unwrap(), b"outside"); + } + + #[cfg(unix)] + #[tokio::test] + async fn restore_prompts_rejects_symlinked_subdirectory() { + let (state, tree, repo) = state_with_prompts(&[("sub/x", b"payload")]).await; + let outside = outside_dir(); + std::fs::create_dir_all(repo.path().join("prompts")).unwrap(); + std::os::unix::fs::symlink(outside.path(), repo.path().join("prompts/sub")).unwrap(); + + let err = restore_prompts(&state, repo.path(), &tree).unwrap_err(); + assert!(err.to_string().contains("symlink"), "got {err}"); + assert_outside_untouched(outside.path()); + } + + #[cfg(unix)] + #[tokio::test] + async fn restore_prompts_rejects_symlinked_prompts_root() { + let (state, tree, repo) = state_with_prompts(&[("x", b"payload")]).await; + let outside = outside_dir(); + std::os::unix::fs::symlink(outside.path(), repo.path().join("prompts")).unwrap(); + + let err = restore_prompts(&state, repo.path(), &tree).unwrap_err(); + assert!(err.to_string().contains("symlink"), "got {err}"); + assert_outside_untouched(outside.path()); + } + + #[cfg(unix)] + #[test] + fn sweep_orphans_refuses_symlinked_root() { + let outside = outside_dir(); + let tmp = tempfile::tempdir().unwrap(); + let link = tmp.path().join("prompts"); + std::os::unix::fs::symlink(outside.path(), &link).unwrap(); + assert!(sweep_orphans(&link, &link, &BTreeSet::new()).is_err()); + assert_outside_untouched(outside.path()); + } + + #[tokio::test] + async fn restore_prompts_handles_tmp_and_md_siblings() { + // `a.txt` sorts after `a.tmp`, so the old `with_extension("tmp")` temp + // name for `a.txt` clobbered the already-restored `a.tmp`. + let (state, tree, repo) = state_with_prompts(&[ + ("a.md", b"markdown"), + ("a.tmp", b"tmpfile"), + ("a.txt", b"text"), + ]) + .await; + restore_prompts(&state, repo.path(), &tree).unwrap(); + let dir = repo.path().join("prompts"); + assert_eq!(std::fs::read(dir.join("a.md")).unwrap(), b"markdown"); + assert_eq!(std::fs::read(dir.join("a.tmp")).unwrap(), b"tmpfile"); + assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"text"); + let leftovers: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|n| n.contains("agentic-tmp")) + .collect(); + assert!( + leftovers.is_empty(), + "temp files left behind: {leftovers:?}" + ); + } + + // A symlink planted at the old temp name (`a.tmp` for `a.md`) must not + // be followed: the outside file stays intact and `a.md` is written. + #[cfg(unix)] + #[test] + fn write_blob_safely_does_not_follow_symlink_at_legacy_temp_name() { + let dir = tempfile::tempdir().unwrap(); + let outside = outside_dir(); + let victim = outside.path().join("keep.txt"); + std::os::unix::fs::symlink(&victim, dir.path().join("a.tmp")).unwrap(); + + write_blob_safely(&dir.path().join("a.md"), b"restored").unwrap(); + + assert_eq!(std::fs::read(dir.path().join("a.md")).unwrap(), b"restored"); + assert_outside_untouched(outside.path()); + } + + // O_EXCL: the temp writer refuses a pre-existing symlink instead of + // writing through it. + #[cfg(unix)] + #[test] + fn write_new_file_does_not_follow_planted_symlink() { + let dir = tempfile::tempdir().unwrap(); + let outside = outside_dir(); + let tmp = dir.path().join("planted"); + std::os::unix::fs::symlink(outside.path().join("keep.txt"), &tmp).unwrap(); + + let err = write_new_file(&tmp, b"evil").unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); + assert_outside_untouched(outside.path()); + } } From 1d657e315bac7417a47551faa38ccef0c27d143d Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:23:39 +0200 Subject: [PATCH 2/7] Run prompt preflight before rollback side effects and harden temp names A symlinked prompts directory or an invalid tree entry name used to be rejected only after reverse migrations and memory restore had committed, leaving a torn rollback. Rollback now validates the target prompts tree and checks for symlinked directories first, including on dry runs, and keeps the write-time checks. The temp file now has a short name independent of the prompt name. It is created exclusively, retried on a name clash up to 16 times, and removed only after the exclusive open succeeded, so a pre-existing file is never deleted. The reserved temp-name restriction on tree entries is dropped so rollback to existing commits keeps working. --- crates/agenticd/src/rollback/mod.rs | 9 +- crates/agenticd/src/rollback/writeback.rs | 150 ++++++++++++++------ crates/agenticd/tests/rollback_in_memory.rs | 110 ++++++++++++++ 3 files changed, 223 insertions(+), 46 deletions(-) diff --git a/crates/agenticd/src/rollback/mod.rs b/crates/agenticd/src/rollback/mod.rs index b4a333c7..0075972e 100644 --- a/crates/agenticd/src/rollback/mod.rs +++ b/crates/agenticd/src/rollback/mod.rs @@ -50,7 +50,7 @@ use crate::server::DaemonState; use agentic_proto::RollbackOutput; use loaders::{load_commit, load_manifest}; -use writeback::{read_model_text, read_text_blobs, restore_prompts}; +use writeback::{preflight_prompts, read_model_text, read_text_blobs, restore_prompts}; pub struct RollbackArgs { pub target: String, @@ -256,6 +256,13 @@ pub async fn execute( let target = load_commit(&state, &target_hash)?; validate_target_shape(&target, &target_hash)?; + // Reject an unwritable prompts tree (bad entry name, symlinked prompts + // directory) before any migration or memory restore, and on dry runs, + // so a refusal can't leave a half-applied rollback. + if let Some(prompts_hash) = target.prompts { + preflight_prompts(&state, &args.repo, &prompts_hash)?; + } + let mut plan: Vec = Vec::new(); let branch = match state.refs.read_head()? { diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index 76ee998d..272105b2 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -26,6 +26,26 @@ use anyhow::{anyhow, Context}; use super::loaders::{load_blob, load_tree}; use crate::server::DaemonState; +/// Check, without touching the filesystem, that [`restore_prompts`] would +/// accept this tree: every entry name is valid and neither `/prompts` +/// nor any existing directory above a target is a symlink. Rollback runs it +/// before migrations or memory restore so a bad tree can't tear a rollback. +pub(super) fn preflight_prompts( + state: &DaemonState, + repo: &Path, + prompts_hash: &Hash, +) -> anyhow::Result<()> { + let dir = repo.join("prompts"); + reject_symlinked_dirs(repo, &dir)?; + for name in load_tree(state, prompts_hash)?.entries.keys() { + validate_tree_entry_name(name)?; + if let Some(parent) = dir.join(name).parent() { + reject_symlinked_dirs(repo, parent)?; + } + } + Ok(()) +} + /// Write target prompts back to `/prompts/`. Files present on disk /// but not in the target tree are removed so the working set matches. /// @@ -45,9 +65,11 @@ use crate::server::DaemonState; /// /// Ancestor directories get the same treatment: `/prompts` and every /// existing directory between it and a write target must not be a symlink -/// ([`reject_symlinked_dirs`]), checked before and after `create_dir_all`, -/// so a planted directory link can't redirect writes or the orphan sweep -/// outside the prompts root. +/// ([`reject_symlinked_dirs`]), checked before and after `create_dir_all`. +/// This covers links that exist before the call. A concurrent swap during +/// the call is out of scope: the daemon's state directory must not be +/// writable by other uids (see the isolate-sidecar-state change), so no +/// other uid can plant links under the prompts directory. pub(super) fn restore_prompts( state: &DaemonState, repo: &Path, @@ -102,20 +124,37 @@ fn reject_symlinked_dirs(base: &Path, target: &Path) -> anyhow::Result<()> { Ok(()) } -/// Marker in temp file names. Tree entry names containing it are rejected -/// by [`validate_tree_entry_name`], so a temp name never equals an entry. -const TMP_MARKER: &str = ".agentic-tmp-"; static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); - -/// Create `tmp` with `O_EXCL` semantics (`create_new`): fails if anything, -/// including a planted symlink, already exists there, and never follows one. -fn write_new_file(tmp: &Path, bytes: &[u8]) -> std::io::Result<()> { - use std::io::Write; - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(tmp)?; - f.write_all(bytes) +const TMP_ATTEMPTS: usize = 16; + +/// Exclusively create a temp file next to `path`, named independently of +/// the prompt name (`.agentic-tmp--`, `n` from `next`). `create_new` +/// (`O_EXCL`) fails on anything already there, including a planted symlink, +/// and never follows one; on `AlreadyExists` we try the next `n`, up to +/// [`TMP_ATTEMPTS`] times. The returned path is ours alone, so callers may +/// remove it on failure. +fn create_temp( + path: &Path, + mut next: impl FnMut() -> u64, +) -> anyhow::Result<(PathBuf, std::fs::File)> { + for _ in 0..TMP_ATTEMPTS { + let tmp = path.with_file_name(format!(".agentic-tmp-{}-{}", std::process::id(), next())); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp) + { + Ok(f) => return Ok((tmp, f)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => { + return Err(e).with_context(|| format!("creating temp file {}", tmp.display())); + } + } + } + Err(anyhow!( + "no free temp file name next to {} after {TMP_ATTEMPTS} attempts", + path.display() + )) } /// Write `bytes` to `path` safely: @@ -136,6 +175,10 @@ fn write_new_file(tmp: &Path, bytes: &[u8]) -> std::io::Result<()> { /// Mirrors `agentic-core::store::FsObjectStore::write_at`'s /// temp-then-rename pattern. (Copilot review on PR #51, second pass.) fn write_blob_safely(path: &Path, bytes: &[u8]) -> anyhow::Result<()> { + write_blob_with(path, bytes, || TMP_COUNTER.fetch_add(1, Ordering::Relaxed)) +} + +fn write_blob_with(path: &Path, bytes: &[u8], next: impl FnMut() -> u64) -> anyhow::Result<()> { match std::fs::symlink_metadata(path) { Ok(meta) if meta.file_type().is_symlink() => { std::fs::remove_file(path) @@ -152,16 +195,9 @@ fn write_blob_safely(path: &Path, bytes: &[u8]) -> anyhow::Result<()> { }); } } - let file_name = path - .file_name() - .ok_or_else(|| anyhow!("prompt path {} has no file name", path.display()))? - .to_string_lossy(); - let tmp = path.with_file_name(format!( - ".{file_name}{TMP_MARKER}{}-{}", - std::process::id(), - TMP_COUNTER.fetch_add(1, Ordering::Relaxed) - )); - let result = write_new_file(&tmp, bytes) + let (tmp, mut file) = create_temp(path, next)?; + // The temp is ours from here on, so it is safe to remove on failure. + let result = std::io::Write::write_all(&mut file, bytes) .with_context(|| format!("writing temp file {}", tmp.display())) .and_then(|()| { std::fs::rename(&tmp, path) @@ -186,12 +222,6 @@ fn validate_tree_entry_name(name: &str) -> anyhow::Result<()> { } for component in Path::new(name).components() { match component { - Component::Normal(c) if c.to_string_lossy().contains(TMP_MARKER) => { - return Err(anyhow!( - "tree entry name {:?} uses the reserved temp-file marker {TMP_MARKER:?}", - name - )); - } Component::Normal(_) => {} _ => { return Err(anyhow!( @@ -457,12 +487,6 @@ mod tests { .is_file()); } - #[test] - fn validate_rejects_reserved_temp_marker() { - let err = validate_tree_entry_name("dir/.a.md.agentic-tmp-1-0").unwrap_err(); - assert!(err.to_string().contains("reserved temp-file marker")); - } - // Build a DaemonState over a fresh object store, commit `files` as a // prompts tree, and return (state, tree hash, repo dir guard). async fn state_with_prompts(files: &[(&str, &[u8])]) -> (DaemonState, Hash, tempfile::TempDir) { @@ -597,18 +621,54 @@ mod tests { assert_outside_untouched(outside.path()); } - // O_EXCL: the temp writer refuses a pre-existing symlink instead of - // writing through it. + // O_EXCL + retry: files or symlinks already sitting at the first + // candidate temp names are left untouched and the write still succeeds + // on the next free name. A fixed counter makes the candidates known. #[cfg(unix)] #[test] - fn write_new_file_does_not_follow_planted_symlink() { + fn write_blob_safely_skips_pre_planted_temp_names() { let dir = tempfile::tempdir().unwrap(); let outside = outside_dir(); - let tmp = dir.path().join("planted"); - std::os::unix::fs::symlink(outside.path().join("keep.txt"), &tmp).unwrap(); + let pid = std::process::id(); + let planted_file = dir.path().join(format!(".agentic-tmp-{pid}-0")); + std::fs::write(&planted_file, b"planted").unwrap(); + let planted_link = dir.path().join(format!(".agentic-tmp-{pid}-1")); + std::os::unix::fs::symlink(outside.path().join("keep.txt"), &planted_link).unwrap(); + + let mut n = 0; + write_blob_with(&dir.path().join("a.md"), b"restored", || { + n += 1; + n - 1 + }) + .unwrap(); - let err = write_new_file(&tmp, b"evil").unwrap_err(); - assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(dir.path().join("a.md")).unwrap(), b"restored"); + assert_eq!(std::fs::read(&planted_file).unwrap(), b"planted"); + assert!(std::fs::symlink_metadata(&planted_link) + .unwrap() + .file_type() + .is_symlink()); assert_outside_untouched(outside.path()); } + + #[test] + fn write_blob_safely_gives_up_after_bounded_attempts() { + let dir = tempfile::tempdir().unwrap(); + let pid = std::process::id(); + for i in 0..TMP_ATTEMPTS { + std::fs::write(dir.path().join(format!(".agentic-tmp-{pid}-{i}")), b"x").unwrap(); + } + let mut n = 0; + let err = write_blob_with(&dir.path().join("a.md"), b"y", || { + n += 1; + n - 1 + }) + .unwrap_err(); + assert!(err.to_string().contains("no free temp file name"), "{err}"); + assert!(!dir.path().join("a.md").exists()); + // Planted files must not have been removed by the error path. + for i in 0..TMP_ATTEMPTS { + assert!(dir.path().join(format!(".agentic-tmp-{pid}-{i}")).exists()); + } + } } diff --git a/crates/agenticd/tests/rollback_in_memory.rs b/crates/agenticd/tests/rollback_in_memory.rs index 81889c68..d06bc60a 100644 --- a/crates/agenticd/tests/rollback_in_memory.rs +++ b/crates/agenticd/tests/rollback_in_memory.rs @@ -664,3 +664,113 @@ fn commit_input_no_memory(message: &str) -> CommitInput { input.no_memory = true; input } + +// --------------------------------------------------------------------------- +// Prompt write-back preflight: an unwritable prompts tree must be rejected +// before any reverse migration or memory restore (and on dry runs). +// --------------------------------------------------------------------------- + +/// Commit a target whose prompts tree contains `prompt_name`, then dirty the +/// schema and memory, so a rollback to the target would have real work to +/// undo. Returns the target ref. +async fn commit_target_then_contaminate( + state: &Arc, + adapter: &InMemoryAdapter, + agentic_dir: &std::path::Path, + prompt_name: &str, +) -> String { + let mut input = commit_input_with_memory("target"); + input + .prompts + .insert(prompt_name.to_string(), b"payload".to_vec()); + let target = commit::execute(Arc::clone(state), input, Some(1000)) + .await + .expect("target commit") + .commit_hash; + + adapter.apply_migration("002_bump").await; + adapter + .insert_rows( + "messages", + vec![serde_json::json!({"id": 99, "body": "bad"})], + ) + .await; + let schema_dir = agentic_dir.join("schema"); + std::fs::create_dir_all(&schema_dir).unwrap(); + std::fs::write(schema_dir.join("002_bump.down.sql"), "-- no-op\n").unwrap(); + target +} + +async fn assert_rollback_refused_before_side_effects( + state: &Arc, + adapter: &InMemoryAdapter, + repo: &std::path::Path, + target: &str, + expect: &str, +) { + let tip = state.refs.read_branch("main").unwrap(); + let rows_before = adapter.rows_of("messages").await; + for dry_run in [true, false] { + let err = rollback::execute( + Arc::clone(state), + RollbackArgs { + target: target.to_string(), + dry_run, + accept_data_loss: false, + approval_token: None, + repo: repo.to_path_buf(), + }, + None, + ) + .await + .expect_err("unwritable prompts tree must be refused"); + assert!( + format!("{err:#}").contains(expect), + "dry_run={dry_run}: {err:#}" + ); + assert_eq!( + adapter.current_schema_version().await.unwrap(), + "002_bump", + "schema must not be reversed (dry_run={dry_run})" + ); + assert_eq!( + adapter.rows_of("messages").await, + rows_before, + "memory must not be restored (dry_run={dry_run})" + ); + assert_eq!(state.refs.read_branch("main").unwrap(), tip); + } +} + +#[cfg(unix)] +#[tokio::test] +async fn rollback_refuses_symlinked_prompts_parent_before_side_effects() { + let (state, adapter, _baseline, dir) = setup_gate_state(false).await; + let agentic_dir = dir.path().join(".agentic"); + let target = commit_target_then_contaminate(&state, &adapter, &agentic_dir, "sub/x").await; + + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("keep.txt"), b"outside").unwrap(); + std::fs::create_dir_all(dir.path().join("prompts")).unwrap(); + std::os::unix::fs::symlink(outside.path(), dir.path().join("prompts/sub")).unwrap(); + + assert_rollback_refused_before_side_effects(&state, &adapter, dir.path(), &target, "symlink") + .await; + assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 1); +} + +#[tokio::test] +async fn rollback_refuses_invalid_prompt_name_before_side_effects() { + let (state, adapter, _baseline, dir) = setup_gate_state(false).await; + let agentic_dir = dir.path().join(".agentic"); + let target = commit_target_then_contaminate(&state, &adapter, &agentic_dir, "../escape").await; + + assert_rollback_refused_before_side_effects( + &state, + &adapter, + dir.path(), + &target, + "unsafe path component", + ) + .await; +} From 0498e5c43dad9c9df9f6eb22f39212c29aceba21 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:26:36 +0200 Subject: [PATCH 3/7] Reject file and directory conflicts before rollback starts A tree with both a and a/b passed the preflight and failed halfway through the write, after the database had changed. A temp name equal to the destination would also expose a partial write, so skip it. --- crates/agenticd/src/rollback/writeback.rs | 51 ++++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index 272105b2..830ae4a4 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -37,7 +37,10 @@ pub(super) fn preflight_prompts( ) -> anyhow::Result<()> { let dir = repo.join("prompts"); reject_symlinked_dirs(repo, &dir)?; - for name in load_tree(state, prompts_hash)?.entries.keys() { + let tree = load_tree(state, prompts_hash)?; + let names: Vec<&String> = tree.entries.keys().collect(); + reject_file_dir_conflicts(&names)?; + for name in names { validate_tree_entry_name(name)?; if let Some(parent) = dir.join(name).parent() { reject_symlinked_dirs(repo, parent)?; @@ -46,6 +49,20 @@ pub(super) fn preflight_prompts( Ok(()) } +/// Reject a tree where one entry is both a file and a directory of another +/// (`a` and `a/b`): the write would fail halfway, after the database changed. +fn reject_file_dir_conflicts(names: &[&String]) -> anyhow::Result<()> { + for name in names { + let prefix = format!("{name}/"); + if let Some(child) = names.iter().find(|m| m.starts_with(&prefix)) { + return Err(anyhow!( + "prompt tree entry {name:?} is both a file and the directory of {child:?}" + )); + } + } + Ok(()) +} + /// Write target prompts back to `/prompts/`. Files present on disk /// but not in the target tree are removed so the working set matches. /// @@ -137,8 +154,15 @@ fn create_temp( path: &Path, mut next: impl FnMut() -> u64, ) -> anyhow::Result<(PathBuf, std::fs::File)> { + let dest = path.file_name().map(|n| n.to_string_lossy().to_lowercase()); for _ in 0..TMP_ATTEMPTS { - let tmp = path.with_file_name(format!(".agentic-tmp-{}-{}", std::process::id(), next())); + let name = format!(".agentic-tmp-{}-{}", std::process::id(), next()); + // A candidate equal to the destination (also case-insensitively, for + // case-folding filesystems) would expose a partial write at `path`. + if dest.as_deref() == Some(name.to_lowercase().as_str()) { + continue; + } + let tmp = path.with_file_name(name); match std::fs::OpenOptions::new() .write(true) .create_new(true) @@ -337,6 +361,29 @@ pub(super) fn read_model_text( mod tests { use super::*; + #[test] + fn file_dir_conflict_is_rejected() { + let (a, ab, c) = ("a".to_string(), "a/b".to_string(), "ab".to_string()); + assert!(reject_file_dir_conflicts(&[&a, &ab]).is_err()); + assert!(reject_file_dir_conflicts(&[&a, &c]).is_ok()); + assert!(reject_file_dir_conflicts(&[&ab, &c]).is_ok()); + } + + #[test] + fn temp_name_never_equals_the_destination() { + let dir = tempfile::tempdir().unwrap(); + let dest = dir + .path() + .join(format!(".AGENTIC-TMP-{}-0", std::process::id())); + let mut n = 0; + let (tmp, _f) = create_temp(&dest, || { + n += 1; + n - 1 + }) + .unwrap(); + assert!(tmp.file_name().unwrap().to_string_lossy().ends_with("-1")); + } + #[test] fn validate_accepts_normal_relative_names() { assert!(validate_tree_entry_name("system.md").is_ok()); From 89264bf068868e6ac07d050da9e58e886213ae12 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:29:05 +0200 Subject: [PATCH 4/7] Compare prompt paths by component in the conflict check Raw string comparison let p//a and a case-folded name slip past p/a/b. --- crates/agenticd/src/rollback/writeback.rs | 24 +++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index 830ae4a4..cc49c6ce 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -51,12 +51,25 @@ pub(super) fn preflight_prompts( /// Reject a tree where one entry is both a file and a directory of another /// (`a` and `a/b`): the write would fail halfway, after the database changed. +/// Names are compared as path components, lowercased, so `a//b` and a +/// case-folding filesystem cannot hide the conflict. fn reject_file_dir_conflicts(names: &[&String]) -> anyhow::Result<()> { - for name in names { - let prefix = format!("{name}/"); - if let Some(child) = names.iter().find(|m| m.starts_with(&prefix)) { + let key = |n: &str| -> Vec { + Path::new(n) + .components() + .map(|c| c.as_os_str().to_string_lossy().to_lowercase()) + .collect() + }; + let keys: Vec> = names.iter().map(|n| key(n)).collect(); + for (i, file) in keys.iter().enumerate() { + if let Some(j) = keys + .iter() + .position(|dir| dir.len() > file.len() && dir.starts_with(file)) + { return Err(anyhow!( - "prompt tree entry {name:?} is both a file and the directory of {child:?}" + "prompt tree entry {:?} is both a file and the directory of {:?}", + names[i], + names[j] )); } } @@ -367,6 +380,9 @@ mod tests { assert!(reject_file_dir_conflicts(&[&a, &ab]).is_err()); assert!(reject_file_dir_conflicts(&[&a, &c]).is_ok()); assert!(reject_file_dir_conflicts(&[&ab, &c]).is_ok()); + let (p, pab, upper) = ("p//a".to_string(), "p/a/b".to_string(), "P/A".to_string()); + assert!(reject_file_dir_conflicts(&[&p, &pab]).is_err()); + assert!(reject_file_dir_conflicts(&[&upper, &pab]).is_err()); } #[test] From 3fa754f859f08f92bed3b3d0df1ea9d681d8c37d Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:40:02 +0200 Subject: [PATCH 5/7] Write prompt temp files under the state directory Temp files used for atomic prompt replacement lived next to the destination, so a committed tree that named every candidate temp file could make the write fail after the database had already changed. They are now created exclusively in the state directory's tmp folder, which no prompt entry can name, and renamed into place. A rename across filesystems fails with an error saying the state directory and prompts must share a filesystem. The write-back comment now describes the residual race for a same-uid worker sharing the volume and why it is accepted. --- crates/agenticd/src/rollback/writeback.rs | 218 +++++++++++++++------- 1 file changed, 148 insertions(+), 70 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index cc49c6ce..fbc0c63f 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -97,9 +97,10 @@ fn reject_file_dir_conflicts(names: &[&String]) -> anyhow::Result<()> { /// existing directory between it and a write target must not be a symlink /// ([`reject_symlinked_dirs`]), checked before and after `create_dir_all`. /// This covers links that exist before the call. A concurrent swap during -/// the call is out of scope: the daemon's state directory must not be -/// writable by other uids (see the isolate-sidecar-state change), so no -/// other uid can plant links under the prompts directory. +/// the call is a residual race for a same-uid worker sharing the volume. It +/// is accepted because the daemon's state directory must not be reachable by +/// the worker (see docs/integration/executor-sidecar.md and the state-dir +/// startup check); a full fix needs an openat-style walk. pub(super) fn restore_prompts( state: &DaemonState, repo: &Path, @@ -109,6 +110,7 @@ pub(super) fn restore_prompts( reject_symlinked_dirs(repo, &dir)?; std::fs::create_dir_all(&dir)?; reject_symlinked_dirs(repo, &dir)?; + let tmp_dir = ensure_tmp_dir(state.refs.agentic_dir())?; let tree = load_tree(state, prompts_hash)?; let mut wanted: BTreeSet = BTreeSet::new(); @@ -121,7 +123,7 @@ pub(super) fn restore_prompts( reject_symlinked_dirs(repo, parent)?; } let blob = load_blob(state, &r.hash)?; - write_blob_safely(&path, &blob.bytes)?; + write_blob_safely(&tmp_dir, &path, &blob.bytes)?; wanted.insert(path); } @@ -157,25 +159,32 @@ fn reject_symlinked_dirs(base: &Path, target: &Path) -> anyhow::Result<()> { static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); const TMP_ATTEMPTS: usize = 16; -/// Exclusively create a temp file next to `path`, named independently of -/// the prompt name (`.agentic-tmp--`, `n` from `next`). `create_new` -/// (`O_EXCL`) fails on anything already there, including a planted symlink, -/// and never follows one; on `AlreadyExists` we try the next `n`, up to -/// [`TMP_ATTEMPTS`] times. The returned path is ours alone, so callers may -/// remove it on failure. +/// `/tmp`, created (mode 0700 on unix) if missing. Temp files +/// live here, outside the prompts tree, so no prompt entry can occupy a +/// temp name. +fn ensure_tmp_dir(agentic_dir: &Path) -> anyhow::Result { + let dir = agentic_dir.join("tmp"); + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder + .create(&dir) + .with_context(|| format!("creating temp directory {}", dir.display()))?; + Ok(dir) +} + +/// Exclusively create a temp file in `tmp_dir` (`.agentic-tmp--`, +/// `n` from `next`). `create_new` (`O_EXCL`) fails on anything already +/// there, including a planted symlink, and never follows one; on +/// `AlreadyExists` we try the next `n`, up to [`TMP_ATTEMPTS`] times. The +/// returned path is ours alone, so callers may remove it on failure. fn create_temp( - path: &Path, + tmp_dir: &Path, mut next: impl FnMut() -> u64, ) -> anyhow::Result<(PathBuf, std::fs::File)> { - let dest = path.file_name().map(|n| n.to_string_lossy().to_lowercase()); for _ in 0..TMP_ATTEMPTS { - let name = format!(".agentic-tmp-{}-{}", std::process::id(), next()); - // A candidate equal to the destination (also case-insensitively, for - // case-folding filesystems) would expose a partial write at `path`. - if dest.as_deref() == Some(name.to_lowercase().as_str()) { - continue; - } - let tmp = path.with_file_name(name); + let tmp = tmp_dir.join(format!(".agentic-tmp-{}-{}", std::process::id(), next())); match std::fs::OpenOptions::new() .write(true) .create_new(true) @@ -189,8 +198,8 @@ fn create_temp( } } Err(anyhow!( - "no free temp file name next to {} after {TMP_ATTEMPTS} attempts", - path.display() + "no free temp file name in {} after {TMP_ATTEMPTS} attempts", + tmp_dir.display() )) } @@ -202,8 +211,9 @@ fn create_temp( /// of the destination, since the attack we're defending against /// is a redirected write. Only `NotFound` is benign (the file /// doesn't exist yet, which is the common case). -/// 2. Write the new bytes to a uniquely named sibling temp file (created -/// exclusively, so a pre-planted symlink is never followed), then atomically +/// 2. Write the new bytes to a uniquely named temp file in `tmp_dir` +/// (created exclusively, so a pre-planted symlink is never followed; +/// `tmp_dir` must be on the same filesystem as `path`), then atomically /// `rename(2)` it over `path`. This closes the TOCTOU window /// between the symlink unlink and the regular file write: even if /// an attacker re-plants a symlink at `path` between steps, the @@ -211,11 +221,18 @@ fn create_temp( /// /// Mirrors `agentic-core::store::FsObjectStore::write_at`'s /// temp-then-rename pattern. (Copilot review on PR #51, second pass.) -fn write_blob_safely(path: &Path, bytes: &[u8]) -> anyhow::Result<()> { - write_blob_with(path, bytes, || TMP_COUNTER.fetch_add(1, Ordering::Relaxed)) +fn write_blob_safely(tmp_dir: &Path, path: &Path, bytes: &[u8]) -> anyhow::Result<()> { + write_blob_with(tmp_dir, path, bytes, || { + TMP_COUNTER.fetch_add(1, Ordering::Relaxed) + }) } -fn write_blob_with(path: &Path, bytes: &[u8], next: impl FnMut() -> u64) -> anyhow::Result<()> { +fn write_blob_with( + tmp_dir: &Path, + path: &Path, + bytes: &[u8], + next: impl FnMut() -> u64, +) -> anyhow::Result<()> { match std::fs::symlink_metadata(path) { Ok(meta) if meta.file_type().is_symlink() => { std::fs::remove_file(path) @@ -232,13 +249,27 @@ fn write_blob_with(path: &Path, bytes: &[u8], next: impl FnMut() -> u64) -> anyh }); } } - let (tmp, mut file) = create_temp(path, next)?; + let (tmp, mut file) = create_temp(tmp_dir, next)?; // The temp is ours from here on, so it is safe to remove on failure. let result = std::io::Write::write_all(&mut file, bytes) .with_context(|| format!("writing temp file {}", tmp.display())) .and_then(|()| { - std::fs::rename(&tmp, path) - .with_context(|| format!("renaming {} → {}", tmp.display(), path.display())) + std::fs::rename(&tmp, path).map_err(|e| { + if e.kind() == std::io::ErrorKind::CrossesDevices { + anyhow!( + "cannot rename {} into {}: `.agentic` and `prompts` must be on \ + the same filesystem", + tmp.display(), + path.display() + ) + } else { + anyhow::Error::new(e).context(format!( + "renaming {} → {}", + tmp.display(), + path.display() + )) + } + }) }); if result.is_err() { let _ = std::fs::remove_file(&tmp); @@ -385,19 +416,10 @@ mod tests { assert!(reject_file_dir_conflicts(&[&upper, &pab]).is_err()); } - #[test] - fn temp_name_never_equals_the_destination() { - let dir = tempfile::tempdir().unwrap(); - let dest = dir - .path() - .join(format!(".AGENTIC-TMP-{}-0", std::process::id())); - let mut n = 0; - let (tmp, _f) = create_temp(&dest, || { - n += 1; - n - 1 - }) - .unwrap(); - assert!(tmp.file_name().unwrap().to_string_lossy().ends_with("-1")); + // Test helper: write through a fresh temp dir outside `path`'s directory. + fn wb(path: &Path, bytes: &[u8]) -> anyhow::Result<()> { + let tmp = tempfile::tempdir().unwrap(); + write_blob_safely(tmp.path(), path, bytes) } #[test] @@ -495,7 +517,7 @@ mod tests { ); // Write the new blob. - write_blob_safely(&dest, b"restored prompt content").unwrap(); + wb(&dest, b"restored prompt content").unwrap(); // The symlink is gone; dest is now a regular file with the new // bytes. @@ -532,7 +554,7 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let dest = tmp.path().join("new.md"); assert!(!dest.exists()); - write_blob_safely(&dest, b"hello").unwrap(); + wb(&dest, b"hello").unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), b"hello"); } @@ -541,7 +563,7 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let dest = tmp.path().join("existing.md"); std::fs::write(&dest, b"old content").unwrap(); - write_blob_safely(&dest, b"new content").unwrap(); + wb(&dest, b"new content").unwrap(); assert_eq!(std::fs::read(&dest).unwrap(), b"new content"); // Regular file (not turned into anything weird). assert!(std::fs::symlink_metadata(&dest) @@ -657,15 +679,18 @@ mod tests { assert_eq!(std::fs::read(dir.join("a.md")).unwrap(), b"markdown"); assert_eq!(std::fs::read(dir.join("a.tmp")).unwrap(), b"tmpfile"); assert_eq!(std::fs::read(dir.join("a.txt")).unwrap(), b"text"); - let leftovers: Vec<_> = std::fs::read_dir(&dir) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .filter(|n| n.contains("agentic-tmp")) - .collect(); - assert!( - leftovers.is_empty(), - "temp files left behind: {leftovers:?}" - ); + // Temp files live outside prompts/ and are renamed away. + for d in [dir.clone(), repo.path().join(".agentic/tmp")] { + let leftovers: Vec<_> = std::fs::read_dir(&d) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|n| n.contains("agentic-tmp")) + .collect(); + assert!( + leftovers.is_empty(), + "temp files left in {d:?}: {leftovers:?}" + ); + } } // A symlink planted at the old temp name (`a.tmp` for `a.md`) must not @@ -678,34 +703,44 @@ mod tests { let victim = outside.path().join("keep.txt"); std::os::unix::fs::symlink(&victim, dir.path().join("a.tmp")).unwrap(); - write_blob_safely(&dir.path().join("a.md"), b"restored").unwrap(); + wb(&dir.path().join("a.md"), b"restored").unwrap(); assert_eq!(std::fs::read(dir.path().join("a.md")).unwrap(), b"restored"); assert_outside_untouched(outside.path()); } // O_EXCL + retry: files or symlinks already sitting at the first - // candidate temp names are left untouched and the write still succeeds - // on the next free name. A fixed counter makes the candidates known. + // candidate temp names in the tmp dir are left untouched and the write + // still succeeds on the next free name. A fixed counter makes the + // candidates known. #[cfg(unix)] #[test] fn write_blob_safely_skips_pre_planted_temp_names() { - let dir = tempfile::tempdir().unwrap(); + let prompts = tempfile::tempdir().unwrap(); + let tmp_dir = tempfile::tempdir().unwrap(); let outside = outside_dir(); let pid = std::process::id(); - let planted_file = dir.path().join(format!(".agentic-tmp-{pid}-0")); + let planted_file = tmp_dir.path().join(format!(".agentic-tmp-{pid}-0")); std::fs::write(&planted_file, b"planted").unwrap(); - let planted_link = dir.path().join(format!(".agentic-tmp-{pid}-1")); + let planted_link = tmp_dir.path().join(format!(".agentic-tmp-{pid}-1")); std::os::unix::fs::symlink(outside.path().join("keep.txt"), &planted_link).unwrap(); let mut n = 0; - write_blob_with(&dir.path().join("a.md"), b"restored", || { - n += 1; - n - 1 - }) + write_blob_with( + tmp_dir.path(), + &prompts.path().join("a.md"), + b"restored", + || { + n += 1; + n - 1 + }, + ) .unwrap(); - assert_eq!(std::fs::read(dir.path().join("a.md")).unwrap(), b"restored"); + assert_eq!( + std::fs::read(prompts.path().join("a.md")).unwrap(), + b"restored" + ); assert_eq!(std::fs::read(&planted_file).unwrap(), b"planted"); assert!(std::fs::symlink_metadata(&planted_link) .unwrap() @@ -716,22 +751,65 @@ mod tests { #[test] fn write_blob_safely_gives_up_after_bounded_attempts() { - let dir = tempfile::tempdir().unwrap(); + let prompts = tempfile::tempdir().unwrap(); + let tmp_dir = tempfile::tempdir().unwrap(); let pid = std::process::id(); for i in 0..TMP_ATTEMPTS { - std::fs::write(dir.path().join(format!(".agentic-tmp-{pid}-{i}")), b"x").unwrap(); + std::fs::write(tmp_dir.path().join(format!(".agentic-tmp-{pid}-{i}")), b"x").unwrap(); } let mut n = 0; - let err = write_blob_with(&dir.path().join("a.md"), b"y", || { + let err = write_blob_with(tmp_dir.path(), &prompts.path().join("a.md"), b"y", || { n += 1; n - 1 }) .unwrap_err(); assert!(err.to_string().contains("no free temp file name"), "{err}"); - assert!(!dir.path().join("a.md").exists()); + assert!(!prompts.path().join("a.md").exists()); // Planted files must not have been removed by the error path. for i in 0..TMP_ATTEMPTS { - assert!(dir.path().join(format!(".agentic-tmp-{pid}-{i}")).exists()); + assert!(tmp_dir + .path() + .join(format!(".agentic-tmp-{pid}-{i}")) + .exists()); + } + } + + // A committed tree can name entries `.agentic-tmp--`; since temp + // files live outside prompts/, restore still succeeds and keeps them. + #[tokio::test] + async fn restore_prompts_succeeds_when_tree_names_temp_candidates() { + let pid = std::process::id(); + let names: Vec = (0..300) + .map(|i| format!(".agentic-tmp-{pid}-{i}")) + .collect(); + let files: Vec<(&str, &[u8])> = names + .iter() + .map(|n| (n.as_str(), b"entry".as_slice())) + .chain(std::iter::once(("a.md", b"markdown".as_slice()))) + .collect(); + let (state, tree, repo) = state_with_prompts(&files).await; + // Twice: the second run finds the entries already on disk, which is + // what used to exhaust the in-tree temp candidates. + restore_prompts(&state, repo.path(), &tree).unwrap(); + restore_prompts(&state, repo.path(), &tree).unwrap(); + let dir = repo.path().join("prompts"); + for n in &names { + assert_eq!(std::fs::read(dir.join(n)).unwrap(), b"entry"); } + assert_eq!(std::fs::read(dir.join("a.md")).unwrap(), b"markdown"); + } + + #[cfg(unix)] + #[test] + fn ensure_tmp_dir_is_private() { + use std::os::unix::fs::PermissionsExt; + let agentic = tempfile::tempdir().unwrap(); + let dir = ensure_tmp_dir(agentic.path()).unwrap(); + assert_eq!(dir, agentic.path().join("tmp")); + assert_eq!( + std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, + 0o700 + ); + ensure_tmp_dir(agentic.path()).unwrap(); // idempotent } } From d0e90977e79d348b645c07407e5682492005f551 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:45:03 +0200 Subject: [PATCH 6/7] Check the temp directory and filesystem before rollback starts A symlinked or loosened .agentic/tmp is refused or tightened, and a prompts path on another filesystem than the temp directory now fails in preflight instead of at rename, after the database changed. --- crates/agenticd/src/rollback/writeback.rs | 106 +++++++++++++++++++--- 1 file changed, 95 insertions(+), 11 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index fbc0c63f..71f7fc07 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -37,6 +37,8 @@ pub(super) fn preflight_prompts( ) -> anyhow::Result<()> { let dir = repo.join("prompts"); reject_symlinked_dirs(repo, &dir)?; + let tmp_dir = ensure_tmp_dir(state.refs.agentic_dir())?; + reject_other_device(&tmp_dir, &dir)?; let tree = load_tree(state, prompts_hash)?; let names: Vec<&String> = tree.entries.keys().collect(); reject_file_dir_conflicts(&names)?; @@ -44,6 +46,7 @@ pub(super) fn preflight_prompts( validate_tree_entry_name(name)?; if let Some(parent) = dir.join(name).parent() { reject_symlinked_dirs(repo, parent)?; + reject_other_device(&tmp_dir, parent)?; } } Ok(()) @@ -97,10 +100,10 @@ fn reject_file_dir_conflicts(names: &[&String]) -> anyhow::Result<()> { /// existing directory between it and a write target must not be a symlink /// ([`reject_symlinked_dirs`]), checked before and after `create_dir_all`. /// This covers links that exist before the call. A concurrent swap during -/// the call is a residual race for a same-uid worker sharing the volume. It -/// is accepted because the daemon's state directory must not be reachable by -/// the worker (see docs/integration/executor-sidecar.md and the state-dir -/// startup check); a full fix needs an openat-style walk. +/// the call is a residual race for a worker that can write the repo. It is +/// accepted because the deployment must not let the worker write the +/// daemon's repo or state directory (docs/integration/executor-sidecar.md); +/// a full fix needs an openat-style walk. pub(super) fn restore_prompts( state: &DaemonState, repo: &Path, @@ -164,16 +167,69 @@ const TMP_ATTEMPTS: usize = 16; /// temp name. fn ensure_tmp_dir(agentic_dir: &Path) -> anyhow::Result { let dir = agentic_dir.join("tmp"); - let mut builder = std::fs::DirBuilder::new(); - builder.recursive(true); - #[cfg(unix)] - std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); - builder - .create(&dir) - .with_context(|| format!("creating temp directory {}", dir.display()))?; + match std::fs::symlink_metadata(&dir) { + // An existing entry must be a real directory (never a symlink), and is + // tightened to 0700 in case an older run or another tool loosened it. + Ok(meta) if meta.file_type().is_dir() => { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)) + .with_context(|| format!("restricting temp directory {}", dir.display()))?; + } + } + Ok(_) => { + return Err(anyhow!( + "temp directory {} exists but is not a directory (symlink or file); refusing to use it", + dir.display() + )); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder + .create(&dir) + .with_context(|| format!("creating temp directory {}", dir.display()))?; + } + Err(e) => { + return Err(e).with_context(|| format!("inspecting temp directory {}", dir.display())); + } + } Ok(dir) } +/// Refuse a target whose nearest existing ancestor is on a different +/// filesystem than the temp directory: the final `rename` would fail with +/// EXDEV after the database changed. +#[cfg(unix)] +fn reject_other_device(tmp_dir: &Path, target: &Path) -> anyhow::Result<()> { + use std::os::unix::fs::MetadataExt; + let tmp_dev = std::fs::metadata(tmp_dir) + .with_context(|| format!("inspecting {}", tmp_dir.display()))? + .dev(); + let Some(existing) = target.ancestors().find(|p| p.exists()) else { + return Ok(()); + }; + let dev = std::fs::metadata(existing) + .with_context(|| format!("inspecting {}", existing.display()))? + .dev(); + if dev != tmp_dev { + return Err(anyhow!( + "{} is on a different filesystem than {}; .agentic and prompts must share one filesystem", + existing.display(), + tmp_dir.display() + )); + } + Ok(()) +} + +#[cfg(not(unix))] +fn reject_other_device(_tmp_dir: &Path, _target: &Path) -> anyhow::Result<()> { + Ok(()) +} + /// Exclusively create a temp file in `tmp_dir` (`.agentic-tmp--`, /// `n` from `next`). `create_new` (`O_EXCL`) fails on anything already /// there, including a planted symlink, and never follows one; on @@ -812,4 +868,32 @@ mod tests { ); ensure_tmp_dir(agentic.path()).unwrap(); // idempotent } + + #[cfg(unix)] + #[test] + fn ensure_tmp_dir_refuses_symlink_and_tightens_existing() { + use std::os::unix::fs::PermissionsExt; + let outside = tempfile::tempdir().unwrap(); + let linked = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(outside.path(), linked.path().join("tmp")).unwrap(); + assert!(ensure_tmp_dir(linked.path()).is_err()); + + let loose = tempfile::tempdir().unwrap(); + let tmp = loose.path().join("tmp"); + std::fs::create_dir(&tmp).unwrap(); + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o777)).unwrap(); + ensure_tmp_dir(loose.path()).unwrap(); + assert_eq!( + std::fs::metadata(&tmp).unwrap().permissions().mode() & 0o777, + 0o700 + ); + } + + #[cfg(unix)] + #[test] + fn same_device_target_passes_the_device_check() { + let agentic = tempfile::tempdir().unwrap(); + let tmp = ensure_tmp_dir(agentic.path()).unwrap(); + reject_other_device(&tmp, &agentic.path().join("prompts/a/b")).unwrap(); + } } From 1b10e37e8813308f19fd8c97ebb1d4ecbcbf8557 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:50:12 +0200 Subject: [PATCH 7/7] Find prompt file and directory conflicts in one sorted pass The pairwise scan was quadratic in the number of tree entries, which a socket client controls. Sorted component paths place every extension of a key right after it, so comparing neighbours is enough. --- crates/agenticd/src/rollback/writeback.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/crates/agenticd/src/rollback/writeback.rs b/crates/agenticd/src/rollback/writeback.rs index 71f7fc07..9dad9ec2 100644 --- a/crates/agenticd/src/rollback/writeback.rs +++ b/crates/agenticd/src/rollback/writeback.rs @@ -63,16 +63,15 @@ fn reject_file_dir_conflicts(names: &[&String]) -> anyhow::Result<()> { .map(|c| c.as_os_str().to_string_lossy().to_lowercase()) .collect() }; - let keys: Vec> = names.iter().map(|n| key(n)).collect(); - for (i, file) in keys.iter().enumerate() { - if let Some(j) = keys - .iter() - .position(|dir| dir.len() > file.len() && dir.starts_with(file)) - { + // Sorted component vectors put every extension of a key directly after + // it, so comparing neighbours finds any conflict in O(n log n). + let mut keys: Vec<(Vec, &String)> = names.iter().map(|n| (key(n), *n)).collect(); + keys.sort(); + for pair in keys.windows(2) { + let ((file, file_name), (dir, dir_name)) = (&pair[0], &pair[1]); + if dir.len() > file.len() && dir.starts_with(file) { return Err(anyhow!( - "prompt tree entry {:?} is both a file and the directory of {:?}", - names[i], - names[j] + "prompt tree entry {file_name:?} is both a file and the directory of {dir_name:?}" )); } }