Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-coord/tests/hostile.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-coord / tests / hostile.rs` 346 lines ยท 11607 bytes Raw Blame History 1 //! Hostile store files (issue #58): FIFOs, symlinks to devices, oversized records and a 2 //! FIFO `STORE_ID` must give a prompt, typed refusal, never a hang or an unbounded read, 3 //! and must never be overwritten. Every store call runs under a 5 s watchdog so a 4 //! regression fails the test instead of hanging the suite. 5 6 use std::fs; 7 use std::os::unix::fs::FileTypeExt; 8 use std::path::{Path, PathBuf}; 9 use std::sync::atomic::{AtomicU32, Ordering}; 10 use std::sync::mpsc; 11 use std::time::Duration; 12 use synapse_coord::{ 13 ClaimOutcome, CoordError, CoordStore, Holder, RecordRefusal, Workspace, MAX_RECORD_BYTES, 14 STORE_ID_FILE, 15 }; 16 17 static N: AtomicU32 = AtomicU32::new(0); 18 19 struct Fx { 20 base: PathBuf, 21 store: PathBuf, 22 top: PathBuf, 23 } 24 impl Drop for Fx { 25 fn drop(&mut self) { 26 let _ = fs::remove_dir_all(&self.base); 27 } 28 } 29 30 fn fx(tag: &str) -> Fx { 31 let base = std::env::temp_dir().join(format!( 32 "synapse-coord-hostile-{tag}-{}-{}", 33 std::process::id(), 34 N.fetch_add(1, Ordering::SeqCst) 35 )); 36 let _ = fs::remove_dir_all(&base); 37 let top = base.join("wa"); 38 fs::create_dir_all(top.join("src")).unwrap(); 39 fs::write(top.join("src/a.rs"), "a").unwrap(); 40 Fx { 41 store: base.join("store"), 42 top, 43 base, 44 } 45 } 46 47 fn ws(top: &Path) -> Workspace { 48 Workspace::worktree(top.to_str().unwrap(), Holder::git("A", "0123", "4567")) 49 } 50 51 fn mkfifo(p: &Path) { 52 let c = std::ffi::CString::new(p.to_str().unwrap()).unwrap(); 53 // SAFETY: valid NUL-terminated path. 54 assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o644) }, 0, "{p:?}"); 55 } 56 57 /// Run `f` on a thread; fail (instead of hanging) if it does not answer within 5 s. 58 fn within(what: &str, f: impl FnOnce() -> T + Send + 'static) -> T { 59 let (tx, rx) = mpsc::channel(); 60 std::thread::spawn(move || { 61 let _ = tx.send(f()); 62 }); 63 rx.recv_timeout(Duration::from_secs(5)) 64 .unwrap_or_else(|_| panic!("{what} did not answer within 5 s")) 65 } 66 67 /// A store with one live claim (so `dirs/`, `agents/` and `STORE_ID` exist). 68 fn seeded(f: &Fx) { 69 let r = CoordStore::open(&f.store) 70 .claim(&ws(&f.top), "alice", ".", "src/a.rs", "edit", Some(600)) 71 .unwrap(); 72 assert!(matches!(r, ClaimOutcome::Claimed { .. })); 73 } 74 75 fn sniff(f: &Fx) -> Result { 76 let (store, top) = (f.store.clone(), f.top.clone()); 77 within("sniff", move || { 78 CoordStore::open(store).sniff(&ws(&top), "bob", ".") 79 }) 80 } 81 82 fn claim(f: &Fx, target: &str) -> Result { 83 let (store, top, target) = (f.store.clone(), f.top.clone(), target.to_string()); 84 within("claim", move || { 85 CoordStore::open(store).claim(&ws(&top), "bob", ".", &target, "edit", Some(60)) 86 }) 87 } 88 89 fn refusal(r: Result) -> (PathBuf, RecordRefusal) { 90 match r { 91 Err(CoordError::RefusedRecord { path, reason }) => (path, reason), 92 other => panic!("expected RefusedRecord, got {other:?}"), 93 } 94 } 95 96 fn is_fifo(p: &Path) -> bool { 97 fs::symlink_metadata(p).unwrap().file_type().is_fifo() 98 } 99 100 #[test] 101 fn fifo_record_in_dirs_is_refused_promptly() { 102 let f = fx("fifo-dirs"); 103 seeded(&f); 104 let evil = f.store.join("dirs/evil.json"); 105 mkfifo(&evil); 106 let (p, r) = refusal(sniff(&f)); 107 assert_eq!((p, r), (evil.clone(), RecordRefusal::NotRegular("fifo"))); 108 // A mutation refuses too (its prune reads every record) and leaves the FIFO in place. 109 let (p, r) = refusal(claim(&f, "src/b.rs")); 110 assert_eq!((p, r), (evil.clone(), RecordRefusal::NotRegular("fifo"))); 111 assert!(is_fifo(&evil)); 112 // Moving it aside restores service. 113 fs::remove_file(&evil).unwrap(); 114 assert_eq!(sniff(&f).unwrap().locks.len(), 1); 115 } 116 117 #[test] 118 fn fifo_record_in_agents_is_refused_promptly() { 119 let f = fx("fifo-agents"); 120 seeded(&f); 121 let evil = f.store.join("agents/evil.json"); 122 mkfifo(&evil); 123 assert_eq!( 124 refusal(sniff(&f)), 125 (evil.clone(), RecordRefusal::NotRegular("fifo")) 126 ); 127 assert_eq!( 128 refusal(claim(&f, "src/b.rs")), 129 (evil.clone(), RecordRefusal::NotRegular("fifo")) 130 ); 131 assert!(is_fifo(&evil)); 132 } 133 134 #[test] 135 fn fifo_as_the_record_being_claimed_is_never_replaced() { 136 let f = fx("fifo-target"); 137 seeded(&f); 138 // The record for directory `src` is a FIFO; claiming in `src` must refuse, not rename 139 // a fresh record over it. 140 let evil = f.store.join("dirs/src.json"); 141 let _ = fs::remove_file(&evil); 142 mkfifo(&evil); 143 let (store, top) = (f.store.clone(), f.top.clone()); 144 let r = within("claim in src", move || { 145 CoordStore::open(store).claim(&ws(&top), "bob", "src", "a.rs", "edit", Some(60)) 146 }); 147 assert_eq!( 148 refusal(r), 149 (evil.clone(), RecordRefusal::NotRegular("fifo")) 150 ); 151 assert!(is_fifo(&evil)); 152 } 153 154 #[test] 155 fn fifo_store_id_is_refused_promptly() { 156 let f = fx("fifo-storeid"); 157 seeded(&f); 158 let id = f.store.join(STORE_ID_FILE); 159 fs::remove_file(&id).unwrap(); 160 mkfifo(&id); 161 assert_eq!( 162 refusal(sniff(&f)), 163 (id.clone(), RecordRefusal::NotRegular("fifo")) 164 ); 165 assert_eq!( 166 refusal(claim(&f, "src/b.rs")), 167 (id.clone(), RecordRefusal::NotRegular("fifo")) 168 ); 169 let store = f.store.clone(); 170 assert_eq!( 171 refusal(within("store_id", move || CoordStore::open(store).store_id())), 172 (id.clone(), RecordRefusal::NotRegular("fifo")) 173 ); 174 // A fresh store whose first mutating open finds a FIFO marker refuses and keeps it. 175 let g = fx("fifo-storeid-fresh"); 176 fs::create_dir_all(&g.store).unwrap(); 177 let gid = g.store.join(STORE_ID_FILE); 178 mkfifo(&gid); 179 assert_eq!( 180 refusal(claim(&g, "src/a.rs")), 181 (gid.clone(), RecordRefusal::NotRegular("fifo")) 182 ); 183 assert!(is_fifo(&gid)); 184 assert!(is_fifo(&id)); 185 } 186 187 #[test] 188 fn symlink_record_to_dev_zero_is_refused_without_reading() { 189 let f = fx("devzero"); 190 seeded(&f); 191 let z = f.store.join("dirs/zero.json"); 192 std::os::unix::fs::symlink("/dev/zero", &z).unwrap(); 193 assert_eq!(refusal(sniff(&f)), (z.clone(), RecordRefusal::Symlink)); 194 assert_eq!( 195 refusal(claim(&f, "src/b.rs")), 196 (z.clone(), RecordRefusal::Symlink) 197 ); 198 // The link is left as found. 199 assert_eq!(fs::read_link(&z).unwrap(), PathBuf::from("/dev/zero")); 200 // A symlink to a regular, valid record is refused too: records are never followed. 201 fs::remove_file(&z).unwrap(); 202 let real = f.base.join("real.json"); 203 fs::write(&real, b"{}").unwrap(); 204 std::os::unix::fs::symlink(&real, &z).unwrap(); 205 assert_eq!(refusal(sniff(&f)), (z, RecordRefusal::Symlink)); 206 } 207 208 #[test] 209 fn oversize_record_is_refused_and_cap_is_inclusive() { 210 let f = fx("oversize"); 211 seeded(&f); 212 let big = f.store.join("dirs/big.json"); 213 // Sparse file one byte over the cap: refused from fstat, nothing is read. 214 let h = fs::File::create(&big).unwrap(); 215 h.set_len(MAX_RECORD_BYTES + 1).unwrap(); 216 drop(h); 217 assert_eq!( 218 refusal(sniff(&f)), 219 ( 220 big.clone(), 221 RecordRefusal::TooLarge { 222 limit: MAX_RECORD_BYTES 223 } 224 ) 225 ); 226 assert_eq!( 227 fs::metadata(&big).unwrap().len(), 228 MAX_RECORD_BYTES + 1, 229 "not overwritten" 230 ); 231 // Exactly at the cap is read (and is valid JSON padded with spaces). 232 let mut at = b"{}".to_vec(); 233 at.resize(MAX_RECORD_BYTES as usize, b' '); 234 fs::write(&big, &at).unwrap(); 235 assert_eq!(sniff(&f).unwrap().locks.len(), 1); 236 } 237 238 #[test] 239 fn non_record_entries_are_ignored_and_symlinked_dirs_not_followed() { 240 let f = fx("ignored"); 241 seeded(&f); 242 // A FIFO without the .json suffix is not a record name: ignored, never opened. 243 mkfifo(&f.store.join("dirs/notes.fifo")); 244 // A symlinked directory (here a self loop) is not walked. 245 std::os::unix::fs::symlink(f.store.join("dirs"), f.store.join("dirs/loop")).unwrap(); 246 assert_eq!(sniff(&f).unwrap().locks.len(), 1); 247 assert!(matches!( 248 claim(&f, "src/b.rs").unwrap(), 249 ClaimOutcome::Claimed { .. } 250 )); 251 } 252 253 #[test] 254 fn planted_lock_file_fifo_is_refused() { 255 let f = fx("lockfifo"); 256 seeded(&f); 257 let lp = f.store.join(".lock"); 258 fs::remove_file(&lp).unwrap(); 259 mkfifo(&lp); 260 assert_eq!( 261 refusal(claim(&f, "src/b.rs")), 262 (lp.clone(), RecordRefusal::NotRegular("fifo")) 263 ); 264 assert!(is_fifo(&lp)); 265 // Read-only sniff takes no lock, so it still answers. 266 assert_eq!(sniff(&f).unwrap().locks.len(), 1); 267 } 268 269 /// Issue #63 item 1: a symlinked directory component under `dirs/` is refused for reads and 270 /// writes alike (listing already skips it), and nothing is written through it. 271 #[test] 272 fn symlinked_dir_component_under_dirs_is_refused_and_not_written_through() { 273 let f = fx("symlinkdir"); 274 seeded(&f); 275 fs::create_dir_all(f.top.join("sub/deep")).unwrap(); 276 fs::write(f.top.join("sub/deep/x.rs"), "x").unwrap(); 277 let outside = f.base.join("outside"); 278 fs::create_dir_all(&outside).unwrap(); 279 let link = f.store.join("dirs/sub"); 280 std::os::unix::fs::symlink(&outside, &link).unwrap(); 281 assert_eq!( 282 refusal(claim(&f, "sub/deep/x.rs")), 283 (link.clone(), RecordRefusal::Symlink) 284 ); 285 assert_eq!( 286 fs::read_dir(&outside).unwrap().count(), 287 0, 288 "nothing may be written through the symlinked directory" 289 ); 290 // A regular file planted where a subdirectory is expected is refused as not a directory. 291 fs::remove_file(&link).unwrap(); 292 fs::write(&link, "not a dir").unwrap(); 293 assert_eq!( 294 refusal(claim(&f, "sub/deep/x.rs")), 295 (link.clone(), RecordRefusal::NotDirectory) 296 ); 297 // Removing it restores service: the record is created under a real directory. 298 fs::remove_file(&link).unwrap(); 299 assert!(matches!( 300 claim(&f, "sub/deep/x.rs").unwrap(), 301 ClaimOutcome::Claimed { .. } 302 )); 303 assert!(fs::symlink_metadata(&link).unwrap().is_dir()); 304 } 305 306 /// Issue #63 item 4: a directory planted as `.lock` is a typed refusal, not `Io(EISDIR)`. 307 #[test] 308 fn planted_lock_file_directory_is_refused() { 309 let f = fx("lockdir"); 310 seeded(&f); 311 let lp = f.store.join(".lock"); 312 fs::remove_file(&lp).unwrap(); 313 fs::create_dir(&lp).unwrap(); 314 assert_eq!( 315 refusal(claim(&f, "src/b.rs")), 316 (lp.clone(), RecordRefusal::NotRegular("directory")) 317 ); 318 assert!(fs::symlink_metadata(&lp).unwrap().is_dir()); 319 } 320 321 /// Issue #63 item 3: `synapse-coord canon` uses the bounded, non-blocking read, so a FIFO or 322 /// an oversize file is refused promptly instead of hanging or being read whole. 323 #[test] 324 fn canon_refuses_fifo_and_oversize_promptly() { 325 let f = fx("canon"); 326 fs::create_dir_all(&f.base).unwrap(); 327 let fifo = f.base.join("p.json"); 328 mkfifo(&fifo); 329 let big = f.base.join("big.json"); 330 let mut body = vec![b' '; synapse_coord::MAX_RECORD_BYTES as usize + 1]; 331 body[0] = b'{'; 332 *body.last_mut().unwrap() = b'}'; 333 fs::write(&big, &body).unwrap(); 334 let ok = f.base.join("ok.json"); 335 fs::write(&ok, br#"{ "b": 1, "a": 2 }"#).unwrap(); 336 for (p, want_ok) in [(fifo, false), (big, false), (ok, true)] { 337 let st = within("canon", move || { 338 std::process::Command::new(env!("CARGO_BIN_EXE_synapse-coord")) 339 .arg("canon") 340 .arg(&p) 341 .output() 342 .unwrap() 343 }); 344 assert_eq!(st.status.success(), want_ok, "{st:?}"); 345 } 346 }