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 f525a7cf..9dad9ec2 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}; @@ -25,6 +26,58 @@ 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)?; + 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)?; + for name in names { + 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(()) +} + +/// 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<()> { + let key = |n: &str| -> Vec { + Path::new(n) + .components() + .map(|c| c.as_os_str().to_string_lossy().to_lowercase()) + .collect() + }; + // 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 {file_name:?} is both a file and the directory of {dir_name:?}" + )); + } + } + Ok(()) +} + /// Write target prompts back to `/prompts/`. Files present on disk /// but not in the target tree are removed so the working set matches. /// @@ -41,13 +94,25 @@ 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`. +/// This covers links that exist before the call. A concurrent swap during +/// 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, 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 tmp_dir = ensure_tmp_dir(state.refs.agentic_dir())?; let tree = load_tree(state, prompts_hash)?; let mut wanted: BTreeSet = BTreeSet::new(); @@ -55,10 +120,12 @@ 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)?; + write_blob_safely(&tmp_dir, &path, &blob.bytes)?; wanted.insert(path); } @@ -66,6 +133,131 @@ 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(()) +} + +static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); +const TMP_ATTEMPTS: usize = 16; + +/// `/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"); + 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 +/// `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( + tmp_dir: &Path, + mut next: impl FnMut() -> u64, +) -> anyhow::Result<(PathBuf, std::fs::File)> { + for _ in 0..TMP_ATTEMPTS { + let tmp = tmp_dir.join(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 in {} after {TMP_ATTEMPTS} attempts", + tmp_dir.display() + )) +} + /// Write `bytes` to `path` safely: /// /// 1. If `path` already exists as a symlink, unlink it. Any other @@ -74,7 +266,9 @@ 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 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 @@ -82,7 +276,18 @@ pub(super) fn restore_prompts( /// /// 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<()> { +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( + 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) @@ -99,11 +304,32 @@ 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 (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).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); + } + result } /// Reject tree entry names that would escape the prompts directory or @@ -140,7 +366,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(); @@ -224,6 +460,23 @@ 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()); + 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 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] fn validate_accepts_normal_relative_names() { assert!(validate_tree_entry_name("system.md").is_ok()); @@ -319,7 +572,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. @@ -356,7 +609,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"); } @@ -365,7 +618,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) @@ -373,4 +626,273 @@ mod tests { .file_type() .is_file()); } + + // 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"); + // 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 + // 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(); + + 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 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 prompts = tempfile::tempdir().unwrap(); + let tmp_dir = tempfile::tempdir().unwrap(); + let outside = outside_dir(); + let pid = std::process::id(); + let planted_file = tmp_dir.path().join(format!(".agentic-tmp-{pid}-0")); + std::fs::write(&planted_file, b"planted").unwrap(); + 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( + tmp_dir.path(), + &prompts.path().join("a.md"), + b"restored", + || { + n += 1; + n - 1 + }, + ) + .unwrap(); + + 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() + .file_type() + .is_symlink()); + assert_outside_untouched(outside.path()); + } + + #[test] + fn write_blob_safely_gives_up_after_bounded_attempts() { + 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(tmp_dir.path().join(format!(".agentic-tmp-{pid}-{i}")), b"x").unwrap(); + } + let mut n = 0; + 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!(!prompts.path().join("a.md").exists()); + // Planted files must not have been removed by the error path. + for i in 0..TMP_ATTEMPTS { + 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 + } + + #[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(); + } } 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; +}