synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
GitHub aien-dev/synapse#74 (code only)
Apply it
git checkout -b patch-b83f671244197247 e863c87b581ddd0d33183667d6d4842d2de1f4fe curl -fsSL https://interplane.io/drakestapleton/synapse/patches/b83f671244197247.patch | git am
Provenance
github-import 1
aien-dev/synapse
74
546d1354c13cb911dde5abcc9a0aa25c3bf3bd01
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":74,"url":"https://github.com/aien-dev/synapse/pull/74","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:17Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/synapse-coord/src/bin/synapse-coord.rs b/crates/synapse-coord/src/bin/synapse-coord.rs index 598546a..ff404ae 100644 --- a/crates/synapse-coord/src/bin/synapse-coord.rs +++ b/crates/synapse-coord/src/bin/synapse-coord.rs @@ -40,8 +40,9 @@ fn ttl(s: Option<&String>) -> Result<Option<i64>, String> { fn main() -> ExitCode { let mut args: Vec<String> = std::env::args().skip(1).collect(); if args.len() == 2 && args[0] == "canon" { - return match std::fs::read(&args[1]) + return match synapse_coord::read_record_file(std::path::Path::new(&args[1])) .ok() + .flatten() .and_then(|b| synapse_coord::json::parse(&b)) { Some(j) => { diff --git a/crates/synapse-coord/src/lib.rs b/crates/synapse-coord/src/lib.rs index ba9523b..0437ff5 100644 --- a/crates/synapse-coord/src/lib.rs +++ b/crates/synapse-coord/src/lib.rs @@ -18,7 +18,7 @@ pub mod time; pub use identity::{ resolve_coord_root, ResolvedRoot, RootSource, StoreId, STORE_ID_FILE, STORE_ID_FORMAT, }; -pub use record::{RecordRefusal, MAX_MARKER_BYTES, MAX_RECORD_BYTES}; +pub use record::{read_record_file, RecordRefusal, MAX_MARKER_BYTES, MAX_RECORD_BYTES}; use json::J; use std::fs::{self, File, OpenOptions}; @@ -662,6 +662,11 @@ impl CoordStore { path: lp.clone(), reason: RecordRefusal::Symlink, }, + // A directory planted as `.lock` is a refused store file, not an I/O error. + Some(libc::EISDIR) => CoordError::RefusedRecord { + path: lp.clone(), + reason: RecordRefusal::NotRegular("directory"), + }, _ => io_err(&lp)(e), })?; // The lock file is a store file too: a FIFO or device planted as `.lock` is refused. @@ -730,8 +735,15 @@ fn has_lock_by(root: &J, agent: &str) -> bool { } } +/// Best-effort directory flush. Opened like every other store file: never following a final +/// link, never blocking (a FIFO planted in place of a directory cannot stall the writer), +/// and only if it really is a directory. fn fsync_dir(dir: &Path) { - if let Ok(f) = File::open(dir) { + if let Ok(f) = OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) + .open(dir) + { let _ = f.sync_all(); } } @@ -742,7 +754,7 @@ fn fsync_dir(dir: &Path) { /// /// Refuses (typed [`CoordError::RefusedRecord`]) to replace anything but a regular file, and /// to write a record over [`MAX_RECORD_BYTES`], which readers would refuse. -fn durable_write(path: &Path, data: &[u8]) -> Result<(), CoordError> { +fn durable_write(root: &Path, path: &Path, data: &[u8]) -> Result<(), CoordError> { if data.len() as u64 > MAX_RECORD_BYTES { return Err(CoordError::RefusedRecord { path: path.to_path_buf(), @@ -751,6 +763,7 @@ fn durable_write(path: &Path, data: &[u8]) -> Result<(), CoordError> { }, }); } + record::check_real_parents(root, path)?; record::check_replaceable(path)?; let dd = path.parent().unwrap_or(Path::new(".")); fs::create_dir_all(dd).map_err(io_err(dd))?; @@ -806,6 +819,9 @@ impl Txn<'_> { if let Some(i) = self.recs.iter().position(|r| r.path == path) { return Ok(i); } + // Never read through a symlinked directory: listing does not follow one, so a record + // behind it would be invisible to prune yet loadable and writable here. + record::check_real_parents(&self.store.root, path)?; let (mut j, existed) = match record::read_bounded(path, MAX_RECORD_BYTES)? { Some(bytes) => match json::parse(&bytes) { Some(j) if j.is_obj() => (j, true), @@ -890,7 +906,7 @@ impl Txn<'_> { } let now = r.root.dump(); if now != r.before { - durable_write(&r.path, &now)?; + durable_write(&self.store.root, &r.path, &now)?; } } self.lock.take(); diff --git a/crates/synapse-coord/src/record.rs b/crates/synapse-coord/src/record.rs index 9f95b10..010be74 100644 --- a/crates/synapse-coord/src/record.rs +++ b/crates/synapse-coord/src/record.rs @@ -43,6 +43,9 @@ pub enum RecordRefusal { NotRegular(&'static str), /// The file is larger than `limit` bytes. TooLarge { limit: u64 }, + /// A directory component of a record path is not a directory (for example a regular + /// file planted where a subdirectory of `dirs/` is expected). + NotDirectory, } impl std::fmt::Display for RecordRefusal { @@ -51,6 +54,7 @@ impl std::fmt::Display for RecordRefusal { RecordRefusal::Symlink => write!(f, "is a symbolic link"), RecordRefusal::NotRegular(k) => write!(f, "is a {k}, not a regular file"), RecordRefusal::TooLarge { limit } => write!(f, "is larger than {limit} bytes"), + RecordRefusal::NotDirectory => write!(f, "is not a directory"), } } } @@ -162,3 +166,42 @@ pub(crate) fn create_temp(tmp: &Path) -> Result<File, CoordError> { .open(tmp) .map_err(|e| io(tmp, e)) } + +/// Refuse a record path whose directory components below `root` are not all real +/// directories. Every existing component from `root` (exclusive) down to `path`'s parent is +/// checked with `lstat`: a symbolic link is refused (a write would otherwise land outside the +/// store, and a read would load a record the listing never shows, since listing does not +/// follow symlinked directories), and anything else that is not a directory is refused as +/// not regular. Components that do not exist yet are fine; they are created as real +/// directories by the writer. A path outside `root` is refused as a symlink escape. +pub(crate) fn check_real_parents(root: &Path, path: &Path) -> Result<(), CoordError> { + let parent = path.parent().unwrap_or(Path::new("")); + let rel = parent + .strip_prefix(root) + .map_err(|_| refused(path, RecordRefusal::Symlink))?; + let mut cur = root.to_path_buf(); + for comp in rel.components() { + cur.push(comp); + match fs::symlink_metadata(&cur) { + Ok(m) => { + let ft = m.file_type(); + if ft.is_symlink() { + return Err(refused(&cur, RecordRefusal::Symlink)); + } + if !ft.is_dir() { + return Err(refused(&cur, RecordRefusal::NotDirectory)); + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(io(&cur, e)), + } + } + Ok(()) +} + +/// Read a store record file (at most [`MAX_RECORD_BYTES`]) without following a final +/// symbolic link or blocking on a FIFO; `Ok(None)` when it does not exist. For tools such +/// as the `synapse-coord canon` command, which must not trust the file they are given. +pub fn read_record_file(path: &Path) -> Result<Option<Vec<u8>>, CoordError> { + read_bounded(path, MAX_RECORD_BYTES) +} diff --git a/crates/synapse-coord/tests/hostile.rs b/crates/synapse-coord/tests/hostile.rs index 39f11b9..a8fade3 100644 --- a/crates/synapse-coord/tests/hostile.rs +++ b/crates/synapse-coord/tests/hostile.rs @@ -265,3 +265,82 @@ fn planted_lock_file_fifo_is_refused() { // Read-only sniff takes no lock, so it still answers. assert_eq!(sniff(&f).unwrap().locks.len(), 1); } + +/// Issue #63 item 1: a symlinked directory component under `dirs/` is refused for reads and +/// writes alike (listing already skips it), and nothing is written through it. +#[test] +fn symlinked_dir_component_under_dirs_is_refused_and_not_written_through() { + let f = fx("symlinkdir"); + seeded(&f); + fs::create_dir_all(f.top.join("sub/deep")).unwrap(); + fs::write(f.top.join("sub/deep/x.rs"), "x").unwrap(); + let outside = f.base.join("outside"); + fs::create_dir_all(&outside).unwrap(); + let link = f.store.join("dirs/sub"); + std::os::unix::fs::symlink(&outside, &link).unwrap(); + assert_eq!( + refusal(claim(&f, "sub/deep/x.rs")), + (link.clone(), RecordRefusal::Symlink) + ); + assert_eq!( + fs::read_dir(&outside).unwrap().count(), + 0, + "nothing may be written through the symlinked directory" + ); + // A regular file planted where a subdirectory is expected is refused as not a directory. + fs::remove_file(&link).unwrap(); + fs::write(&link, "not a dir").unwrap(); + assert_eq!( + refusal(claim(&f, "sub/deep/x.rs")), + (link.clone(), RecordRefusal::NotDirectory) + ); + // Removing it restores service: the record is created under a real directory. + fs::remove_file(&link).unwrap(); + assert!(matches!( + claim(&f, "sub/deep/x.rs").unwrap(), + ClaimOutcome::Claimed { .. } + )); + assert!(fs::symlink_metadata(&link).unwrap().is_dir()); +} + +/// Issue #63 item 4: a directory planted as `.lock` is a typed refusal, not `Io(EISDIR)`. +#[test] +fn planted_lock_file_directory_is_refused() { + let f = fx("lockdir"); + seeded(&f); + let lp = f.store.join(".lock"); + fs::remove_file(&lp).unwrap(); + fs::create_dir(&lp).unwrap(); + assert_eq!( + refusal(claim(&f, "src/b.rs")), + (lp.clone(), RecordRefusal::NotRegular("directory")) + ); + assert!(fs::symlink_metadata(&lp).unwrap().is_dir()); +} + +/// Issue #63 item 3: `synapse-coord canon` uses the bounded, non-blocking read, so a FIFO or +/// an oversize file is refused promptly instead of hanging or being read whole. +#[test] +fn canon_refuses_fifo_and_oversize_promptly() { + let f = fx("canon"); + fs::create_dir_all(&f.base).unwrap(); + let fifo = f.base.join("p.json"); + mkfifo(&fifo); + let big = f.base.join("big.json"); + let mut body = vec![b' '; synapse_coord::MAX_RECORD_BYTES as usize + 1]; + body[0] = b'{'; + *body.last_mut().unwrap() = b'}'; + fs::write(&big, &body).unwrap(); + let ok = f.base.join("ok.json"); + fs::write(&ok, br#"{ "b": 1, "a": 2 }"#).unwrap(); + for (p, want_ok) in [(fifo, false), (big, false), (ok, true)] { + let st = within("canon", move || { + std::process::Command::new(env!("CARGO_BIN_EXE_synapse-coord")) + .arg("canon") + .arg(&p) + .output() + .unwrap() + }); + assert_eq!(st.status.success(), want_ok, "{st:?}"); + } +}