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/aien-sovereign-core-mv/patches/8ef55a6de509d3a8 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#317 (code only) closed derived `8ef55a6de509d3a8` #317 Imported from GitHub aien-dev/aien-sovereign-core-mv#317 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `3acc2cb044464cc0934b4c8967f9bd332edbb7aa` · Head `7fbb000a3bcb95c59c77e559b0bfa394bf90bbce` ### Fetch it A git bundle of the pull request's head, 16877 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/8ef55a6de509d3a8.bundle -o 8ef55a6de509d3a8.bundle git fetch 8ef55a6de509d3a8.bundle refs/pull/317/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 317 7fbb000a3bcb95c59c77e559b0bfa394bf90bbce ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":317,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/317","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:48Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index e0ced61f..88d23072 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:2773d5ada0e6ae8b446499314f4a704361ab91a14a35259a62607b7c731d0ab9", - "compiled_at": "2026-10-08T03:14:47Z", + "compiled_at": "2026-10-08T04:19:10Z", "compiler": "crumb-compile/1", - "digest": "sha256:468bf2cc13f51b7d08ea67c7c1ffa63d4f4c3d375f0c4defb1367f4d24355649", + "digest": "sha256:ab3b19ba72dfcb9a077abfaf1a39bdbaa3876bfcc9aee8345b44477d9e5756b3", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1350, - "generated_at_commit": "bf43344b25d7b3f2b7dbde03e5432f8d53545808", - "source_tree": "sha256:addf1fa1e80454886a326fd28e9ae216d290d45b11be527a77a68ff607ec0468" + "files": 1352, + "generated_at_commit": "7e1e78cec04b6fc751e7377abc1d47bb414396cd", + "source_tree": "sha256:24a769aebf8bda35900e7ee22233147dae076d8beeb41aa5b29bbc6e965f1bfb" } }, "history": [], diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index 073a44e7..c9da646a 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -668,10 +668,15 @@ pub fn confined_world_state( // sovereign-core #267: confine and read through the same held directory // descriptors, so a swap after the check cannot redirect the read. match open_confined(&ws, &row.path, &row.target) { - Err(r) => ( - EffectState::Unresolved, - Err(format!("{}: {}", r.name, r.detail)), - ), + // The file exists but cannot be read: the plain read error, as before. + Err(r) if r.name == "Unreadable" => (EffectState::Unresolved, Err(r.detail)), + Err(r) => { + let r = outside_of(r); + ( + EffectState::Unresolved, + Err(format!("{}: {}", r.name, r.detail)), + ) + } Ok(t) => state_from(row, t.sha256()), } } @@ -804,6 +809,7 @@ pub struct ConfinedTarget { #[allow(dead_code)] // held so the chain stays open for the handle's life dir: std::os::fd::OwnedFd, pub file: Option, + target: String, } impl ConfinedTarget { @@ -817,7 +823,9 @@ impl ConfinedTarget { let mut h = Sha256::new(); let mut buf = [0u8; 64 * 1024]; loop { - let n = r.read(&mut buf).map_err(|e| format!("read target: {e}"))?; + let n = r + .read(&mut buf) + .map_err(|e| format!("read {}: {e}", self.target))?; if n == 0 { break; } @@ -827,6 +835,46 @@ impl ConfinedTarget { } } +/// Test seams (unit tests and, through the `test-support` feature, the +/// integration tests): a swap hook that fires inside the real call between +/// confinement and the read, one at the start of `open_confined`, and a switch +/// that forces the ENOSYS fallback walk. Never compiled into the daemon. +#[cfg(any(test, feature = "test-support"))] +pub mod test_hooks { + use std::cell::{Cell, RefCell}; + type Hook = RefCell>>; + thread_local! { + static PAUSE: Hook = const { RefCell::new(None) }; + static BEFORE: Hook = const { RefCell::new(None) }; + static FALLBACK: Cell = const { Cell::new(false) }; + } + /// Run `f` once, right after confinement succeeded and before any read. + pub fn set_pause(f: impl FnOnce() + 'static) { + PAUSE.with(|p| *p.borrow_mut() = Some(Box::new(f))); + } + /// Run `f` once, at the start of `open_confined`, before any descriptor opens. + pub fn set_before(f: impl FnOnce() + 'static) { + BEFORE.with(|p| *p.borrow_mut() = Some(Box::new(f))); + } + /// Force the per-component fallback walk (as on a kernel without openat2). + pub fn set_force_fallback(on: bool) { + FALLBACK.with(|f| f.set(on)); + } + pub(super) fn run_pause() { + if let Some(f) = PAUSE.with(|p| p.borrow_mut().take()) { + f(); + } + } + pub(super) fn run_before() { + if let Some(f) = BEFORE.with(|p| p.borrow_mut().take()) { + f(); + } + } + pub(super) fn force_fallback() -> bool { + FALLBACK.with(|f| f.get()) + } +} + /// `openat2(2)` syscall number: 437 on every architecture that has it. const SYS_OPENAT2: libc::c_long = 437; @@ -858,21 +906,33 @@ fn open_beneath( mode: 0, resolve: libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS, }; - // SAFETY: valid C string and a correctly sized open_how; a descriptor - // returned (>= 0) is owned by nobody else and wrapped immediately. - let fd = unsafe { - libc::syscall( - SYS_OPENAT2, - dirfd, - c.as_ptr(), - &how as *const OpenHow, - std::mem::size_of::(), - ) + #[cfg(any(test, feature = "test-support"))] + let force_fallback = test_hooks::force_fallback(); + #[cfg(not(any(test, feature = "test-support")))] + let force_fallback = false; + let fd = if force_fallback { + -1 + } else { + // SAFETY: valid C string and a correctly sized open_how; a descriptor + // returned (>= 0) is owned by nobody else and wrapped immediately. + unsafe { + libc::syscall( + SYS_OPENAT2, + dirfd, + c.as_ptr(), + &how as *const OpenHow, + std::mem::size_of::(), + ) + } }; if fd >= 0 { return Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as libc::c_int) }); } - let err = std::io::Error::last_os_error(); + let err = if force_fallback { + std::io::Error::from_raw_os_error(libc::ENOSYS) + } else { + std::io::Error::last_os_error() + }; if err.raw_os_error() != Some(libc::ENOSYS) { return Err(err); } @@ -899,10 +959,16 @@ fn open_beneath( cur.ok_or_else(|| std::io::Error::from_raw_os_error(libc::EINVAL)) } -/// Open a confined target (see `ConfinedTarget`). Same refusals as -/// `confine_target` ("OutsideWorkspace"). Ancestors of the workspace root -/// itself are trusted (checked canonical, opened `O_NOFOLLOW`); everything -/// below it is resolved beneath that held descriptor. +/// Open a confined target (see `ConfinedTarget`). Ancestors of the workspace +/// root itself are trusted (checked canonical, opened `O_NOFOLLOW`); +/// everything below it is resolved beneath that held descriptor. +/// +/// Refusal names. `OutsideWorkspace`: the shape checks, an escape, an +/// intermediate symlink or non-directory. Three INTERNAL names let each caller +/// keep the refusal it always gave (they never leave this module): +/// `NotRegular` (the final component exists and is a symlink, directory or +/// other non-file), `Unreadable` (the file exists but cannot be opened) and +/// `MissingParent` (a directory above the target is absent). pub fn open_confined(workspace: &str, path: &str, target: &str) -> Result { use std::os::fd::FromRawFd; let out = |w: String| Refusal::new("OutsideWorkspace", w); @@ -924,47 +990,82 @@ pub fn open_confined(workspace: &str, path: &str, target: &str) -> Result { let f = std::fs::File::from(fd); let m = f .metadata() - .map_err(|e| out(format!("target {target}: {e}")))?; + .map_err(|e| Refusal::new("Unreadable", format!("read {target}: {e}")))?; if !m.file_type().is_file() { - return Err(refuse_kind()); + return Err(not_regular()); } Some(f) } - Err(e) if e.raw_os_error() == Some(libc::ELOOP) => return Err(refuse_kind()), - // EXDEV: RESOLVE_BENEATH refused an escape. - Err(e) if e.raw_os_error() == Some(libc::EXDEV) => { - return Err(out(format!("target {target} resolves outside {workspace}"))) + // ELOOP: a symlink. In the last component it is a non-regular target; + // in a directory component it is an escape route. + Err(e) if e.raw_os_error() == Some(libc::ELOOP) => { + let leaf = parent.is_none_or(|p| open_beneath(dir.as_raw_fd(), p, dir_flags).is_ok()); + return Err(if leaf { + not_regular() + } else { + out(format!( + "target directory of {target} passes through a symlink" + )) + }); + } + // EXDEV: RESOLVE_BENEATH refused an escape. ENOTDIR: a component is not a directory. + Err(e) if matches!(e.raw_os_error(), Some(libc::EXDEV | libc::ENOTDIR)) => { + return Err(out(format!( + "target directory of {target}: {e} (outside or not a directory)" + ))) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - // Absent file is fine; an absent or non-directory parent is not. - if let Some(parent) = rel.parent().filter(|p| !p.as_os_str().is_empty()) { - open_beneath(dir.as_raw_fd(), parent, libc::O_RDONLY | libc::O_DIRECTORY).map_err( - |e| { - out(format!( - "target directory of {target}: {e} (outside, missing or a symlink)" - )) - }, - )?; + // Absent file is fine; an absent parent directory is not. + if let Some(p) = parent { + if let Err(pe) = open_beneath(dir.as_raw_fd(), p, dir_flags) { + return Err(match pe.raw_os_error() { + Some(libc::ENOENT) => Refusal::new( + "MissingParent", + format!("target directory of {target}: {pe} (missing)"), + ), + _ => out(format!( + "target directory of {target}: {pe} (outside or a symlink)" + )), + }); + } } None } - Err(e) => return Err(out(format!("target {target}: {e}"))), + Err(e) => return Err(Refusal::new("Unreadable", format!("read {target}: {e}"))), }; - #[cfg(test)] - tests::run_pause_hook(); - Ok(ConfinedTarget { dir, file }) + #[cfg(any(test, feature = "test-support"))] + test_hooks::run_pause(); + Ok(ConfinedTarget { + dir, + file, + target: target.to_string(), + }) +} + +/// The refusal an outside caller sees: the internal names collapse to +/// `OutsideWorkspace`, exactly what `confine_target` always returned for them. +fn outside_of(r: Refusal) -> Refusal { + match r.name { + "NotRegular" | "MissingParent" | "Unreadable" => Refusal::new("OutsideWorkspace", r.detail), + _ => r, + } } /// Workspace confinement of an effect target (sovereign-core #249): the @@ -972,11 +1073,15 @@ pub fn open_confined(workspace: &str, path: &str, target: &str) -> Result Result<(), Refusal> { - open_confined(workspace, path, target).map(|_| ()) + match open_confined(workspace, path, target) { + Ok(_) => Ok(()), + Err(r) => Err(outside_of(r)), + } } /// `confine_target` and the sha256 of the target in one held walk. @@ -984,10 +1089,10 @@ pub fn confined_sha256( workspace: &str, path: &str, target: &str, -) -> Result, Refusal> { - open_confined(workspace, path, target)? +) -> Result, String> { + open_confined(workspace, path, target) + .map_err(|r| outside_of(r).to_string())? .sha256() - .map_err(|e| Refusal::new("OutsideWorkspace", e)) } /// An approved grant must be backed by its COMMITTED replay claim: same @@ -1073,8 +1178,8 @@ pub(crate) fn write_approved_grant( ) -> Result<(u64, String), String> { b.with_home(|home| { let target = Path::new(workspace).join(path).display().to_string(); - confine_target(workspace, path, &target).map_err(|r| r.to_string())?; - let prior = file_sha256(Path::new(&target))?; + // #267 follow-up: confine and hash through one held handle. + let prior = confined_sha256(workspace, path, &target)?; // The file must still be the one the bound requirements were checked against. if let Some(base) = base { let now = prior.as_deref().unwrap_or("absent"); @@ -1251,7 +1356,10 @@ pub fn authorize( )); } let target = Path::new(&c.workspace).join(&c.path).display().to_string(); - confine_target(&c.workspace, &c.path, &target).map_err(|r| r.to_string())?; + // #267 follow-up: keep the confined handle; the prior hash below is + // read from it, not re-resolved by path after the MAC checks. + let held = open_confined(&c.workspace, &c.path, &target) + .map_err(|r| outside_of(r).to_string())?; if let Some((key, p)) = &desk { // Path, content and workspace are the daemon's own commit record; // the MAC must cover exactly those. @@ -1275,7 +1383,7 @@ pub fn authorize( )); } } - let prior = file_sha256(Path::new(&target))?; + let prior = held.sha256()?; for &gid in l.minted_by_commit.get(&c.id).into_iter().flatten() { if l.revoked.contains_key(&gid) || l.stops.iter().any(|&s| s > gid) { continue; @@ -1389,6 +1497,56 @@ fn noted(r: Result) -> ControlResponse { } } +/// What `open_intent` learned about the target before the grant checks. +enum IntentRead { + /// The hash of the target (None when absent), read through the handle + /// confinement opened. + Prior(Option), + /// The target cannot be read as a regular file (a directory, a leaf + /// symlink, no permission). Refused at once as "Stale", exactly where the + /// old by-path read refused it, before the grant is looked at. + Stale(String), + /// A directory above the target is absent: the old read saw "absent"; so + /// does the grant check, then the confinement refusal follows. + MissingParent(String), + /// The path escapes the workspace (symlinked or non-directory component, + /// bad shape). Nothing outside is read; the grant checks run with the + /// grant's own prior standing in, then this refusal follows. + Outside(String), +} + +/// The prior hash an intent records (#267 follow-up): when the grant names a +/// workspace, the target is confined and hashed through one held handle +/// BEFORE any other check, so what is compared with the grant is what +/// confinement checked. A grant with no workspace keeps the by-path read (it +/// is refused right after: it names no workspace). +fn intent_prior(l: &Ledger, req: &IntentRequest) -> IntentRead { + let stale = |e: String| { + IntentRead::Stale(Refusal::new("Stale", format!("target unreadable: {e}")).to_string()) + }; + let ws = l + .grants + .get(&req.authorization) + .and_then(|g| g.workspace.as_deref()); + let Some(ws) = ws else { + return match file_sha256(Path::new(&req.target)) { + Ok(p) => IntentRead::Prior(p), + Err(e) => stale(e), + }; + }; + match open_confined(ws, &req.path, &req.target) { + Ok(t) => match t.sha256() { + Ok(p) => IntentRead::Prior(p), + Err(e) => stale(e), + }, + Err(r) => match r.name { + "NotRegular" | "Unreadable" => stale(r.detail), + "MissingParent" => IntentRead::MissingParent(outside_of(r).to_string()), + _ => IntentRead::Outside(r.to_string()), + }, + } +} + /// ComposeEffectIntent: every check of 2.3 and the durable intent, in one /// step under the home lock. The answer's id is the intent. pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { @@ -1398,18 +1556,33 @@ pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { noted(b.with_home(|home| { let views = host_views(home)?; let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; - let current = file_sha256(Path::new(&req.target)) - .map_err(|e| Refusal::new("Stale", format!("target unreadable: {e}")).to_string())?; + // Refusal order is the one callers always saw: an unreadable target is + // "Stale" first; then the grant checks; then confinement. A confinement + // refusal found while reading is held back until the grant checks ran. + let (current, deferred) = match intent_prior(&l, req) { + IntentRead::Prior(p) => (p, None), + IntentRead::Stale(e) => return Err(e), + IntentRead::MissingParent(e) => (None, Some(e)), + IntentRead::Outside(e) => ( + l.grants + .get(&req.authorization) + .and_then(|g| g.prior_sha256.clone().flatten()), + Some(e), + ), + }; let g = l.check_intent(req, ¤t).map_err(|r| r.to_string())?; - // sovereign-core #249: confinement, and an approved grant's backing. - let ws = g.workspace.as_deref().ok_or_else(|| { - Refusal::new( + // sovereign-core #249: a grant names its workspace; confinement (already + // done above, through the handle that was read); an approved grant's backing. + if g.workspace.is_none() { + return Err(Refusal::new( "NotAuthorized", format!("authorization #{} names no workspace", g.id), ) - .to_string() - })?; - confine_target(ws, &req.path, &req.target).map_err(|r| r.to_string())?; + .to_string()); + } + if let Some(e) = deferred { + return Err(e); + } check_approved_backing(&l, g, &views).map_err(|r| r.to_string())?; check_minted_backing(&l, g).map_err(|r| r.to_string())?; let text = json!({ @@ -1971,18 +2144,6 @@ mod tests { ); } - thread_local! { - static PAUSE: std::cell::RefCell>> = - const { std::cell::RefCell::new(None) }; - } - - /// Test seam: runs once between confinement and the read. - pub(super) fn run_pause_hook() { - if let Some(f) = PAUSE.with(|p| p.borrow_mut().take()) { - f(); - } - } - /// #267 red/green: a parent swapped for a symlink to a directory holding /// the expected bytes, exactly between confinement and the read, must not /// make the world check DONE. (Old code: confine_target, then read by @@ -1998,17 +2159,144 @@ mod tests { std::fs::write(outside.join("f"), b"expected").unwrap(); let l = race_ledger(&ws, b"expected"); let (w2, o2) = (ws.clone(), outside.clone()); - PAUSE.with(|p| { - *p.borrow_mut() = Some(Box::new(move || { - std::fs::rename(w2.join("d"), w2.join("d.held")).unwrap(); - std::os::unix::fs::symlink(&o2, w2.join("d")).unwrap(); - })) + test_hooks::set_pause(move || { + std::fs::rename(w2.join("d"), w2.join("d.held")).unwrap(); + std::os::unix::fs::symlink(&o2, w2.join("d")).unwrap(); }); let (st, disk) = confined_world_state(&l, &l.intents[&3]); assert_ne!(st, EffectState::Done, "read outside bytes: {disk:?}"); assert_eq!(st, EffectState::Unresolved); assert_eq!(disk.unwrap(), Some(hex(&Sha256::digest(b"inside")))); } + + /// #267 follow-up, grant creation: the REAL `write_approved_grant`, with the + /// parent swapped for a symlink to a directory holding other bytes exactly + /// between its confinement and its read. The grant must record the hash of + /// the file confinement checked, and a `base` equal to that hash must + /// still pass. (With the by-path read the recorded prior is the OUTSIDE + /// hash and `base` is refused as BaseChanged.) + #[test] + fn write_approved_grant_records_the_prior_of_the_confined_file() { + use crate::spine::{ComposeBridge, Generation}; + if !aien_omega_compose::LINKED { + eprintln!("NOT_RUN: stub compose build"); + return; + } + let t = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(t.path()).unwrap(); + let (ws, outside) = (root.join("ws"), root.join("outside")); + std::fs::create_dir_all(ws.join("d")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(ws.join("d/NOTES.md"), b"inside").unwrap(); + std::fs::write(outside.join("NOTES.md"), b"expected").unwrap(); + let proposer: crate::spine::ComposeProposer = + std::sync::Arc::new(|_: &str, _: std::time::Duration| { + Ok(Generation { + text: "filename: d/NOTES.md\nkeep it\n".to_string(), + tokens: 4, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }); + let b = ComposeBridge::new(root.join("compose"), proposer, "test:fixed"); + let ControlResponse::ComposeTaskResult(rep) = b.run_task("g", ws.to_str().unwrap()) else { + panic!("run_task did not produce a result") + }; + let cx = rep.cx_promotion; + let link = ApprovedLink { + approval_key: "k".into(), + replay_claim: cx, + cx_promotion: cx, + cx_evidence: cx, + }; + let w = ws.to_str().unwrap(); + let prior_of = |id: u64| -> Value { + let ControlResponse::ComposeRecalled(r) = b.recall(&[id], None) else { + panic!("recall failed") + }; + let v: Value = serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap(); + v["prior_sha256"].clone() + }; + for base in [None, Some(hex(&Sha256::digest(b"inside")))] { + let (w2, o2) = (ws.clone(), outside.clone()); + test_hooks::set_pause(move || swap_in_symlink(&w2, &o2)); + let r = write_approved_grant( + &b, + w, + "d/NOTES.md", + "c", + "drake", + &json!({}), + &link, + "p", + base.as_deref(), + ); + let (id, _) = r.unwrap_or_else(|e| panic!("grant refused: {e}")); + assert_eq!( + prior_of(id), + json!(hex(&Sha256::digest(b"inside"))), + "the grant recorded bytes that confinement did not check" + ); + // put the directory back for the next round + std::fs::remove_file(ws.join("d")).unwrap(); + std::fs::rename(ws.join("d.held"), ws.join("d")).unwrap(); + } + } + + fn swap_in_symlink(ws: &Path, outside: &Path) { + std::fs::rename(ws.join("d"), ws.join("d.held")).unwrap(); + std::os::unix::fs::symlink(outside, ws.join("d")).unwrap(); + } + + fn h(b: &[u8]) -> Option { + Some(hex(&Sha256::digest(b))) + } + + /// Both the openat2 path and the forced ENOSYS fallback walk give the same + /// exact refusal for every shape: a symlink in a middle component, a symlink + /// to a file in a middle component (ELOOP) as against a plain file there + /// (ENOTDIR), a symlink as the last component, a missing parent, and a + /// `..` path. + #[test] + fn fallback_walk_refuses_symlinks_and_outside_paths() { + let t = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(t.path()).unwrap(); + let (ws, outside) = (root.join("ws"), root.join("outside")); + std::fs::create_dir_all(ws.join("a/b")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("f"), b"expected").unwrap(); + std::fs::write(ws.join("a/b/f"), b"inside").unwrap(); + std::fs::write(ws.join("a/file"), b"plain file").unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("s")).unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("a/l")).unwrap(); + std::os::unix::fs::symlink(outside.join("f"), ws.join("a/b/lf")).unwrap(); + std::os::unix::fs::symlink(ws.join("a/file"), ws.join("a/lfile")).unwrap(); + let w = ws.to_str().unwrap(); + let open = |p: &str| open_confined(w, p, &ws.join(p).display().to_string()); + for forced in [false, true] { + test_hooks::set_force_fallback(forced); + assert_eq!(open("a/b/f").unwrap().sha256().unwrap(), h(b"inside")); + assert!(open("a/b/new").unwrap().file.is_none()); + for (p, want) in [ + ("s/f", "OutsideWorkspace"), // symlink to a dir, middle + ("a/l/f", "OutsideWorkspace"), // same, deeper + ("a/lfile/f", "OutsideWorkspace"), // symlink to a FILE, middle: ELOOP + ("a/file/f", "OutsideWorkspace"), // plain file, middle: ENOTDIR + ("a/b/lf", "NotRegular"), // symlink, last component + ("s", "NotRegular"), // symlink, only component + ("a/missing/f", "MissingParent"), + ] { + let e = open(p) + .err() + .unwrap_or_else(|| panic!("{p} was opened (forced={forced})")); + assert_eq!(e.name, want, "{p} (forced={forced}): {}", e.detail); + } + let e = open_confined(w, "../outside/f", &format!("{w}/../outside/f")); + assert_eq!(e.err().unwrap().name, "OutsideWorkspace"); + } + test_hooks::set_force_fallback(false); + } + /// Ledger with one daemon-minted grant for `ws` and one open intent /// (#3) writing `d/f` with content `want`. fn race_ledger(ws: &Path, want: &[u8]) -> Ledger { diff --git a/crates/aien-runtime/tests/confine_race_test.rs b/crates/aien-runtime/tests/confine_race_test.rs new file mode 100644 index 00000000..fa8d5559 --- /dev/null +++ b/crates/aien-runtime/tests/confine_race_test.rs @@ -0,0 +1,184 @@ +//! sovereign-core #267 follow-up: the REAL `mint_grant` (authorize) and +//! `open_intent` calls, with a swap fired INSIDE the call between the +//! confinement check and the read. Each asserts an exact outcome: the recorded +//! prior is the hash of the file the confinement check saw, or a specific +//! refusal. Needs the linked composition archive; IGNORED in a stub build. +//! branch must give the identical kind for every row. +//! +//! Needs the linked composition archive; IGNORED in a stub build. +use aien_omega_compose::hex; +use aien_runtime::control::{ComposeNoteReport, ComposeTaskReport, ControlResponse}; +use aien_runtime::effects::test_hooks; +use aien_runtime::effects::{self, IntentRequest, MintRequest}; +use aien_runtime::spine::{ComposeBridge, ComposeProposer, Generation}; +use sha2::{Digest, Sha256}; +use std::path::PathBuf; +use std::sync::Arc; + +const PROPOSAL: &str = "filename: d/NOTES.md\nkeep every change inside the workspace\n"; +const CONTENT: &str = "keep every change inside the workspace\n"; + +fn proposer() -> ComposeProposer { + Arc::new(|_p: &str, _l: std::time::Duration| { + Ok(Generation { + text: PROPOSAL.to_string(), + tokens: 8, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +static ONE_HOME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +struct Fx { + _turn: std::sync::MutexGuard<'static, ()>, + _tmp: tempfile::TempDir, + root: PathBuf, + ws: PathBuf, + b: ComposeBridge, + report: ComposeTaskReport, +} + +impl Fx { + fn new() -> Option { + let turn = ONE_HOME.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + let ws = root.join("ws"); + std::fs::create_dir_all(ws.join("d")).unwrap(); + let b = ComposeBridge::new(root.join("compose"), proposer(), "test:fixed-proposer"); + let run = b.run_task("write the note", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + return None; + } + let ControlResponse::ComposeTaskResult(report) = run else { + panic!("run: {run:?}") + }; + assert!(report.committed, "{report:?}"); + Some(Fx { + _turn: turn, + _tmp: tmp, + root, + ws, + b, + report: *report, + }) + } + fn file(&self) -> PathBuf { + self.ws.join("d/NOTES.md") + } + fn mint_req(&self) -> MintRequest { + MintRequest { + cx_promotion: self.report.cx_promotion, + proposal_sha256: sha(PROPOSAL.as_bytes()), + workspace: self.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + } + } + fn req(&self, a: u64, wrong_grant: bool) -> IntentRequest { + let (pid, start) = effects::self_executor(); + IntentRequest { + authorization: a, + proposal_sha256: sha(PROPOSAL.as_bytes()), + path: "d/NOTES.md".into(), + target: self.file().display().to_string(), + content_sha256: if wrong_grant { + sha(b"other") + } else { + sha(CONTENT.as_bytes()) + }, + executor_pid: pid, + executor_start: start, + } + } +} + +fn id(r: ControlResponse) -> u64 { + match r { + ControlResponse::ComposeNoted(ComposeNoteReport { id, .. }) => id, + other => panic!("expected a note, got {other:?}"), + } +} + +fn text(fx: &Fx, id: u64) -> serde_json::Value { + match fx.b.recall(&[id], None) { + ControlResponse::ComposeRecalled(r) => { + serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap() + } + other => panic!("recall: {other:?}"), + } +} + +/// Move the real `d` aside and put a symlink to `outside` in its place. +fn swap_in_symlink(ws: PathBuf, outside: PathBuf) { + std::fs::rename(ws.join("d"), ws.join("d.held")).unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("d")).unwrap(); +} + +/// authorize: `d` is swapped for a symlink to outside bytes after the +/// confinement check and before the read. The grant must record the hash of the +/// inside file (what confinement approved), never the outside bytes. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] +fn mint_records_the_prior_of_the_confined_file() { + let Some(fx) = Fx::new() else { return }; + let outside = fx.root.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(fx.file(), "inside").unwrap(); + std::fs::write(outside.join("NOTES.md"), "expected").unwrap(); + let (ws, o) = (fx.ws.clone(), outside.clone()); + test_hooks::set_pause(move || swap_in_symlink(ws, o)); + let g = id(effects::mint_grant(&fx.b, &fx.mint_req())); + assert!( + fx.ws.join("d").is_symlink(), + "the swap hook did not fire inside the call" + ); + assert_eq!( + text(&fx, g)["prior_sha256"], + serde_json::json!(sha(b"inside")), + "the grant recorded bytes that confinement did not check" + ); +} + +/// open_intent: the grant was minted on "old\n". `d` is then a symlink to an +/// outside directory that holds the SAME bytes, while the real `d` (now +/// holding different bytes) is parked. The swap back to the real directory +/// fires at the start of the confined open. The read must see the real file, +/// find it changed, and refuse as Stale with no intent recorded. A by-path read +/// done before the swap would read the outside "old\n", match the grant and +/// record an intent. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] +fn open_intent_reads_the_confined_file_not_the_path() { + let Some(fx) = Fx::new() else { return }; + let outside = fx.root.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(fx.file(), "old\n").unwrap(); + let g = id(effects::mint_grant(&fx.b, &fx.mint_req())); + std::fs::write(outside.join("NOTES.md"), "old\n").unwrap(); + std::fs::write(fx.file(), "changed\n").unwrap(); + swap_in_symlink(fx.ws.clone(), outside); + let ws = fx.ws.clone(); + test_hooks::set_before(move || { + std::fs::remove_file(ws.join("d")).unwrap(); + std::fs::rename(ws.join("d.held"), ws.join("d")).unwrap(); + }); + let r = effects::open_intent(&fx.b, &fx.req(g, false)); + assert!( + !fx.ws.join("d").is_symlink(), + "the swap hook did not fire inside the call" + ); + match &r { + ControlResponse::Error(e) => assert!( + e.starts_with("EFFECT_REFUSED Stale"), + "wanted Stale, got {e}" + ), + other => panic!("wanted a Stale refusal, got {other:?}"), + } +} diff --git a/crates/aien-runtime/tests/refusal_table_test.rs b/crates/aien-runtime/tests/refusal_table_test.rs new file mode 100644 index 00000000..01dcea00 --- /dev/null +++ b/crates/aien-runtime/tests/refusal_table_test.rs @@ -0,0 +1,296 @@ +//! sovereign-core #267 follow-up: a security fix must not change the refusal +//! an old caller gets. This table drives the REAL `authorize` (mint_grant) and +//! `open_intent` over eight target states and records the refusal KIND each +//! gets. The same file ran on origin/main (3acc2cb) to produce EXPECTED; the +//! branch must give the identical kind for every row. +//! +//! Needs the linked composition archive; IGNORED in a stub build. +use aien_omega_compose::hex; +use aien_runtime::control::{ComposeNoteReport, ComposeTaskReport, ControlResponse}; +use aien_runtime::effects::{self, IntentRequest, MintRequest}; +use aien_runtime::spine::{ComposeBridge, ComposeProposer, Generation}; +use sha2::{Digest, Sha256}; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::sync::Arc; + +const PROPOSAL: &str = "filename: d/NOTES.md\nkeep every change inside the workspace\n"; +const CONTENT: &str = "keep every change inside the workspace\n"; + +fn proposer() -> ComposeProposer { + Arc::new(|_p: &str, _l: std::time::Duration| { + Ok(Generation { + text: PROPOSAL.to_string(), + tokens: 8, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +static ONE_HOME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +struct Fx { + _turn: std::sync::MutexGuard<'static, ()>, + _tmp: tempfile::TempDir, + root: PathBuf, + ws: PathBuf, + b: ComposeBridge, + report: ComposeTaskReport, +} + +impl Fx { + fn new() -> Option { + let turn = ONE_HOME.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + let ws = root.join("ws"); + std::fs::create_dir_all(ws.join("d")).unwrap(); + let b = ComposeBridge::new(root.join("compose"), proposer(), "test:fixed-proposer"); + let run = b.run_task("write the note", ws.to_str().unwrap()); + if !aien_omega_compose::LINKED { + return None; + } + let ControlResponse::ComposeTaskResult(report) = run else { + panic!("run: {run:?}") + }; + assert!(report.committed, "{report:?}"); + Some(Fx { + _turn: turn, + _tmp: tmp, + root, + ws, + b, + report: *report, + }) + } + fn file(&self) -> PathBuf { + self.ws.join("d/NOTES.md") + } + fn mint_req(&self) -> MintRequest { + MintRequest { + cx_promotion: self.report.cx_promotion, + proposal_sha256: sha(PROPOSAL.as_bytes()), + workspace: self.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + } + } + fn req(&self, a: u64, wrong_grant: bool) -> IntentRequest { + let (pid, start) = effects::self_executor(); + IntentRequest { + authorization: a, + proposal_sha256: sha(PROPOSAL.as_bytes()), + path: "d/NOTES.md".into(), + target: self.file().display().to_string(), + content_sha256: if wrong_grant { + sha(b"other") + } else { + sha(CONTENT.as_bytes()) + }, + executor_pid: pid, + executor_start: start, + } + } +} + +/// The refusal kind of a response: "OK", the EFFECT_REFUSED name, or the +/// first word of a plain error. +fn kind(r: &ControlResponse) -> String { + match r { + ControlResponse::Error(e) => match e.strip_prefix("EFFECT_REFUSED ") { + Some(rest) => rest.split(':').next().unwrap().to_string(), + None => format!("plain:{}", e.split_whitespace().next().unwrap_or("")), + }, + ControlResponse::ComposeNoted(_) => "OK".into(), + other => format!("other:{other:?}"), + } +} + +fn id(r: ControlResponse) -> u64 { + match r { + ControlResponse::ComposeNoted(ComposeNoteReport { id, .. }) => id, + other => panic!("expected a note, got {other:?}"), + } +} + +/// How the world is shaped before the call. +#[derive(Clone, Copy, Debug)] +enum World { + Valid, + Missing, + Directory, + PermissionDenied, + LeafSymlinkInside, + LeafSymlinkOutside, + IntermediateSymlinkSameBytes, + IntermediateSymlinkOtherBytes, + MissingParent, +} + +const WORLDS: [World; 9] = [ + World::Valid, + World::Missing, + World::Directory, + World::PermissionDenied, + World::LeafSymlinkInside, + World::LeafSymlinkOutside, + World::IntermediateSymlinkSameBytes, + World::IntermediateSymlinkOtherBytes, + World::MissingParent, +]; + +fn shape(fx: &Fx, w: World) { + let f = fx.file(); + let d = fx.ws.join("d"); + let outside = fx.root.join("outside"); + match w { + World::Valid => {} + World::Missing => std::fs::remove_file(&f).unwrap(), + World::Directory => { + std::fs::remove_file(&f).unwrap(); + std::fs::create_dir(&f).unwrap(); + } + World::PermissionDenied => { + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o000)).unwrap() + } + World::LeafSymlinkInside => { + std::fs::write(d.join("other"), "old\n").unwrap(); + std::fs::remove_file(&f).unwrap(); + std::os::unix::fs::symlink(d.join("other"), &f).unwrap(); + } + World::LeafSymlinkOutside => { + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("x"), "old\n").unwrap(); + std::fs::remove_file(&f).unwrap(); + std::os::unix::fs::symlink(outside.join("x"), &f).unwrap(); + } + World::IntermediateSymlinkSameBytes | World::IntermediateSymlinkOtherBytes => { + std::fs::create_dir_all(&outside).unwrap(); + let bytes = if matches!(w, World::IntermediateSymlinkSameBytes) { + "old\n" + } else { + "different\n" + }; + std::fs::write(outside.join("NOTES.md"), bytes).unwrap(); + std::fs::rename(&d, fx.ws.join("d.held")).unwrap(); + std::os::unix::fs::symlink(&outside, &d).unwrap(); + } + World::MissingParent => std::fs::remove_dir_all(&d).unwrap(), + } +} + +/// Rows: " | " -> kind. `wrong_grant` rows use a request whose +/// content differs from the grant (NotAuthorized on a readable target). +fn run_table() -> Vec<(String, String)> { + let mut rows = Vec::new(); + for w in WORLDS { + // authorize: the world is shaped, then the mint is asked. + { + let fx = Fx::new().unwrap(); + std::fs::write(fx.file(), "old\n").unwrap(); + shape(&fx, w); + let r = effects::mint_grant(&fx.b, &fx.mint_req()); + rows.push((format!("{w:?} | authorize"), kind(&r))); + } + // open_intent: a valid grant is minted on "old\n", then the world is shaped. + for wrong in [false, true] { + let fx = Fx::new().unwrap(); + std::fs::write(fx.file(), "old\n").unwrap(); + let g = id(effects::mint_grant(&fx.b, &fx.mint_req())); + shape(&fx, w); + let r = effects::open_intent(&fx.b, &fx.req(g, wrong)); + let op = if wrong { + "open_intent(wrong grant)" + } else { + "open_intent" + }; + rows.push((format!("{w:?} | {op}"), kind(&r))); + } + // restore permissions so the temp dir can be removed + let _ = w; + } + rows +} + +/// origin/main (3acc2cb) results for the same table (this file run there). +const EXPECTED: &[(&str, &str)] = &[ + ("Valid | authorize", "OK"), + ("Valid | open_intent", "OK"), + ("Valid | open_intent(wrong grant)", "NotAuthorized"), + ("Missing | authorize", "OK"), + ("Missing | open_intent", "Stale"), + ("Missing | open_intent(wrong grant)", "NotAuthorized"), + ("Directory | authorize", "OutsideWorkspace"), + ("Directory | open_intent", "Stale"), + ("Directory | open_intent(wrong grant)", "Stale"), + ("PermissionDenied | authorize", "OutsideWorkspace"), + ("PermissionDenied | open_intent", "Stale"), + ("PermissionDenied | open_intent(wrong grant)", "Stale"), + ("LeafSymlinkInside | authorize", "OutsideWorkspace"), + ("LeafSymlinkInside | open_intent", "Stale"), + ("LeafSymlinkInside | open_intent(wrong grant)", "Stale"), + ("LeafSymlinkOutside | authorize", "OutsideWorkspace"), + ("LeafSymlinkOutside | open_intent", "Stale"), + ("LeafSymlinkOutside | open_intent(wrong grant)", "Stale"), + ( + "IntermediateSymlinkSameBytes | authorize", + "OutsideWorkspace", + ), + ( + "IntermediateSymlinkSameBytes | open_intent", + "OutsideWorkspace", + ), + ( + "IntermediateSymlinkSameBytes | open_intent(wrong grant)", + "NotAuthorized", + ), + ( + "IntermediateSymlinkOtherBytes | authorize", + "OutsideWorkspace", + ), + ("IntermediateSymlinkOtherBytes | open_intent", "Stale"), + ( + "IntermediateSymlinkOtherBytes | open_intent(wrong grant)", + "NotAuthorized", + ), + ("MissingParent | authorize", "OutsideWorkspace"), + ("MissingParent | open_intent", "Stale"), + ("MissingParent | open_intent(wrong grant)", "NotAuthorized"), +]; + +/// The one row where the branch deliberately differs from origin/main. It is +/// still a refusal and stricter, not a weakening: main read the bytes THROUGH +/// the symlinked directory and said Stale; the branch never reads through the +/// symlink and says OutsideWorkspace. Telling Stale would need the outside +/// bytes: the very bug. +const DIFFERS: &[(&str, &str)] = &[( + "IntermediateSymlinkOtherBytes | open_intent", + "OutsideWorkspace", +)]; + +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] +fn refusal_kinds_match_origin_main() { + if !aien_omega_compose::LINKED { + return; + } + let rows = run_table(); + for (k, v) in &rows { + println!("ROW {k} => {v}"); + } + assert_eq!(rows.len(), EXPECTED.len()); + for (k, v) in &rows { + let main = EXPECTED + .iter() + .find(|(ek, _)| ek == k) + .unwrap_or_else(|| panic!("no expectation for {k}")) + .1; + let want = DIFFERS.iter().find(|(dk, _)| dk == k).map_or(main, |d| d.1); + assert_eq!(v, want, "{k}: branch gives {v}, origin/main gave {main}"); + } +} ```