use super::*;
use std::os::unix::fs::symlink;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
fn project() -> tempfile::TempDir {
let tmp = tempfile::tempdir().expect("tempdir");
std::fs::create_dir_all(native_config_dir(tmp.path())).expect("mkdir .trusty-code");
tmp
}
fn swap_for_symlink(dir: &Path, victim: &Path) {
std::fs::remove_dir_all(dir).expect("remove the real directory");
symlink(victim, dir).expect("symlink the victim in its place");
}
fn descendants(root: &Path) -> Vec<PathBuf> {
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
walk(&path, out);
} else {
out.push(path);
}
}
}
let mut out = Vec::new();
walk(root, &mut out);
out.sort();
out
}
#[test]
fn pinned_write_lands_at_the_validated_path() {
let tmp = project();
let dir = NativeWriteDir::open(tmp.path(), Path::new("agents")).expect("pin the agents dir");
dir.atomic_write("pm.md", b"hello").expect("write");
assert_eq!(dir.path(), native_config_dir(tmp.path()).join("agents"));
assert_eq!(
std::fs::read_to_string(dir.path().join("pm.md")).expect("read back"),
"hello"
);
assert_eq!(
dir.read("pm.md").expect("read").as_deref(),
Some(&b"hello"[..])
);
dir.atomic_write("pm.md", b"second").expect("rewrite");
assert_eq!(
dir.read("pm.md").expect("read").as_deref(),
Some(&b"second"[..])
);
}
#[test]
fn component_swapped_after_open_never_reaches_victim() {
let tmp = project();
let victim = tempfile::tempdir().expect("victim tempdir");
let dir =
NativeWriteDir::open(tmp.path(), Path::new("skill-refs")).expect("pin the skill-refs dir");
swap_for_symlink(dir.path(), victim.path());
let err = dir
.atomic_write("SKILL.md", b"secret")
.expect_err("a swapped component must be reported");
assert!(
matches!(err, WriteTargetError::Unpinned { .. }),
"expected Unpinned, got {err:?}"
);
let leaked: Vec<_> = std::fs::read_dir(victim.path())
.expect("read the victim")
.flatten()
.map(|e| e.file_name())
.collect();
assert!(
leaked.is_empty(),
"the victim directory must receive nothing, found {leaked:?}"
);
}
#[test]
fn native_root_swapped_between_check_and_pin_never_reaches_victim() {
let tmp = project();
let victim = tempfile::tempdir().expect("victim tempdir");
let link_at = native_config_dir(tmp.path());
let parked = tmp.path().join(".trusty-code-parked");
let stop = Arc::new(AtomicBool::new(false));
let swapper = {
let stop = Arc::clone(&stop);
let victim_path = victim.path().to_path_buf();
let (link_at, parked) = (link_at.clone(), parked.clone());
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let _ = std::fs::rename(&link_at, &parked);
let _ = symlink(&victim_path, &link_at);
std::thread::sleep(std::time::Duration::from_micros(50));
if std::fs::remove_file(&link_at).is_err() {
let _ = std::fs::remove_dir_all(&link_at);
}
let _ = std::fs::rename(&parked, &link_at);
}
let _ = std::fs::remove_file(&link_at);
let _ = std::fs::rename(&parked, &link_at);
})
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let (mut attempts, mut written) = (0u32, 0u32);
while std::time::Instant::now() < deadline && (attempts < 3000 || written == 0) {
attempts += 1;
if let Ok(dir) = NativeWriteDir::open(tmp.path(), Path::new("agents"))
&& dir
.atomic_write(&format!("pm-{attempts}.md"), b"AGENT BODY")
.is_ok()
{
written += 1;
}
}
stop.store(true, Ordering::Relaxed);
swapper.join().expect("swapper thread");
assert!(
written > 0,
"the harness proves nothing if every attempt was refused ({attempts} attempts)"
);
let leaked = descendants(victim.path());
assert!(
leaked.is_empty(),
"the victim tree must receive nothing across {attempts} attempts, found {leaked:?}"
);
}
#[test]
fn a_name_with_a_path_separator_is_refused() {
let tmp = project();
let victim = tempfile::tempdir().expect("victim tempdir");
let dir = NativeWriteDir::open(tmp.path(), Path::new("agents")).expect("pin");
symlink(victim.path(), dir.path().join("link")).expect("symlink inside the pinned dir");
for name in [
"link/escaped.md",
"../escaped.md",
"sub/escaped.md",
"",
".",
"..",
] {
assert!(
matches!(
dir.atomic_write(name, b"secret"),
Err(WriteTargetError::Unpinnable { .. })
),
"atomic_write must refuse `{name}`"
);
assert!(
matches!(
dir.create_new(name, b"secret"),
Err(WriteTargetError::Unpinnable { .. })
),
"create_new must refuse `{name}`"
);
assert!(
matches!(dir.read(name), Err(WriteTargetError::Unpinnable { .. })),
"read must refuse `{name}`"
);
assert!(
matches!(
dir.lock_exclusive(name),
Err(WriteTargetError::Unpinnable { .. })
),
"lock_exclusive must refuse `{name}`"
);
}
let leaked = descendants(victim.path());
assert!(
leaked.is_empty(),
"nothing may reach a symlink's target, found {leaked:?}"
);
}
#[test]
fn symlinked_component_is_refused_at_open() {
let tmp = project();
let inside = native_config_dir(tmp.path()).join("elsewhere");
std::fs::create_dir_all(&inside).expect("mkdir");
symlink(&inside, native_config_dir(tmp.path()).join("skill-refs")).expect("symlink");
let err = NativeWriteDir::open(tmp.path(), Path::new("skill-refs"))
.expect_err("a symlinked component must be refused");
assert!(
matches!(err, WriteTargetError::Unpinned { .. }),
"expected Unpinned, got {err:?}"
);
}
#[test]
fn symlinked_native_root_escape_is_refused_at_open() {
let tmp = tempfile::tempdir().expect("tempdir");
let outside = tempfile::tempdir().expect("outside tempdir");
symlink(outside.path(), tmp.path().join(TRUSTY_CODE_DIRNAME)).expect("symlink");
let err = NativeWriteDir::open(tmp.path(), Path::new("agents"))
.expect_err("an escaping config root must be refused");
assert!(
matches!(err, WriteTargetError::SymlinkEscape { .. }),
"expected SymlinkEscape, got {err:?}"
);
}
#[test]
fn child_dir_is_pinned_like_its_parent() {
let tmp = project();
let victim = tempfile::tempdir().expect("victim tempdir");
let refs = NativeWriteDir::open(tmp.path(), Path::new("skill-refs")).expect("pin");
let child = refs
.child(Path::new("git-workflow"))
.expect("pin the child");
child.atomic_write("SKILL.md", b"body").expect("write");
assert_eq!(
std::fs::read_to_string(child.path().join("SKILL.md")).expect("read back"),
"body"
);
swap_for_symlink(child.path(), victim.path());
let err = refs
.child(Path::new("git-workflow"))
.expect_err("a swapped child must be refused");
assert!(
matches!(err, WriteTargetError::Unpinned { .. }),
"expected Unpinned, got {err:?}"
);
}
#[test]
fn create_new_refuses_an_existing_file() {
let tmp = project();
let dir = NativeWriteDir::open(tmp.path(), Path::new("agents")).expect("pin");
dir.create_new("pm.md", b"first").expect("first write");
let err = dir
.create_new("pm.md", b"second")
.expect_err("an existing target must be refused");
assert!(
matches!(err, WriteTargetError::Unpinnable { .. }),
"expected Unpinnable, got {err:?}"
);
assert_eq!(
dir.read("pm.md").expect("read").as_deref(),
Some(&b"first"[..])
);
}
#[test]
fn ledger_lock_is_exclusive_across_handles() {
let tmp = project();
let root = tmp.path().to_path_buf();
let dir = NativeWriteDir::open(&root, Path::new("agents")).expect("pin");
let held = dir.lock_exclusive(".ledger.lock").expect("take the lock");
let (tx, rx) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
let other = NativeWriteDir::open(&root, Path::new("agents")).expect("pin");
let lock = other.lock_exclusive(".ledger.lock").expect("take the lock");
tx.send(()).expect("report acquisition");
drop(lock);
});
assert!(
rx.recv_timeout(std::time::Duration::from_millis(200))
.is_err(),
"a second handle must block while the lock is held"
);
drop(held);
rx.recv_timeout(std::time::Duration::from_secs(5))
.expect("the lock must be acquired once released");
worker.join().expect("worker thread");
}