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/c197364dd2d1ea30 # 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#262 (code only) closed derived `c197364dd2d1ea30` #262 Imported from GitHub aien-dev/aien-sovereign-core-mv#262 (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 `735c97a8623f418c3ce2b8acc24c38c90d711dc5` · Head `964701485e08cc0abaed7b3732ff9121a61317b0` ### Fetch it A git bundle of the pull request's head, 84688 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/c197364dd2d1ea30.bundle -o c197364dd2d1ea30.bundle git fetch c197364dd2d1ea30.bundle refs/pull/262/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 262 964701485e08cc0abaed7b3732ff9121a61317b0 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":262,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/262","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:34Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 7839395a..62432597 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:4ff1a56b7c8ac606ad5709f2ba1141f16055c34f5f242ac491233dca20d5153e", - "compiled_at": "2026-10-07T03:51:32Z", + "compiled_at": "2026-10-07T04:04:12Z", "compiler": "crumb-compile/1", - "digest": "sha256:950da750f791d269aa8ab366556f3652cf49b9a06b1e74011dfc3d6d1962729a", + "digest": "sha256:1d809adb36da3ebedb06024df206f84cd51a8729712d2aa4f8bc2cd4e3712af3", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", - "files": 1119, - "generated_at_commit": "0b14ebab343e7cd911a8db1eded99d7a4718339e", - "source_tree": "sha256:8ff157daf713d6d9839d9d0c9720872d479e368575bdb78fe2143ffc14bb49ab" + "files": 1127, + "generated_at_commit": "0665895bfda2f5f17c7eec88ae4e4493e1b1d030", + "source_tree": "sha256:07d3ebde58e51ffd9111c4c875366fd0ffb0f87439a47fa8880201e7bdbc5f0b" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 9bcb974e..8cde56e8 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "6a6cc7468724c1e39da5894f241e7624a1e06cb1ba64aa1a57b11c8561cffcb2", - "last_commit": "a914490", + "digest": "f72fc5c4b197c4025e2b705412ad89319b6fcf8ce243d5c80319b9338d4cd434", + "last_commit": "0665895", "name": "src", "purpose": "" } ], - "children_root": "sha256:ece32049063166417cb3a3776ce48142e7d8508419ca2137329b429105347b01", - "compiled_at": "2026-10-07T03:37:34Z", + "children_root": "sha256:ec21789c3310a211aef981afbed6bb83adb598a73eafb51f6085b15a97cdaaeb", + "compiled_at": "2026-10-07T04:04:12Z", "compiler": "crumb-compile/1", - "digest": "sha256:49c03271c3d397db12777d39f844007b87ae1e684a0c1a522c3341f024391d0a", + "digest": "sha256:32b9f2b9c62f8aa5ee72c44c8c82042c4515a72aa55726538a6d7b8f6b2edd20", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 28, - "generated_at_commit": "a914490eb8ae8f9582ec31b498497eb4483ac400", - "source_tree": "sha256:1a0913028dd44628b2524bd46371813d7e17182776a4ae4cfe79339ce426ca03" + "generated_at_commit": "0665895bfda2f5f17c7eec88ae4e4493e1b1d030", + "source_tree": "sha256:aae6fcc239e2e70034557a27678bd875c15ff32992e3f3909ef4e322d2e36a76" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 48649b52..94abcdf2 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-07T03:37:34Z", + "compiled_at": "2026-10-07T04:04:12Z", "compiler": "crumb-compile/1", - "digest": "sha256:6a6cc7468724c1e39da5894f241e7624a1e06cb1ba64aa1a57b11c8561cffcb2", + "digest": "sha256:f72fc5c4b197c4025e2b705412ad89319b6fcf8ce243d5c80319b9338d4cd434", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "a914490eb8ae8f9582ec31b498497eb4483ac400", - "source_tree": "sha256:a229666f3c0ca085e00955867c49c65e30aaf99cff891f64aff548c808d8d118" + "generated_at_commit": "0665895bfda2f5f17c7eec88ae4e4493e1b1d030", + "source_tree": "sha256:b9990d063003a8155b056f7de543d605f553cc43160c6ad21a89313640a9e524" } }, "history": [ diff --git a/crates/aien-cli/src/compose.rs b/crates/aien-cli/src/compose.rs index d1df2a83..bb90f6bb 100644 --- a/crates/aien-cli/src/compose.rs +++ b/crates/aien-cli/src/compose.rs @@ -30,6 +30,9 @@ //! stop --approver NAME durable operator stop //! resume --approver NAME end the stop (old grants stay stale) //! revoke --authorization ID --approver NAME revoke an unspent grant +//! desk-key [--create 1] the approval desk key (#249): +//! prints its id and path, never the key; +//! --create 1 makes one if none exists //! //! S5 `execute` brackets the write with a durable intent and an ack (see //! `aien_runtime::effects`); it prints `"state"` and exits 3 when the effect @@ -257,6 +260,18 @@ async fn step(sub: &str, m: &HashMap) -> Result { let target = engine .validate_path(ws.join(&path).to_str().ok_or("path is not UTF-8")?) .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; + // sovereign-core #249: the grant names the canonical workspace + // (symlinks resolved, whatever form --workspace took) and the + // target must be exactly /, as the daemon checks. + let wsc = std::fs::canonicalize(&ws) + .map_err(|e| format!("workspace {}: {e}", ws.display()))?; + if target != wsc.join(&path) { + return Err(format!( + "CONFINEMENT DENIAL: target {} is not {}", + target.display(), + wsc.join(&path).display() + )); + } let csha = sha256_hex(content.as_bytes()); // NEXT-PHASE-2: the grant names the target and the state it was // granted against; a changed target makes it stale. @@ -272,7 +287,7 @@ async fn step(sub: &str, m: &HashMap) -> Result { links.extend(constraint.unwrap_or_default().into_iter().take(2)); let text = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, "approver": approver, "receipt_sha256": rc["sha256"], "target": tgt, - "prior_sha256": prior}); + "prior_sha256": prior, "workspace": wsc.display().to_string()}); let n = note("authorization", &text.to_string(), links).await?; Ok(json!({"step": "S4", "receipt": rc, "authorization": n, "approvals": 1})) } @@ -479,12 +494,23 @@ async fn step(sub: &str, m: &HashMap) -> Result { other => Err(format!("unexpected response {other:?}")), } } + "desk-key" => { + use aien_runtime::approved_auth::{desk_key_path, DeskKey}; + let dir = aien_runtime::spine::compose_dir_from_env()?; + let path = desk_key_path(&dir); + let key = match (DeskKey::load(&path), m.contains_key("create")) { + (Ok(k), _) => k, + (Err(_), true) if !path.exists() => DeskKey::create(&path)?, + (Err(e), _) => return Err(e), + }; + Ok(json!({"desk_key_id": key.id(), "path": path.display().to_string()})) + } "recover" => match send(ControlCommand::RecoverComposeHome).await? { ControlResponse::ComposeRecovered(r) => Ok(json!({"repair": r, "opens": r.opens})), other => Err(format!("unexpected response {other:?}")), }, other => Err(format!( - "unknown compose step {other:?} (remember, inspect, propose, authorize, execute, explain, recall, shutdown, recover, effects, reconcile, stop, resume, revoke)" + "unknown compose step {other:?} (remember, inspect, propose, authorize, execute, explain, recall, shutdown, recover, effects, reconcile, stop, resume, revoke, desk-key)" )), } } diff --git a/crates/aien-omega-compose/Cargo.toml b/crates/aien-omega-compose/Cargo.toml index 1d38fde5..53978fe6 100644 --- a/crates/aien-omega-compose/Cargo.toml +++ b/crates/aien-omega-compose/Cargo.toml @@ -6,6 +6,9 @@ authors = ["Drake Stapleton "] description = "FFI to omega COMPOSITION-2 (librx_compose.a, rxc_host ABI): goals through J-Space, AEGIS and Cortex" license.workspace = true build = "build.rs" +# Declared so dependents' build scripts see DEP_RX_COMPOSE_LINKED (aien-runtime +# gates its journal-dependent tests on it: ignored, not passed, in a stub build). +links = "rx_compose" [dependencies] sha2 = "0.10" diff --git a/crates/aien-omega-compose/build.rs b/crates/aien-omega-compose/build.rs index ff7ef456..3d64938b 100644 --- a/crates/aien-omega-compose/build.rs +++ b/crates/aien-omega-compose/build.rs @@ -121,6 +121,7 @@ fn link(lib: &Path) { println!("cargo:rustc-link-lib=dylib=m"); println!("cargo:rerun-if-changed={}", lib.display()); println!("cargo:rustc-cfg=has_omega_compose"); + println!("cargo:linked=1"); } fn is_sha(s: &str) -> bool { diff --git a/crates/aien-runtime/build.rs b/crates/aien-runtime/build.rs new file mode 100644 index 00000000..d4406f05 --- /dev/null +++ b/crates/aien-runtime/build.rs @@ -0,0 +1,11 @@ +//! `cfg(compose_linked)` when aien-omega-compose linked the real +//! librx_compose.a (its build script's `links` metadata), so tests that need +//! the Cortex journal are reported IGNORED in a stub build instead of passing +//! vacuously. +fn main() { + println!("cargo:rustc-check-cfg=cfg(compose_linked)"); + println!("cargo:rerun-if-env-changed=DEP_RX_COMPOSE_LINKED"); + if std::env::var("DEP_RX_COMPOSE_LINKED").as_deref() == Ok("1") { + println!("cargo:rustc-cfg=compose_linked"); + } +} diff --git a/crates/aien-runtime/src/approved.rs b/crates/aien-runtime/src/approved.rs index fdc377be..2be161c0 100644 --- a/crates/aien-runtime/src/approved.rs +++ b/crates/aien-runtime/src/approved.rs @@ -20,15 +20,27 @@ //! (`filename: \n`), the value `aien compose authorize` puts //! in the authorization grant and `ComposeEffectIntent` must repeat. //! +//! Authentication (#249 A, crate::approved_auth): `approval_mac` must be the +//! approval desk key's HMAC over every approved field, else `Unauthenticated`. +//! Replay (#249 B, crate::approved_replay): the approval is claimed durably +//! in the Cortex journal before the run and settled after it (committed, +//! failed, uncertain); a claimed request id, approval id or approval key is +//! refused for ever, across restarts. +//! //! Design note: docs/COMPOSE_PROPOSER_HOOK.md. +use crate::approved_auth::{ + approval_key, check_confinement, desk_key_path, ApprovalIdentity, DeskKey, +}; +use crate::approved_replay::{self, ClaimKeys, CommitEvidence}; use crate::control::ComposeTaskReport; +use crate::effects::{write_approved_grant, ApprovedLink}; use crate::spine::{check_file_proposal, ComposeBridge}; use aien_omega_compose::hex; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; -use std::collections::HashSet; -use std::sync::{Arc, Mutex}; +use std::path::Path; +use std::sync::Arc; /// Prefix of every hook refusal. pub const REFUSED: &str = "PROPOSAL_REFUSED"; @@ -50,11 +62,20 @@ pub struct ApprovedProposal { pub approved_proposal_sha256: String, /// sha256 of `content`. pub content_sha256: String, + /// HMAC-SHA256 (hex) of the approval binding under the approval desk key + /// (crate::approved_auth). Never caller text: only the desk key holder + /// can make it. + pub approval_mac: String, } /// What a committed approved proposal hands to the effect ledger. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ApprovedComposeReport { + /// "COMMITTED" (this submission ran and the World committed it) or + /// "ALREADY_COMMITTED" (a retry of the same authenticated approval whose + /// first response was lost: nothing ran again, `task` is None and the + /// evidence is the original run's, read from the replay ledger). + pub state: String, pub request_id: String, pub trace_id: String, pub approval_id: String, @@ -68,8 +89,62 @@ pub struct ApprovedComposeReport { /// Links the authorization grant carries, as `aien compose authorize` /// does: [cx_promotion, cx_evidence]. pub grant_links: Vec, - /// The compose run (J-Space branch, AEGIS verdict, World commit records). - pub task: ComposeTaskReport, + /// The desk key that authenticated the approval (its id, never the key). + pub desk_key_id: String, + /// The durable replay key (crate::approved_auth::approval_key). + pub approval_key: String, + /// The replay claim (its `accepted` record id in the Cortex journal). + pub replay_claim: u64, + /// The compose run (J-Space branch, AEGIS verdict, World commit records); + /// None for ALREADY_COMMITTED. + pub task: Option, + /// The authorization grant the daemon wrote for this approval (reserved + /// `approved_grant` record, keyed on `compose_proposal_sha256`, linked to + /// promotion, evidence and the replay claim). The effect intent names it; + /// a caller never writes its own. None for ALREADY_COMMITTED. + #[serde(default)] + pub approved_grant: Option, + /// The grant's absolute target (`/`). + #[serde(default)] + pub target: Option, +} + +/// A refusal of the approved-proposal command, with the correlation ids. +/// `refused_by` is "PROPOSAL_REFUSED" (checks before or around the run) or +/// "REPLAY_REFUSED" (crate::approved_replay); `name` is the refusal name. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApprovedRefusal { + pub refused_by: String, + pub name: String, + pub detail: String, + pub request_id: String, + pub trace_id: String, + pub approval_id: String, + /// The replay claim the refusal concerns, when there is one. + pub replay_claim: Option, +} + +impl std::fmt::Display for ApprovedRefusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} {}: {}", self.refused_by, self.name, self.detail) + } +} + +impl ApprovedRefusal { + /// From a " : detail" text. + fn from_text(p: &ApprovedProposal, text: &str, claim: Option) -> Box { + let (head, detail) = text.split_once(": ").unwrap_or((text, "")); + let (by, name) = head.split_once(' ').unwrap_or((REFUSED, head)); + Box::new(Self { + refused_by: by.to_string(), + name: name.to_string(), + detail: detail.to_string(), + request_id: p.request_id.clone(), + trace_id: p.trace_id.clone(), + approval_id: p.approval_id.clone(), + replay_claim: claim, + }) + } } fn sha256_hex(b: &[u8]) -> String { @@ -132,59 +207,81 @@ pub fn verify(p: &ApprovedProposal) -> Result { proposal_text(&p.path, &p.content) } -/// The hook over one compose bridge (the daemon's, or a test's). +/// The hook over one compose bridge (the daemon's, or a test's). Replay +/// state lives only in the bridge's Cortex journal (crate::approved_replay): +/// two hooks over one compose home, or a restarted daemon, see the same claims. pub struct ProposerHook { bridge: Arc, - /// Request and approval ids already submitted by this process. - consumed: Mutex>, } impl ProposerHook { pub fn new(bridge: Arc) -> Self { - Self { - bridge, - consumed: Mutex::new(HashSet::new()), - } + Self { bridge } } - /// Blocking (runs the composition). Verify, refuse duplicates, run, and - /// return the commit only if the World committed exactly this proposal. + /// Blocking (runs the composition). Order: verify (hashes, template) -> + /// start-up reconcile gate -> desk key (file rules) -> confinement -> + /// authenticate (MAC) -> durable claim -> in_flight -> one compose run -> + /// committed | failed | uncertain. Nothing runs unless every step before + /// it passed; nothing before the claim writes a record. pub fn submit( &self, p: &ApprovedProposal, workspace: &str, - ) -> Result { - let text = verify(p)?; - { - let mut seen = self - .consumed - .lock() - .map_err(|_| refuse("Internal", "replay set lock poisoned"))?; - let keys = [ - format!("request:{}", p.request_id), - format!("approval:{}", p.approval_id), - ]; - if let Some(k) = keys.iter().find(|k| seen.contains(*k)) { - return Err(refuse("Duplicate", format!("{k} was already submitted"))); - } - // Consumed before the run: a failed run never frees the approval. - for k in keys { - seen.insert(k); - } + ) -> Result> { + let refusal = |t: String, c: Option| ApprovedRefusal::from_text(p, &t, c); + let text = verify(p).map_err(|e| refusal(e, None))?; + if let Some(why) = self.bridge.reconcile_failed() { + return Err(refusal( + refuse( + "ReconcileFailed", + format!("the start-up reconcile did not complete ({why}); run aien compose reconcile"), + ), + None, + )); } - // The goal names the path, so an existing file is an edit target here as - // in RunComposeTask; the approved branch of the Skill ignores it (edit = - // None), see spine.rs. + let identity = (|| { + let desk = DeskKey::load(&desk_key_path(self.bridge.dir()))?; + check_confinement(self.bridge.dir(), Path::new(workspace))?; + desk.authenticate(p, Path::new(workspace)) + })() + .map_err(|e| refusal(e, None))?; + let keys = ClaimKeys { + approval_key: approval_key(&identity), + request_id: p.request_id.clone(), + approval_id: p.approval_id.clone(), + trace_id: p.trace_id.clone(), + }; + let claim = match approved_replay::claim(&self.bridge, &keys) { + Ok(c) => c, + Err(r) => return self.replayed(p, &identity, &keys, r), + }; + crash_point("approved_after_claim"); + let rr = |r: approved_replay::Refusal| refusal(r.to_string(), Some(claim.id)); + approved_replay::mark_in_flight(&self.bridge, &claim).map_err(|e| { + // Nothing ran; end the claim as not_executed if the journal lets us. + let _ = approved_replay::not_executed(&self.bridge, &claim, &e.to_string()); + rr(e) + })?; + // Exactly one compose run per claim. let goal = format!( "apply approved proposal for {} (request {})", p.path, p.request_id ); - let r = self + let r = match self .bridge - .run_approved_task(&goal, workspace, &text) - .map_err(|e| refuse("ComposeError", e))?; + .run_approved_task(&goal, &identity.workspace, &text) + { + Ok(r) => r, + Err(e) => { + // The run may have reached the World: never guess. + let why = refuse("ComposeError", &e); + approved_replay::uncertain(&self.bridge, &claim, &why).map_err(rr)?; + return Err(refusal(why, Some(claim.id))); + } + }; if !r.committed { - return Err(refuse( + let why = refuse( "NotCommitted", format!( "outcome {} (AEGIS pass mask {:#x}); {}", @@ -192,7 +289,9 @@ impl ProposerHook { r.aegis_pass_mask, r.proposer_error.as_deref().unwrap_or("no proposer error") ), - )); + ); + approved_replay::fail(&self.bridge, &claim, &why).map_err(rr)?; + return Err(refusal(why, Some(claim.id))); } let compose_sha = sha256_hex(text.as_bytes()); if r.proposal.as_deref() != Some(text.as_str()) @@ -200,12 +299,126 @@ impl ProposerHook { || r.proposal_path.as_deref() != Some(p.path.as_str()) || r.proposal_content_sha256.as_deref() != Some(p.content_sha256.as_str()) { - return Err(refuse( + let why = refuse( "Mismatch", - "the committed proposal is not the approved one", - )); + format!( + "the World committed task {} (promotion #{}) but not the approved proposal", + r.task, r.cx_promotion + ), + ); + approved_replay::uncertain(&self.bridge, &claim, &why).map_err(rr)?; + return Err(refusal(why, Some(claim.id))); + } + let evidence = CommitEvidence { + compose_proposal_sha256: compose_sha.clone(), + cx_promotion: r.cx_promotion, + cx_evidence: r.cx_evidence, + task: r.task, + }; + crash_point("approved_after_compose"); + // If this append fails the claim stays in_flight: refused forever, + // UNCERTAIN after a restart (fail closed). + approved_replay::commit(&self.bridge, &claim, &evidence).map_err(rr)?; + crash_point("approved_after_commit"); + // The one grant for this approval, written by the daemon (never by the + // caller). If it cannot be written the approval stays spent and no + // effect is possible: a new approval is needed (fail closed). + // The grant's target comes from the bound (MAC-covered) workspace only. + let link = ApprovedLink { + approval_key: keys.approval_key.clone(), + replay_claim: claim.id, + cx_promotion: evidence.cx_promotion, + cx_evidence: evidence.cx_evidence, + }; + let ids = serde_json::json!({"request_id": p.request_id, "trace_id": p.trace_id, + "approval_id": p.approval_id, "desk_key_id": identity.desk_key_id, + "approved_proposal_sha256": p.approved_proposal_sha256}); + let (grant, target) = write_approved_grant( + &self.bridge, + &identity.workspace, + &p.path, + &p.content_sha256, + &p.approver, + &ids, + &link, + &compose_sha, + ) + .map_err(|e| { + refusal( + refuse( + "GrantNotWritten", + format!("the approval is committed and spent; no effect is possible: {e}"), + ), + Some(claim.id), + ) + })?; + let mut out = self.report( + p, + &identity, + &keys, + claim.id, + "COMMITTED", + &evidence, + Some(r), + ); + out.approved_grant = Some(grant); + out.target = Some(target); + Ok(out) + } + + /// A claim refusal. A retry of the very same authenticated approval (all + /// keys equal) whose claim committed gets the original result back as + /// ALREADY_COMMITTED; everything else is refused with the claim's state. + fn replayed( + &self, + p: &ApprovedProposal, + identity: &ApprovalIdentity, + keys: &ClaimKeys, + r: approved_replay::Refusal, + ) -> Result> { + if r.name == "AlreadyCommitted" { + if let (Some(id), Some(ev)) = (r.claim, r.evidence.as_ref()) { + if self.claim_keys(id).as_ref() == Ok(keys) { + return Ok(self.report(p, identity, keys, id, "ALREADY_COMMITTED", ev, None)); + } + } } - Ok(ApprovedComposeReport { + Err(ApprovedRefusal::from_text(p, &r.to_string(), r.claim)) + } + + /// The keys a claim recorded, read back from the journal. + fn claim_keys(&self, id: u64) -> Result { + self.bridge.with_home(|home| { + let (recs, _) = home + .compose + .recall(aien_omega_compose::SUBJECT_HOST, 4096) + .map_err(|e| format!("host records: {e}"))?; + let views: Vec<_> = recs + .iter() + .map(|r| crate::spine::record_view(&mut home.compose, r)) + .collect(); + let l = + approved_replay::ReplayLedger::from_records(&views).map_err(|e| e.to_string())?; + l.claims + .get(&id) + .map(|row| row.keys.clone()) + .ok_or_else(|| format!("#{id} is not a claim")) + }) + } + + #[allow(clippy::too_many_arguments)] + fn report( + &self, + p: &ApprovedProposal, + identity: &ApprovalIdentity, + keys: &ClaimKeys, + claim: u64, + state: &str, + ev: &CommitEvidence, + task: Option, + ) -> ApprovedComposeReport { + ApprovedComposeReport { + state: state.into(), request_id: p.request_id.clone(), trace_id: p.trace_id.clone(), approval_id: p.approval_id.clone(), @@ -213,9 +426,28 @@ impl ProposerHook { path: p.path.clone(), content_sha256: p.content_sha256.clone(), approved_proposal_sha256: p.approved_proposal_sha256.clone(), - compose_proposal_sha256: compose_sha, - grant_links: vec![r.cx_promotion, r.cx_evidence], - task: r, - }) + compose_proposal_sha256: ev.compose_proposal_sha256.clone(), + grant_links: vec![ev.cx_promotion, ev.cx_evidence], + desk_key_id: identity.desk_key_id.clone(), + approval_key: keys.approval_key.clone(), + replay_claim: claim, + task, + approved_grant: None, + target: None, + } + } +} + +/// Test builds only (cargo feature `fault-hold`): abort the process at the +/// named point when `AIEN_FAULT_HOLD` names it, to prove the crash +/// boundaries of #249 B. The default build compiles this to nothing. +#[cfg(feature = "fault-hold")] +fn crash_point(name: &str) { + if std::env::var("AIEN_FAULT_HOLD").as_deref() == Ok(name) { + eprintln!("fault hold {name}: aborting (test build)"); + std::process::abort(); } } + +#[cfg(not(feature = "fault-hold"))] +fn crash_point(_: &str) {} diff --git a/crates/aien-runtime/src/approved_auth.rs b/crates/aien-runtime/src/approved_auth.rs new file mode 100644 index 00000000..77bb7a41 --- /dev/null +++ b/crates/aien-runtime/src/approved_auth.rs @@ -0,0 +1,406 @@ +//! Approval authentication for the proposer hook (#249, part A). +//! +//! An [`crate::approved::ApprovedProposal`] carries `approval_mac`: an +//! HMAC-SHA256, keyed by the approval desk key, over the canonical binding of +//! every field the approval covers ([`ApprovalIdentity`]). The daemon holds +//! the same key (`/approval-desk.key`) and recomputes the MAC; +//! any field the caller changes (trace, request, approval id, approver, path, +//! content, approved proposal digest) or a MAC made with another key is +//! refused `PROPOSAL_REFUSED Unauthenticated`. +//! +//! What the MAC proves: the holder of the desk key approved exactly these +//! fields. It does not prove which human pressed approve; the desk (the +//! INTERPLANE host's approval continuation, host-only) names the approver and +//! the MAC stops anyone without the key from changing that name. Caller text +//! (model output, tool arguments, request JSON) is never approval: it cannot +//! carry a valid MAC without the key. +//! +//! Why a key and not the existing operator `authorization` grant: grant +//! records are `ComposeNote`s any same-user socket caller can append, so +//! "bound to a grant" would be caller text in two steps; the aien-mcp +//! `ApprovalGrant` lives in the INTERPLANE process memory and the daemon +//! cannot check it. The key is the smallest thing that separates "the desk +//! approved" from "the caller says it was approved". +//! +//! Key rules (checked on every load, so a replaced key takes effect at once): +//! a regular file (never a symlink, opened `O_NOFOLLOW`), owned by this +//! process's effective uid, no group or other permission bits, 64 hex digits. +//! The key is never printed, logged, recorded or reported; only +//! [`DeskKey::id`] (first 16 hex digits of sha256 of the key) is. +//! The compose home must not overlap the workspace the proposal targets (the +//! model-facing tools read inside the workspace), else `Confinement`. +//! +//! Rotation: replacing the key file makes every MAC made with the old key +//! fail (`Unauthenticated`), including approvals issued but not yet +//! submitted; the desk must approve again. Records already written keep the +//! old `desk_key_id`. Loss of the key: the daemon refuses every approved +//! proposal (`NoDesk`) until an operator creates a new one +//! (`aien compose desk-key`). +//! +//! Limit: the OS user stays the outer boundary. A process running as the +//! daemon's user that can read the compose home can read the key. +use aien_omega_compose::hex; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +/// Version tag inside every binding. +pub const APPROVAL_BINDING_VERSION: &str = "aien.approval.v2"; +/// File name of the desk key inside the compose home. +pub const DESK_KEY_FILE: &str = "approval-desk.key"; + +const REFUSED: &str = crate::approved::REFUSED; + +fn refuse(name: &str, why: impl std::fmt::Display) -> String { + format!("{REFUSED} {name}: {why}") +} + +/// The fields one approval covers. `desk_key_id` names the key that +/// authenticated it; it is not caller input (the daemon fills it from the key +/// it holds). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovalIdentity { + pub trace_id: String, + pub request_id: String, + pub approval_id: String, + pub approver: String, + pub path: String, + pub content_sha256: String, + pub approved_proposal_sha256: String, + pub desk_key_id: String, + /// The canonical absolute workspace the approval is for (476ca4 c17): the + /// effect can land only here. The daemon canonicalises the submitted + /// workspace and binds that, so a valid approval presented with another + /// workspace fails the MAC (Unauthenticated, nothing consumed). + pub workspace: String, +} + +impl ApprovalIdentity { + /// The identity of `p` for the canonical `workspace` under the desk key + /// `desk_key_id`. + pub fn of(p: &crate::approved::ApprovedProposal, workspace: &str, desk_key_id: &str) -> Self { + Self { + trace_id: p.trace_id.clone(), + request_id: p.request_id.clone(), + approval_id: p.approval_id.clone(), + approver: p.approver.clone(), + path: p.path.clone(), + content_sha256: p.content_sha256.clone(), + approved_proposal_sha256: p.approved_proposal_sha256.clone(), + desk_key_id: desk_key_id.to_string(), + workspace: workspace.to_string(), + } + } +} + +/// The canonical absolute workspace path (symlinks resolved), as bound. +pub fn canonical_workspace(workspace: &Path) -> Result { + let c = std::fs::canonicalize(workspace) + .map_err(|e| format!("workspace {}: {e}", workspace.display()))?; + c.to_str() + .map(str::to_string) + .ok_or_else(|| format!("workspace {} is not UTF-8", c.display())) +} + +/// Canonical binding: compact JSON, keys in sorted order, of the nine +/// identity fields plus `"v": APPROVAL_BINDING_VERSION`. +pub fn binding_bytes(id: &ApprovalIdentity) -> Vec { + // serde_json's Map is a BTreeMap here (no preserve_order feature), so + // keys serialize sorted; inserted sorted anyway. + let mut m = Map::new(); + for (k, v) in [ + ("approval_id", &id.approval_id), + ("approved_proposal_sha256", &id.approved_proposal_sha256), + ("approver", &id.approver), + ("content_sha256", &id.content_sha256), + ("desk_key_id", &id.desk_key_id), + ("path", &id.path), + ("request_id", &id.request_id), + ("trace_id", &id.trace_id), + ("workspace", &id.workspace), + ] { + m.insert(k.into(), Value::String(v.clone())); + } + m.insert("v".into(), Value::String(APPROVAL_BINDING_VERSION.into())); + Value::Object(m).to_string().into_bytes() +} + +/// The durable replay key of an approval: sha256 (hex) of its binding. +pub fn approval_key(id: &ApprovalIdentity) -> String { + hex(&Sha256::digest(binding_bytes(id))) +} + +/// HMAC-SHA256 (RFC 2104) over sha2; no extra dependency. +pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] { + const B: usize = 64; + let mut k = [0u8; B]; + if key.len() > B { + k[..32].copy_from_slice(&Sha256::digest(key)); + } else { + k[..key.len()].copy_from_slice(key); + } + let mut ipad = [0x36u8; B]; + let mut opad = [0x5cu8; B]; + for i in 0..B { + ipad[i] ^= k[i]; + opad[i] ^= k[i]; + } + let inner = Sha256::new() + .chain_update(ipad) + .chain_update(msg) + .finalize(); + let out = Sha256::new() + .chain_update(opad) + .chain_update(inner) + .finalize(); + let mut r = [0u8; 32]; + r.copy_from_slice(&out); + r +} + +/// Equal length and equal bytes, without an early exit. +fn ct_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn unhex32(s: &str) -> Option<[u8; 32]> { + let s = s.trim_end_matches('\n'); + // Canonical form only: 64 lowercase hex digits. + if s.len() != 64 + || !s + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return None; + } + let mut out = [0u8; 32]; + for (i, o) in out.iter_mut().enumerate() { + *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; + } + Some(out) +} + +/// Path of the desk key in a compose home. +pub fn desk_key_path(compose_dir: &Path) -> PathBuf { + compose_dir.join(DESK_KEY_FILE) +} + +/// The approval desk key. `Debug` shows only the id; the bytes are zeroed on drop. +pub struct DeskKey { + key: [u8; 32], + id: String, +} + +impl std::fmt::Debug for DeskKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "DeskKey {{ id: {} }}", self.id) + } +} + +impl Drop for DeskKey { + fn drop(&mut self) { + for b in self.key.iter_mut() { + // SAFETY: a valid, aligned &mut u8. + unsafe { std::ptr::write_volatile(b, 0) }; + } + } +} + +fn euid() -> u32 { + // SAFETY: geteuid has no preconditions and cannot fail. + unsafe { libc::geteuid() } +} + +impl DeskKey { + fn from_bytes(key: [u8; 32]) -> Self { + let id = hex(&Sha256::digest(key))[..16].to_string(); + Self { key, id } + } + + /// Load and check the key file (see the module rules). Errors are + /// `PROPOSAL_REFUSED NoDesk: ...` and never contain key bytes. + pub fn load(path: &Path) -> Result { + let nodesk = |why: String| refuse("NoDesk", format!("{}: {why}", path.display())); + let lmeta = std::fs::symlink_metadata(path).map_err(|e| nodesk(e.to_string()))?; + if lmeta.file_type().is_symlink() { + return Err(nodesk("is a symlink".into())); + } + let f = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .map_err(|e| nodesk(e.to_string()))?; + // Checks on the opened file, not the path (no swap in between). + let m = f.metadata().map_err(|e| nodesk(e.to_string()))?; + if !m.file_type().is_file() { + return Err(nodesk("not a regular file".into())); + } + if m.uid() != euid() { + return Err(nodesk(format!( + "owned by uid {}, not this process's uid {}", + m.uid(), + euid() + ))); + } + if m.mode() & 0o077 != 0 { + return Err(nodesk(format!( + "mode {:o} gives group or other access (must be 0600 or stricter)", + m.mode() & 0o777 + ))); + } + let mut s = String::new(); + f.take(256) + .read_to_string(&mut s) + .map_err(|e| nodesk(e.to_string()))?; + let key = unhex32(&s).ok_or_else(|| nodesk("not 64 hex digits".into()))?; + s.replace_range(.., &"0".repeat(s.len())); + Ok(Self::from_bytes(key)) + } + + /// Create a new key file (exclusive create, mode 0600, `O_NOFOLLOW`) from + /// /dev/urandom. Refuses when the file exists: rotation is delete + create + /// by the operator, never an overwrite here. + pub fn create(path: &Path) -> Result { + let mut key = [0u8; 32]; + std::fs::File::open("/dev/urandom") + .and_then(|mut r| r.read_exact(&mut key)) + .map_err(|e| format!("desk key: /dev/urandom: {e}"))?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("desk key: {}: {e}", parent.display()))?; + } + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .map_err(|e| format!("desk key: create {}: {e}", path.display()))?; + // umask can only remove bits; set 0600 explicitly anyway. + f.set_permissions(std::fs::Permissions::from_mode(0o600)) + .and_then(|_| f.write_all(format!("{}\n", hex(&key)).as_bytes())) + .and_then(|_| f.sync_all()) + .map_err(|e| format!("desk key: write {}: {e}", path.display()))?; + Ok(Self::from_bytes(key)) + } + + /// First 16 hex digits of sha256(key): names the key, reveals nothing usable. + pub fn id(&self) -> &str { + &self.id + } + + /// The MAC (hex) the desk attaches to `id`'s binding. + pub fn mac(&self, id: &ApprovalIdentity) -> String { + hex(&hmac_sha256(&self.key, &binding_bytes(id))) + } + + /// Desk side: the MAC for a proposal under this key, for `workspace` + /// (canonicalised here as the daemon will). + pub fn sign(&self, p: &crate::approved::ApprovedProposal, workspace: &Path) -> String { + let ws = canonical_workspace(workspace).unwrap_or_else(|_| workspace.display().to_string()); + self.mac(&ApprovalIdentity::of(p, &ws, &self.id)) + } + + /// Daemon side: Ok(identity) only when `p.approval_mac` is this key's MAC + /// over `p`'s binding; else `PROPOSAL_REFUSED Unauthenticated`. + pub fn authenticate( + &self, + p: &crate::approved::ApprovedProposal, + workspace: &Path, + ) -> Result { + let ws = canonical_workspace(workspace).map_err(|e| refuse("Unauthenticated", e))?; + let id = ApprovalIdentity::of(p, &ws, &self.id); + let want = hmac_sha256(&self.key, &binding_bytes(&id)); + let got = unhex32(&p.approval_mac); + match got { + Some(g) if ct_eq(&g, &want) => Ok(id), + _ => Err(refuse( + "Unauthenticated", + format!( + "approval_mac is not the approval desk's (key {}) MAC over these fields", + self.id + ), + )), + } + } +} + +/// Refuse when the compose home and the workspace overlap (either inside the +/// other): the model-facing tools read inside the workspace, and the desk key +/// and the journal must stay out of their reach. +pub fn check_confinement(compose_dir: &Path, workspace: &Path) -> Result<(), String> { + let c = std::fs::canonicalize(compose_dir).map_err(|e| { + refuse( + "Confinement", + format!("compose home {}: {e}", compose_dir.display()), + ) + })?; + let w = std::fs::canonicalize(workspace).map_err(|e| { + refuse( + "Confinement", + format!("workspace {}: {e}", workspace.display()), + ) + })?; + if c.starts_with(&w) || w.starts_with(&c) { + return Err(refuse( + "Confinement", + format!( + "compose home {} and workspace {} overlap; the approval desk refuses to run", + c.display(), + w.display() + ), + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hmac_matches_rfc4231_case_2() { + // RFC 4231 test case 2. + let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?"); + assert_eq!( + hex(&mac), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + } + + #[test] + fn binding_is_sorted_compact_json() { + let id = ApprovalIdentity { + trace_id: "t".into(), + request_id: "r".into(), + approval_id: "a".into(), + approver: "p".into(), + path: "N.md".into(), + content_sha256: "c".into(), + approved_proposal_sha256: "s".into(), + desk_key_id: "k".into(), + workspace: "/w".into(), + }; + assert_eq!( + String::from_utf8(binding_bytes(&id)).unwrap(), + r#"{"approval_id":"a","approved_proposal_sha256":"s","approver":"p","content_sha256":"c","desk_key_id":"k","path":"N.md","request_id":"r","trace_id":"t","v":"aien.approval.v2","workspace":"/w"}"# + ); + } + + #[test] + fn ct_eq_and_unhex() { + assert!(ct_eq(b"ab", b"ab")); + assert!(!ct_eq(b"ab", b"ac")); + assert!(!ct_eq(b"ab", b"abc")); + assert!(unhex32(&"0".repeat(63)).is_none()); + assert!(unhex32(&"zz".repeat(32)).is_none()); + assert_eq!(unhex32(&"ff".repeat(32)), Some([0xff; 32])); + assert!(unhex32(&"FF".repeat(32)).is_none()); + assert!(unhex32(&format!(" {}", "f".repeat(63))).is_none()); + } +} diff --git a/crates/aien-runtime/src/approved_replay.rs b/crates/aien-runtime/src/approved_replay.rs new file mode 100644 index 00000000..93bb95bb --- /dev/null +++ b/crates/aien-runtime/src/approved_replay.rs @@ -0,0 +1,558 @@ +//! Restart-safe replay protection for approved proposals (sovereign-core #249, part B). +//! +//! Every approved submission is claimed in the compose home's Cortex journal +//! BEFORE anything runs, and its lifecycle is written there as host records of +//! kind `effect` with an `approved_submission` field (never a `phase`, so the +//! effect ledger of crate::effects ignores them; ComposeNote cannot forge them, +//! see effects::check_reserved_note): +//! +//! accepted the claim: approval key, request id, approval id, trace id, +//! the claiming process (pid + start ticks). Durable before return. +//! in_flight written immediately before the compose run starts +//! committed the run committed exactly the approved proposal (evidence kept) +//! failed the run returned and reported that the World did not commit +//! not_executed the claim ended before any run started (refusal after the +//! claim, or a crash between accepted and in_flight) +//! uncertain the run may have changed the World but completion is not +//! proven (run error, committed-but-mismatch, crash in flight) +//! declared an operator settled an uncertain claim (what the operator saw); +//! it changes the reported state only +//! +//! Invariant: a claim key (approval key, request id, approval id; each on its +//! own) is accepted at most once, ever. Every later submission naming any of +//! them is refused with the claim's state, whatever that state is: an approval +//! is single-use even when its run never started, so no interrupted state is +//! ever guessed into a second run. A retry after a lost response gets the +//! committed evidence back in the refusal (`AlreadyCommitted`). +//! +//! Atomicity: the ledger is rebuilt from the journal under the compose-home +//! lock and the check and the `accepted` append happen in that one locked step +//! (the same pattern as effects::open_intent), so two concurrent submissions +//! cannot both be accepted. The journal is opened with CX_OPEN_SYNC: an +//! appended record is durable when `note` returns. +//! +//! The approval identity and its canonical key belong to crate::approved_auth +//! (`ApprovalIdentity`, `approval_key`); this module never recomputes them. It +//! takes the key and the two ids from the caller ([`ClaimKeys`]). +//! +//! Limits: the ledger reads at most HOST_RECALL_MAX host records in one recall +//! and refuses (fails closed) beyond that; liveness of a claiming process is +//! pid + start ticks (effects::executor_alive). +use crate::control::ComposeRecordView; +use crate::effects::{executor_alive, self_executor}; +use crate::spine::{record_view, ComposeBridge, ComposeHome}; +use aien_omega_compose::NoteKind; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fmt; + +/// The JSON field that marks a replay record (reserved against ComposeNote). +pub const FIELD: &str = "approved_submission"; +const HOST_RECALL_MAX: u32 = 4096; + +/// The keys one submission claims, taken from the authenticated identity. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClaimKeys { + /// `approved_auth::approval_key(&identity)`: sha256 hex of the binding. + pub approval_key: String, + pub request_id: String, + pub approval_id: String, + /// Correlation only; not a claim key. + pub trace_id: String, +} + +impl ClaimKeys { + fn keys(&self) -> [String; 3] { + [ + format!("key:{}", self.approval_key), + format!("request:{}", self.request_id), + format!("approval:{}", self.approval_id), + ] + } + fn check(&self) -> Result<(), Refusal> { + let k = &self.approval_key; + if k.len() != 64 + || !k + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return Err(Refusal::new( + "BadKey", + "approval_key is not 64 lowercase hex", + )); + } + if self.request_id.is_empty() || self.approval_id.is_empty() { + return Err(Refusal::new("BadKey", "empty request_id or approval_id")); + } + Ok(()) + } +} + +/// What a committed run left behind (returned again on a retry). +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct CommitEvidence { + pub compose_proposal_sha256: String, + pub cx_promotion: u64, + pub cx_evidence: u64, + pub task: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClaimState { + Accepted, + InFlight, + Committed, + Failed, + NotExecuted, + Uncertain, +} + +impl ClaimState { + pub fn name(self) -> &'static str { + match self { + Self::Accepted => "ACCEPTED", + Self::InFlight => "IN_FLIGHT", + Self::Committed => "COMMITTED", + Self::Failed => "FAILED", + Self::NotExecuted => "NOT_EXECUTED", + Self::Uncertain => "UNCERTAIN", + } + } + pub fn terminal(self) -> bool { + !matches!(self, Self::Accepted | Self::InFlight) + } +} + +/// A named refusal: `REPLAY_REFUSED : ...`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + pub name: &'static str, + pub detail: String, + /// The existing claim the refusal is about, when there is one. + pub claim: Option, + /// Set for AlreadyCommitted: the original result, for a caller whose + /// response was lost. + pub evidence: Option, +} + +impl Refusal { + fn new(name: &'static str, detail: impl Into) -> Self { + Self { + name, + detail: detail.into(), + claim: None, + evidence: None, + } + } +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "REPLAY_REFUSED {}: {}", self.name, self.detail) + } +} + +/// A claim this process holds (the `accepted` record id). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Claim { + pub id: u64, +} + +/// One claim as the ledger reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClaimRow { + pub id: u64, + pub keys: ClaimKeys, + pub executor_pid: u32, + pub executor_start: u64, + pub state: ClaimState, + /// The record that set `state` (the claim itself while ACCEPTED). + pub state_record: u64, + pub evidence: Option, + pub reason: Option, + /// Operator declaration on an UNCERTAIN claim: (record, "committed" | "not_committed"). + pub declared: Option<(u64, String)>, +} + +/// The replay ledger, rebuilt from the journal's host records. +#[derive(Debug, Default)] +pub struct ReplayLedger { + pub claims: BTreeMap, + /// claim key -> claim id + index: BTreeMap, +} + +fn corrupt(id: u64, why: impl Into) -> Refusal { + Refusal::new("CorruptLedger", format!("record #{id}: {}", why.into())) +} +fn s(v: &Value, k: &str, id: u64) -> Result { + v.get(k) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| corrupt(id, format!("missing {k}"))) +} +fn u(v: &Value, k: &str, id: u64) -> Result { + v.get(k) + .and_then(Value::as_u64) + .ok_or_else(|| corrupt(id, format!("missing {k}"))) +} + +impl ReplayLedger { + pub fn from_records(host: &[ComposeRecordView]) -> Result { + let mut l = Self::default(); + for r in host { + if !r.verified { + return Err(corrupt(r.id, "digest does not verify")); + } + if r.note.as_deref() != Some("effect") { + continue; + } + let Some(text) = r.text.as_deref() else { + continue; + }; + let Ok(v) = serde_json::from_str::(text) else { + continue; + }; + let Some(phase) = v.get(FIELD) else { continue }; + let phase = phase + .as_str() + .ok_or_else(|| corrupt(r.id, "phase is not a string"))?; + l.read(r.id, phase, &v)?; + } + Ok(l) + } + + fn read(&mut self, id: u64, phase: &str, v: &Value) -> Result<(), Refusal> { + if phase == "accepted" { + let keys = ClaimKeys { + approval_key: s(v, "approval_key", id)?, + request_id: s(v, "request_id", id)?, + approval_id: s(v, "approval_id", id)?, + trace_id: s(v, "trace_id", id)?, + }; + for k in keys.keys() { + if let Some(prev) = self.index.insert(k.clone(), id) { + return Err(corrupt(id, format!("{k} already claimed by #{prev}"))); + } + } + let ex = v.get("executor").cloned().unwrap_or(Value::Null); + self.claims.insert( + id, + ClaimRow { + id, + keys, + executor_pid: u(&ex, "pid", id)? as u32, + executor_start: u(&ex, "start", id)?, + state: ClaimState::Accepted, + state_record: id, + evidence: None, + reason: None, + declared: None, + }, + ); + return Ok(()); + } + let c = u(v, "claim", id)?; + let row = self + .claims + .get_mut(&c) + .ok_or_else(|| corrupt(id, format!("names claim #{c}, which is not one")))?; + let reason = v.get("reason").and_then(Value::as_str).map(str::to_string); + // Allowed transitions; anything else is a corrupt ledger (fail closed). + let next = match (phase, row.state) { + ("in_flight", ClaimState::Accepted) => ClaimState::InFlight, + ("committed", ClaimState::InFlight) => ClaimState::Committed, + ("failed", ClaimState::InFlight) => ClaimState::Failed, + ("uncertain", ClaimState::InFlight) => ClaimState::Uncertain, + ("not_executed", ClaimState::Accepted) => ClaimState::NotExecuted, + ("declared", ClaimState::Uncertain) => { + if row.declared.is_some() { + return Err(corrupt(id, format!("claim #{c} declared twice"))); + } + let d = s(v, "declared", id)?; + if d != "committed" && d != "not_committed" { + return Err(corrupt( + id, + "declared is neither committed nor not_committed", + )); + } + row.declared = Some((id, d)); + return Ok(()); + } + (p, st) => { + return Err(corrupt( + id, + format!("{p} after {} on claim #{c}", st.name()), + )); + } + }; + if next == ClaimState::Committed { + let e = v.get("evidence").cloned().unwrap_or(Value::Null); + row.evidence = + Some(serde_json::from_value(e).map_err(|e| corrupt(id, format!("evidence: {e}")))?); + } + row.state = next; + row.state_record = id; + row.reason = reason; + Ok(()) + } + + /// The existing claim on any of these keys, if one exists. + pub fn find(&self, keys: &ClaimKeys) -> Option<&ClaimRow> { + keys.keys() + .iter() + .find_map(|k| self.index.get(k)) + .and_then(|id| self.claims.get(id)) + } + + /// Why a new claim on `keys` is refused (None: it may be claimed). + pub fn check(&self, keys: &ClaimKeys) -> Option { + let row = self.find(keys)?; + let alive = executor_alive(row.executor_pid, row.executor_start); + let (name, what): (&'static str, String) = match row.state { + ClaimState::Committed => ("AlreadyCommitted", "committed; the original result is attached".into()), + ClaimState::Failed => ("AlreadyFailed", "ran and did not commit; a new approval is needed".into()), + ClaimState::NotExecuted => ("AlreadyConsumed", "claimed, never ran; a new approval is needed".into()), + ClaimState::Uncertain => ("Uncertain", "may have committed; an operator must reconcile it, it is never re-run".into()), + ClaimState::Accepted | ClaimState::InFlight if alive => ("InFlight", format!("{} in a running process", row.state.name())), + // The claiming process is gone and nothing settled the claim yet: + // before in_flight nothing ran; after it, completion is unknown. + ClaimState::Accepted => ("AlreadyConsumed", "claimed by a process that is gone, never ran; a new approval is needed".into()), + ClaimState::InFlight => ("Uncertain", "in flight in a process that is gone; an operator must reconcile it, it is never re-run".into()), + }; + let mut r = Refusal::new( + name, + format!( + "claim #{} (request {}, approval {}, key {}) is {}: {what}", + row.id, + row.keys.request_id, + row.keys.approval_id, + row.keys.approval_key, + row.state.name() + ), + ); + r.claim = Some(row.id); + r.evidence = row.evidence.clone(); + Some(r) + } +} + +fn ledger(home: &mut ComposeHome) -> Result { + let (recs, total) = home + .compose + .recall(aien_omega_compose::SUBJECT_HOST, HOST_RECALL_MAX) + .map_err(|e| Refusal::new("Journal", format!("host records: {e}")))?; + if total > recs.len() as u64 { + return Err(Refusal::new( + "CorruptLedger", + format!("{total} host records exceed the replay ledger's {HOST_RECALL_MAX}"), + )); + } + let views: Vec = recs + .iter() + .map(|r| record_view(&mut home.compose, r)) + .collect(); + ReplayLedger::from_records(&views) +} + +fn append(home: &mut ComposeHome, link: u64, text: &Value) -> Result { + let mut l = [0u64; 4]; + l[0] = link; + home.compose + .note(NoteKind::Effect, l, text.to_string().as_bytes()) + .map_err(|e| Refusal::new("Journal", format!("replay record: {e}"))) +} + +/// Run `f` under the compose-home lock; a lock/open/mark failure is a refusal. +fn locked( + b: &ComposeBridge, + f: impl FnOnce(&mut ComposeHome) -> Result, +) -> Result { + let mut inner: Option = None; + let r = b.with_home(|home| { + f(home).map_err(|e| { + let s = e.to_string(); + inner = Some(e); + s + }) + }); + match r { + Ok(t) => Ok(t), + Err(e) => Err(inner.unwrap_or_else(|| Refusal::new("Journal", e))), + } +} + +/// Claim `keys` for one execution. Durable before it returns. Refused if any +/// key was ever claimed, with that claim's state. +pub fn claim(b: &ComposeBridge, keys: &ClaimKeys) -> Result { + keys.check()?; + locked(b, |home| { + let l = ledger(home)?; + if let Some(r) = l.check(keys) { + return Err(r); + } + let (pid, start) = self_executor(); + if start == 0 { + return Err(Refusal::new( + "Executor", + "cannot read this process's start ticks", + )); + } + let text = json!({ + FIELD: "accepted", + "approval_key": keys.approval_key, "request_id": keys.request_id, + "approval_id": keys.approval_id, "trace_id": keys.trace_id, + "executor": {"pid": pid, "start": start}, + }); + Ok(Claim { + id: append(home, 0, &text)?, + }) + }) +} + +/// Append one lifecycle record after checking the claim is ours and in `from`. +fn step(b: &ComposeBridge, c: &Claim, from: ClaimState, text: Value) -> Result { + locked(b, |home| { + let l = ledger(home)?; + let row = l + .claims + .get(&c.id) + .ok_or_else(|| Refusal::new("NoClaim", format!("#{} is not a claim", c.id)))?; + let (pid, start) = self_executor(); + if (row.executor_pid, row.executor_start) != (pid, start) { + return Err(Refusal::new( + "NotOwner", + format!("claim #{} belongs to another process", c.id), + )); + } + if row.state != from { + return Err(Refusal::new( + "WrongState", + format!( + "claim #{} is {}, expected {}", + c.id, + row.state.name(), + from.name() + ), + )); + } + append(home, c.id, &text) + }) +} + +/// Immediately before the compose run. +pub fn mark_in_flight(b: &ComposeBridge, c: &Claim) -> Result<(), Refusal> { + step( + b, + c, + ClaimState::Accepted, + json!({FIELD: "in_flight", "claim": c.id}), + ) + .map(|_| ()) +} + +/// The run committed exactly the approved proposal. +pub fn commit(b: &ComposeBridge, c: &Claim, e: &CommitEvidence) -> Result<(), Refusal> { + let text = json!({FIELD: "committed", "claim": c.id, "evidence": e}); + step(b, c, ClaimState::InFlight, text).map(|_| ()) +} + +/// The run returned and reported that the World did not commit +/// (`ComposeTaskReport.committed == false`). +pub fn fail(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { + let text = json!({FIELD: "failed", "claim": c.id, "reason": reason}); + step(b, c, ClaimState::InFlight, text).map(|_| ()) +} + +/// The claim ends before the run started (any refusal after `claim`). +pub fn not_executed(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { + let text = json!({FIELD: "not_executed", "claim": c.id, "reason": reason}); + step(b, c, ClaimState::Accepted, text).map(|_| ()) +} + +/// The run may have changed the World and success is not proven: the run +/// returned an error, or committed something other than the approved proposal. +pub fn uncertain(b: &ComposeBridge, c: &Claim, reason: &str) -> Result<(), Refusal> { + let text = json!({FIELD: "uncertain", "claim": c.id, "reason": reason}); + step(b, c, ClaimState::InFlight, text).map(|_| ()) +} + +/// Operator settles an UNCERTAIN claim after looking at the World. The claim +/// stays consumed either way. +pub fn declare( + b: &ComposeBridge, + claim: u64, + committed: bool, + by: &str, + note: &str, +) -> Result { + locked(b, |home| { + let l = ledger(home)?; + let row = l + .claims + .get(&claim) + .ok_or_else(|| Refusal::new("NoClaim", format!("#{claim} is not a claim")))?; + if row.state != ClaimState::Uncertain || row.declared.is_some() { + return Err(Refusal::new( + "WrongState", + format!( + "claim #{claim} is {} (declared: {})", + row.state.name(), + row.declared.is_some() + ), + )); + } + let d = if committed { + "committed" + } else { + "not_committed" + }; + append( + home, + claim, + &json!({FIELD: "declared", "claim": claim, "declared": d, "by": by, "note": note}), + ) + }) +} + +/// Daemon start: settle every claim whose process is gone. ACCEPTED (never +/// ran) -> not_executed; IN_FLIGHT -> uncertain. Nothing is re-run. +pub fn reconcile_at_start(b: &ComposeBridge) -> Result { + if !b.dir().join("cortex.cx").exists() { + return Ok("Replay reconcile: no compose home yet".into()); + } + locked(b, |home| { + let l = ledger(home)?; + let (mut ne, mut un) = (0, 0); + for row in l.claims.values() { + if row.state.terminal() || executor_alive(row.executor_pid, row.executor_start) { + continue; + } + let (phase, why) = match row.state { + ClaimState::Accepted => { + ne += 1; + ( + "not_executed", + "claiming process gone before the run started (reconcile@start)", + ) + } + _ => { + un += 1; + ( + "uncertain", + "claiming process gone while in flight (reconcile@start)", + ) + } + }; + append( + home, + row.id, + &json!({FIELD: phase, "claim": row.id, "reason": why, "by": "reconcile@start"}), + )?; + } + Ok(format!( + "Replay reconcile: {} claims, {ne} -> NOT_EXECUTED, {un} -> UNCERTAIN", + l.claims.len() + )) + }) +} diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 003c4a3b..85c93095 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -113,6 +113,16 @@ pub enum ControlCommand { ComposeReconcile { declare: Option, }, + /// sovereign-core #249: one approved proposal through the proposer hook + /// (crate::approved): desk-key MAC authentication, a durable replay claim, + /// then the production compose run (J-Space, AEGIS verify, World commit, + /// Cortex records) with `workspace` as the task's workspace. Answered with + /// `ComposeApprovedResult` or `ComposeApprovedRefused`. Writes nothing to + /// `workspace`; the effect still needs an authorization, an intent and an ack. + ComposeApprovedProposal { + proposal: crate::approved::ApprovedProposal, + workspace: String, + }, /// NEXT-PHASE-2: operator `stop`, `resume`, `revoke` (ACCEPTANCE-v2 2.5, 2.6). ComposeControl { action: String, @@ -181,6 +191,11 @@ pub enum ControlResponse { ComposeReconciled(Box), /// Result of `ComposeControl`. ComposeControlled(Box), + /// `ComposeApprovedProposal` committed (state COMMITTED or ALREADY_COMMITTED). + ComposeApprovedResult(Box), + /// `ComposeApprovedProposal` refused (named; nothing ran unless the + /// refusal says the run happened). + ComposeApprovedRefused(Box), Error(String), } diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index 1eb35d2a..1c674b11 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -104,6 +104,35 @@ pub struct Grant { /// `Some(None)`: authorized against an absent target. `None`: the grant /// predates NEXT-PHASE-2 and names no prior state (always stale). pub prior_sha256: Option>, + /// The workspace the target must stay inside (sovereign-core #249). A + /// grant without one opens no intent. + pub workspace: Option, + /// Set on the grant the daemon writes after an approved compose (#249). + pub approved: Option, + /// The record's links. + pub links: Vec, +} + +/// Marker field of the grant the daemon itself writes after a COMMITTED +/// approved compose (sovereign-core #249). Reserved: `ComposeNote` refuses it. +pub const APPROVED_GRANT: &str = "approved_grant"; + +/// What an approved grant must be backed by: a COMMITTED replay claim whose +/// commit evidence names the grant's proposal, promotion and evidence. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovedLink { + pub approval_key: String, + pub replay_claim: u64, + pub cx_promotion: u64, + pub cx_evidence: u64, +} + +/// What the ledger reads back from an approved grant: its link and the bound +/// approval identity its text names (so the approval key can be recomputed). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovedGrant { + pub link: ApprovedLink, + pub identity: crate::approved_auth::ApprovalIdentity, } /// What an executor asks for before it touches the world. @@ -140,6 +169,8 @@ pub struct IntentRow { #[derive(Debug, Default, Clone)] pub struct Ledger { pub grants: BTreeMap, + /// Approved grants by replay claim: more than one for a claim opens none. + pub approved_by_claim: BTreeMap>, pub intents: BTreeMap, /// authorization id -> intent id (one intent per authorization). pub spent: BTreeMap, @@ -192,7 +223,7 @@ impl Ledger { continue; }; match r.note.as_deref() { - Some("authorization") => l.read_authorization(r.id, text)?, + Some("authorization") => l.read_authorization(r.id, text, &r.links)?, Some("effect") => l.read_effect(r.id, text)?, _ => {} } @@ -200,7 +231,7 @@ impl Ledger { Ok(l) } - fn read_authorization(&mut self, id: u64, text: &str) -> Result<(), Refusal> { + fn read_authorization(&mut self, id: u64, text: &str, links: &[u64]) -> Result<(), Refusal> { let v: Value = match serde_json::from_str(text) { Ok(v) => v, // An authorization that is not JSON authorizes nothing. @@ -234,6 +265,40 @@ impl Ledger { content_sha256: c.to_string(), target: v.get("target").and_then(Value::as_str).map(str::to_string), prior_sha256: opt_digest(&v, "prior_sha256", id)?, + workspace: v + .get("workspace") + .and_then(Value::as_str) + .map(str::to_string), + approved: match v.get(APPROVED_GRANT) { + None => None, + Some(_) => { + let link = ApprovedLink { + approval_key: s(&v, "approval_key", id)?, + replay_claim: u(&v, "replay_claim", id)?, + cx_promotion: u(&v, "cx_promotion", id)?, + cx_evidence: u(&v, "cx_evidence", id)?, + }; + self.approved_by_claim + .entry(link.replay_claim) + .or_default() + .push(id); + Some(ApprovedGrant { + identity: crate::approved_auth::ApprovalIdentity { + trace_id: s(&v, "trace_id", id)?, + request_id: s(&v, "request_id", id)?, + approval_id: s(&v, "approval_id", id)?, + approver: s(&v, "approver", id)?, + path: path.to_string(), + content_sha256: c.to_string(), + approved_proposal_sha256: s(&v, "approved_proposal_sha256", id)?, + desk_key_id: s(&v, "desk_key_id", id)?, + workspace: s(&v, "workspace", id)?, + }, + link, + }) + } + }, + links: links.to_vec(), }, ); Ok(()) @@ -462,6 +527,37 @@ pub fn world_state(row: &IntentRow) -> (EffectState, Result, Stri (st, now) } +/// The world check, confined (476ca4 c28): the target is read only while it +/// still resolves inside its grant's workspace (`confine_target` again, at +/// ack and reconcile time, so a directory swapped for a symlink after the +/// intent opened is seen). When confinement refuses, or the grant names no +/// workspace, the state is UNRESOLVED, never DONE or NOT_DONE. +pub fn confined_world_state( + l: &Ledger, + row: &IntentRow, +) -> (EffectState, Result, String>) { + let ws = l + .grants + .get(&row.authorization) + .and_then(|g| g.workspace.clone()); + let Some(ws) = ws else { + return ( + EffectState::Unresolved, + Err(format!( + "OutsideWorkspace: authorization #{} names no workspace", + row.authorization + )), + ); + }; + if let Err(r) = confine_target(&ws, &row.path, &row.target) { + return ( + EffectState::Unresolved, + Err(format!("{}: {}", r.name, r.detail)), + ); + } + world_state(row) +} + /// Start time of a process (clock ticks since boot, /proc//stat field 22). pub fn process_start_ticks(pid: u32) -> Option { let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; @@ -504,9 +600,35 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { "ComposeNote: effect records with a \"phase\" are written only by the effect commands" .into(), ), + // sovereign-core #249: approved-submission replay records come only from + // crate::approved_replay. + "effect" if v.get(crate::approved_replay::FIELD).is_some() => Err( + "ComposeNote: approved_submission records are written only by the replay ledger".into(), + ), "authorization" if v.get("control").is_some() => { Err("ComposeNote: control records are written only by ComposeControl".into()) } + // sovereign-core #249: the approved grant comes only from the daemon, + // after a COMMITTED approved compose. + "authorization" if v.get(APPROVED_GRANT).is_some() => Err( + "ComposeNote: approved_grant records are written only by ComposeApprovedProposal" + .into(), + ), + // sovereign-core #249: a grant names its workspace and a target inside it. + "authorization" if v.get("proposal_sha256").is_some() => { + let (Some(ws), Some(path), Some(target)) = ( + v.get("workspace").and_then(Value::as_str), + v.get("path").and_then(Value::as_str), + v.get("target").and_then(Value::as_str), + ) else { + return Err( + "ComposeNote: an authorization grant must name its workspace, path and target" + .into(), + ); + }; + confine_target(ws, path, target) + .map_err(|r| format!("ComposeNote: authorization grant refused: {r}")) + } // ACCEPTANCE-v3 2.4: repair records come only from RecoverComposeHome. "constraint" if v.get("repair").is_some() => Err( "ComposeNote: constraint records with a \"repair\" field are written only by RecoverComposeHome" @@ -516,7 +638,161 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { } } -fn ledger(home: &mut ComposeHome) -> Result { +/// Workspace confinement of an effect target (sovereign-core #249): the +/// workspace is an absolute, canonical directory that is not `/`; `path` is +/// relative with plain components only; `target` is exactly +/// `workspace/path`; its parent resolves (symlinks followed) to +/// `workspace/`; and the target itself, when present, is a +/// regular file, never a symlink. +pub fn confine_target(workspace: &str, path: &str, target: &str) -> Result<(), Refusal> { + use std::path::Component; + let out = |w: String| Refusal::new("OutsideWorkspace", w); + let ws = Path::new(workspace); + let canon = + std::fs::canonicalize(ws).map_err(|e| out(format!("workspace {workspace}: {e}")))?; + if !ws.is_absolute() || canon != ws || !canon.is_dir() || canon == Path::new("/") { + return Err(out(format!( + "workspace {workspace} is not an absolute canonical directory other than /" + ))); + } + let rel = Path::new(path); + if path.is_empty() || !rel.components().all(|c| matches!(c, Component::Normal(_))) { + return Err(out(format!("path {path:?} is not a plain relative path"))); + } + let want = ws.join(rel); + if Path::new(target) != want { + return Err(out(format!( + "target {target} is not {} (workspace {workspace} + path {path})", + want.display() + ))); + } + let parent = want.parent().unwrap_or(ws); + let real = std::fs::canonicalize(parent) + .map_err(|e| out(format!("target directory {}: {e}", parent.display())))?; + if real != parent || !real.starts_with(&canon) { + return Err(out(format!( + "target directory {} resolves to {} (outside or through a symlink)", + parent.display(), + real.display() + ))); + } + match std::fs::symlink_metadata(&want) { + Ok(m) if !m.file_type().is_file() => Err(out(format!( + "target {target} exists and is not a regular file (symlink or other)" + ))), + Ok(_) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(out(format!("target {target}: {e}"))), + } +} + +/// An approved grant must be backed by its COMMITTED replay claim: same +/// approval key, commit evidence naming the grant's proposal, promotion and +/// evidence, and the record linking all three. +fn check_approved_backing( + l: &Ledger, + g: &Grant, + host: &[ComposeRecordView], +) -> Result<(), Refusal> { + let Some(ag) = &g.approved else { + return Ok(()); + }; + let a = &ag.link; + let no = |w: &str| { + Refusal::new( + "NotAuthorized", + format!( + "approved grant #{} is not backed by a committed approved compose: {w}", + g.id + ), + ) + }; + // One approval, one grant: a copy of the grant (same claim) opens nothing. + if l.approved_by_claim.get(&a.replay_claim).map(Vec::len) != Some(1) { + return Err(no("more than one approved grant names this replay claim")); + } + // The grant's fields are the bound approval: its identity hashes to the + // claim's approval key (path, content, workspace and ids all covered), and + // the target is the bound workspace plus path. + let id = &ag.identity; + let bound_target = Path::new(&id.workspace).join(&id.path); + if crate::approved_auth::approval_key(id) != a.approval_key + || g.target.as_deref().map(Path::new) != Some(bound_target.as_path()) + || g.workspace.as_deref() != Some(id.workspace.as_str()) + { + return Err(no("grant fields are not the bound approval")); + } + let rl = + crate::approved_replay::ReplayLedger::from_records(host).map_err(|r| no(&r.to_string()))?; + let row = rl + .claims + .get(&a.replay_claim) + .ok_or_else(|| no("no such replay claim"))?; + let ev = row.evidence.as_ref(); + if row.state != crate::approved_replay::ClaimState::Committed + || row.keys.approval_key != a.approval_key + || ( + &row.keys.request_id, + &row.keys.approval_id, + &row.keys.trace_id, + ) != (&id.request_id, &id.approval_id, &id.trace_id) + || ev.map(|e| { + ( + e.compose_proposal_sha256.as_str(), + e.cx_promotion, + e.cx_evidence, + ) + }) != Some((g.proposal_sha256.as_str(), a.cx_promotion, a.cx_evidence)) + || ![a.cx_promotion, a.cx_evidence, a.replay_claim] + .iter() + .all(|x| g.links.contains(x)) + { + return Err(no("claim state, key, evidence or links differ")); + } + Ok(()) +} + +/// The grant the daemon writes after a COMMITTED approved compose (#249): +/// reserved (`approved_grant`), confined to `workspace`, linked to the +/// promotion, evidence and replay claim. Returns (record id, target). +#[allow(clippy::too_many_arguments)] +pub(crate) fn write_approved_grant( + b: &ComposeBridge, + workspace: &str, + path: &str, + content_sha256: &str, + approver: &str, + ids: &Value, + link: &ApprovedLink, + proposal_sha256: &str, +) -> 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))?; + let mut text = json!({ + APPROVED_GRANT: 1, "proposal_sha256": proposal_sha256, "path": path, + "content_sha256": content_sha256, "approver": approver, "target": target, + "workspace": workspace, "prior_sha256": prior, + "approval_key": link.approval_key, "replay_claim": link.replay_claim, + "cx_promotion": link.cx_promotion, "cx_evidence": link.cx_evidence, + }); + if let (Some(t), Some(i)) = (text.as_object_mut(), ids.as_object()) { + for (k, v) in i { + t.entry(k.clone()).or_insert(v.clone()); + } + } + let n = append( + home, + NoteKind::Authorization, + &[link.cx_promotion, link.cx_evidence, link.replay_claim], + &text, + )?; + Ok((n.id, target)) + }) +} + +fn host_views(home: &mut ComposeHome) -> Result, String> { let (recs, total) = home .compose .recall(aien_omega_compose::SUBJECT_HOST, HOST_RECALL_MAX) @@ -530,11 +806,14 @@ fn ledger(home: &mut ComposeHome) -> Result { ) )); } - let views: Vec = recs + Ok(recs .iter() .map(|r| record_view(&mut home.compose, r)) - .collect(); - Ledger::from_records(&views).map_err(|r| r.to_string()) + .collect()) +} + +fn ledger(home: &mut ComposeHome) -> Result { + Ledger::from_records(&host_views(home)?).map_err(|r| r.to_string()) } fn append( @@ -580,10 +859,21 @@ pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { return ControlResponse::Error(e); } noted(b.with_home(|home| { - let l = ledger(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())?; 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( + "NotAuthorized", + format!("authorization #{} names no workspace", g.id), + ) + .to_string() + })?; + confine_target(ws, &req.path, &req.target).map_err(|r| r.to_string())?; + check_approved_backing(&l, g, &views).map_err(|r| r.to_string())?; let text = json!({ "phase": PHASE_INTENT, "tool": "write_file", "authorization": g.id, "proposal_sha256": req.proposal_sha256, "path": req.path, "target": req.target, @@ -613,7 +903,7 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse row.state_record )); } - let (st, disk) = world_state(row); + let (st, disk) = confined_world_state(&l, row); let text = json!({ "phase": PHASE_ACK, "intent": intent, "authorization": row.authorization, "tool": "write_file", "path": row.path, "content_sha256": row.content_sha256, @@ -668,7 +958,7 @@ pub fn reconcile( }); continue; } - let (world, disk) = world_state(&row); + let (world, disk) = confined_world_state(&l, &row); let disk_hex = disk.as_ref().ok().cloned().flatten(); let (st, who) = match declare { Some(d) => { @@ -686,6 +976,18 @@ pub fn reconcile( } None => (world, by.to_string()), }; + // Never DONE for a target outside its workspace, not even by declaration. + if st == EffectState::Done + && disk + .as_ref() + .is_err_and(|e| e.starts_with("OutsideWorkspace")) + { + return Err(format!( + "reconcile: intent #{} cannot be declared DONE: {}", + row.id, + disk.as_ref().err().map(String::as_str).unwrap_or_default() + )); + } if st == EffectState::Unresolved && row.unresolved_digest.as_ref() == Some(&disk_hex) { out.push(ReconcileOutcome { intent: row.id, @@ -1081,4 +1383,109 @@ mod tests { assert!(check_reserved_note("effect", r#"{"tool":"inspect"}"#).is_ok()); assert!(check_reserved_note("constraint", "plain text").is_ok()); } + + #[test] + fn grants_are_confined_and_the_approved_kind_is_reserved() { + let t = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(t.path()).unwrap(); + let ws = root.join("ws"); + std::fs::create_dir_all(ws.join("d")).unwrap(); + let w = ws.to_str().unwrap(); + let tg = |p: &str| ws.join(p).display().to_string(); + assert!(confine_target(w, "N.md", &tg("N.md")).is_ok()); + assert!(confine_target(w, "d/N.md", &tg("d/N.md")).is_ok()); + let out = |ws: &str, p: &str, t: &str| confine_target(ws, p, t).unwrap_err().name; + assert_eq!(out(w, "N.md", "/etc/N.md"), "OutsideWorkspace"); + assert_eq!(out(w, "../N.md", &tg("../N.md")), "OutsideWorkspace"); + assert_eq!(out(w, "/etc/passwd", "/etc/passwd"), "OutsideWorkspace"); + assert_eq!(out(w, "./N.md", &tg("./N.md")), "OutsideWorkspace"); + assert_eq!(out(w, "", w), "OutsideWorkspace"); + assert_eq!(out("/", "etc/passwd", "/etc/passwd"), "OutsideWorkspace"); + assert_eq!(out("ws", "N.md", "ws/N.md"), "OutsideWorkspace"); + assert_eq!( + out(&format!("{w}/d/.."), "N.md", &format!("{w}/d/../N.md")), + "OutsideWorkspace" + ); + std::os::unix::fs::symlink(&root, ws.join("up")).unwrap(); + assert_eq!(out(w, "up/x", &tg("up/x")), "OutsideWorkspace"); + std::os::unix::fs::symlink("/etc/hostname", ws.join("l")).unwrap(); + assert_eq!(out(w, "l", &tg("l")), "OutsideWorkspace"); + std::os::unix::fs::symlink(&ws, root.join("wl")).unwrap(); + let wl = root.join("wl").display().to_string(); + assert_eq!(out(&wl, "N.md", &format!("{wl}/N.md")), "OutsideWorkspace"); + + let g = |extra: Value| { + let mut v = json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", + "approver": "x", "target": tg("N.md"), "prior_sha256": null, "workspace": w}); + for (k, x) in extra.as_object().unwrap() { + v[k] = x.clone(); + } + v.to_string() + }; + assert!(check_reserved_note("authorization", &g(json!({}))).is_ok()); + assert!(check_reserved_note("authorization", &g(json!({"approved_grant": 1}))).is_err()); + assert!(check_reserved_note("authorization", &g(json!({"target": "/etc/N.md"}))).is_err()); + let mut no_ws: Value = serde_json::from_str(&g(json!({}))).unwrap(); + no_ws.as_object_mut().unwrap().remove("workspace"); + assert!(check_reserved_note("authorization", &no_ws.to_string()).is_err()); + + // Approved grants (476ca4 c25): fields bound to the approval key, one per + // claim, and a COMMITTED claim behind it. + let rec = |id: u64, links: Vec, text: String| ComposeRecordView { + links, + ..super::tests::rec(id, "authorization", serde_json::from_str(&text).unwrap()) + }; + let ident = crate::approved_auth::ApprovalIdentity { + trace_id: "t".into(), + request_id: "r".into(), + approval_id: "a".into(), + approver: "x".into(), + path: "N.md".into(), + content_sha256: "c".into(), + approved_proposal_sha256: "s".into(), + desk_key_id: "k".into(), + workspace: w.into(), + }; + let key = crate::approved_auth::approval_key(&ident); + let approved = |extra: Value| { + let mut e = json!({"approved_grant": 1, "approval_key": key, "replay_claim": 3, + "cx_promotion": 1, "cx_evidence": 2, "trace_id": "t", "request_id": "r", + "approval_id": "a", "approved_proposal_sha256": "s", "desk_key_id": "k"}); + for (k, x) in extra.as_object().unwrap() { + e[k] = x.clone(); + } + g(e) + }; + let why = |recs: &[ComposeRecordView], id: u64| { + let l = Ledger::from_records(recs).unwrap(); + let r = check_approved_backing(&l, &l.grants[&id], recs).unwrap_err(); + assert_eq!(r.name, "NotAuthorized"); + r.detail + }; + // Bound fields, no claim behind it. + let one = rec(5, vec![1, 2, 3], approved(json!({}))); + assert!(why(std::slice::from_ref(&one), 5).contains("no such replay claim")); + // Path, content, target or ids not the ones the approval key binds. + for bad in [ + json!({"path": "O.md", "target": tg("O.md")}), + json!({"content_sha256": "other"}), + json!({"request_id": "r2"}), + json!({"approval_key": "0".repeat(64)}), + ] { + let r = rec(5, vec![1, 2, 3], approved(bad.clone())); + assert!( + why(std::slice::from_ref(&r), 5).contains("not the bound approval"), + "{bad}" + ); + } + // A byte copy of the grant (same claim, same links): neither opens. + let copy = rec(6, vec![1, 2, 3], approved(json!({}))); + let both = [one.clone(), copy]; + for id in [5, 6] { + assert!(why(&both, id).contains("more than one approved grant")); + } + // A grant without the marker needs no backing; the approved one without + // its fields is a corrupt ledger, not a generic grant. + assert!(Ledger::from_records(&[rec(6, vec![], g(json!({"approved_grant": 1})))]).is_err()); + } } diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index 8bd576a6..b52be6f0 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -1,6 +1,8 @@ //! AIEN Runtime: Canonical Single-Process Host for Persistent Branching Intelligence pub mod approved; +pub mod approved_auth; +pub mod approved_replay; pub mod client; pub mod context; pub mod control; diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index c18c5ca8..28ef62d3 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -201,6 +201,33 @@ impl AienRuntimeServer { } }; println!("{line}"); + // sovereign-core #249: settle approved-proposal claims a previous + // process left open (never re-run). A failure gates effect commands + // and approved proposals like a failed effect reconcile. + let b = compose.clone().expect("compose is Some here"); + let gate = b.clone(); + let line = match tokio::task::spawn_blocking(move || { + crate::approved_replay::reconcile_at_start(&b) + }) + .await + { + Ok(Ok(line)) => line, + Ok(Err(e)) => { + gate.set_reconcile_failed(format!("replay reconcile refused: {e}")); + format!( + "Replay reconcile: refused: {e}; {}", + crate::effects::RECONCILE_GATE_NOTE + ) + } + Err(e) => { + gate.set_reconcile_failed(format!("replay reconcile failed: {e}")); + format!( + "Replay reconcile: failed: {e}; {}", + crate::effects::RECONCILE_GATE_NOTE + ) + } + }; + println!("{line}"); } // Connection accept loop @@ -388,7 +415,7 @@ pub fn finish_reason_label(reason: &aien_inference_abi::FinishReason) -> &'stati } /// A compose command, run on a blocking thread against the bridge. -type ComposeJob = Box ControlResponse + Send>; +type ComposeJob = Box) -> ControlResponse + Send>; /// NEXT-PHASE-1: the whole turn as one string (no streaming) and its token /// count, for the compose "model" Skill. Same submission path as @@ -611,7 +638,7 @@ async fn handle_connection( ref workspace, } => { let (g, w) = (goal.clone(), workspace.clone()); - Some(Box::new(move |b: &ComposeBridge| b.run_task(&g, &w))) + Some(Box::new(move |b: &Arc| b.run_task(&g, &w))) } ControlCommand::ComposeNote { ref kind, @@ -620,18 +647,20 @@ async fn handle_connection( } => { let (k, t, l) = (kind.clone(), text.clone(), links.clone()); // NEXT-PHASE-2: gated effect/control records cannot be forged here. - Some(Box::new( - move |b: &ComposeBridge| match crate::effects::check_reserved_note(&k, &t) { + Some(Box::new(move |b: &Arc| { + match crate::effects::check_reserved_note(&k, &t) { Ok(()) => b.note(&k, &t, &l), Err(e) => ControlResponse::Error(e), - }, - )) + } + })) } ControlCommand::ComposeRecall { ref ids, prefix } => { let i = ids.clone(); - Some(Box::new(move |b: &ComposeBridge| b.recall(&i, prefix))) + Some(Box::new(move |b: &Arc| b.recall(&i, prefix))) + } + ControlCommand::RecoverComposeHome => { + Some(Box::new(|b: &Arc| b.recover())) } - ControlCommand::RecoverComposeHome => Some(Box::new(|b: &ComposeBridge| b.recover())), // NEXT-PHASE-2: effect intents, acks, reconcile, operator control. ControlCommand::ComposeEffectIntent { authorization, @@ -651,7 +680,7 @@ async fn handle_connection( executor_pid, executor_start, }; - Some(Box::new(move |b: &ComposeBridge| { + Some(Box::new(move |b: &Arc| { crate::effects::open_intent(b, &req) })) } @@ -660,23 +689,35 @@ async fn handle_connection( ref reported, } => { let r = reported.clone(); - Some(Box::new(move |b: &ComposeBridge| { + Some(Box::new(move |b: &Arc| { crate::effects::ack(b, intent, &r) })) } ControlCommand::ComposeReconcile { ref declare } => { let d = declare.clone(); - Some(Box::new(move |b: &ComposeBridge| { + Some(Box::new(move |b: &Arc| { crate::effects::reconcile(b, d.as_ref(), "reconcile") })) } + ControlCommand::ComposeApprovedProposal { + ref proposal, + ref workspace, + } => { + let (p, w) = (proposal.clone(), workspace.clone()); + Some(Box::new(move |b: &Arc| { + match crate::approved::ProposerHook::new(b.clone()).submit(&p, &w) { + Ok(r) => ControlResponse::ComposeApprovedResult(Box::new(r)), + Err(r) => ControlResponse::ComposeApprovedRefused(r), + } + })) + } ControlCommand::ComposeControl { ref action, ref approver, authorization, } => { let (a, p) = (action.clone(), approver.clone()); - Some(Box::new(move |b: &ComposeBridge| { + Some(Box::new(move |b: &Arc| { crate::effects::control(b, &a, &p, authorization) })) } diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 82a5e0af..b684a4de 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -415,7 +415,8 @@ impl AienRuntimeSpine { | ControlCommand::ComposeEffectIntent { .. } | ControlCommand::ComposeEffectAck { .. } | ControlCommand::ComposeReconcile { .. } - | ControlCommand::ComposeControl { .. } => ControlResponse::Error( + | ControlCommand::ComposeControl { .. } + | ControlCommand::ComposeApprovedProposal { .. } => ControlResponse::Error( "compose commands are handled on the socket connection, not as one-shot commands" .into(), ), diff --git a/crates/aien-runtime/tests/approved_attacks_test.rs b/crates/aien-runtime/tests/approved_attacks_test.rs new file mode 100644 index 00000000..57926ece --- /dev/null +++ b/crates/aien-runtime/tests/approved_attacks_test.rs @@ -0,0 +1,1403 @@ +//! sovereign-core #249 part C: adversarial tests of the approved-write path, +//! each driven over the daemon's real control socket (AienRuntimeServer with a +//! mock backend; the approved proposal text is the proposer, no model). +//! +//! Every test asserts the SECURE outcome: it passes when the attack is refused +//! and fails ("ATTACK SUCCEEDED") when it is not. Tests share one process-wide +//! AIEN_COMPOSE_DIR, so they take turns. +//! +//! Needs librx_compose.a (AIEN_OMEGA_COMPOSE_LIB); in a stub build every test +//! returns early. The two crash tests need `--features fault-hold` (the +//! production build compiles the crash points to nothing). +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_omega_compose::hex; +use aien_runtime::approved::{approved_proposal_sha256, ApprovedProposal}; +use aien_runtime::approved_auth::{desk_key_path, DeskKey}; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlEnvelope, ControlResponse}; +use aien_runtime::effects; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +const PATH: &str = "NOTES.md"; +const CONTENT: &str = "approved through the daemon\n"; +const APPROVER: &str = "interplane-host"; + +/// One daemon at a time: AIEN_COMPOSE_DIR is process-wide. +static TURN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn home(tmp: &Path) -> PathBuf { + tmp.join("compose") +} + +fn ws(tmp: &Path) -> PathBuf { + let w = tmp.join("ws"); + std::fs::create_dir_all(&w).unwrap(); + w +} + +/// A compose home with a desk key, and a workspace beside it. +fn fresh() -> tempfile::TempDir { + let tmp = tempfile::tempdir().unwrap(); + DeskKey::create(&desk_key_path(&home(tmp.path()))).unwrap(); + ws(tmp.path()); + tmp +} + +fn unsigned(request: &str, approval: &str, path: &str, content: &str) -> ApprovedProposal { + ApprovedProposal { + request_id: request.into(), + trace_id: format!("trace-{request}"), + approval_id: approval.into(), + approver: APPROVER.into(), + path: path.into(), + content: content.into(), + approved_proposal_sha256: approved_proposal_sha256(path, content), + content_sha256: sha(content.as_bytes()), + approval_mac: String::new(), + } +} + +/// Signed by the real desk key of `tmp`'s compose home. +fn signed(tmp: &Path, request: &str, approval: &str) -> ApprovedProposal { + sign(tmp, unsigned(request, approval, PATH, CONTENT)) +} + +fn sign(tmp: &Path, mut p: ApprovedProposal) -> ApprovedProposal { + p.approval_mac = DeskKey::load(&desk_key_path(&home(tmp))) + .unwrap() + .sign(&p, &ws(tmp)); + p +} + +struct Daemon { + c: AienRuntimeClient, + socket: PathBuf, + h: tokio::task::JoinHandle>, +} + +/// Start a daemon over `tmp`'s compose home (one at a time per compose home). +async fn up(tmp: &Path, name: &str) -> Daemon { + std::env::set_var("AIEN_COMPOSE_DIR", home(tmp)); + let socket = tmp.join(name); + let cfg = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16)); + let server = AienRuntimeServer::new(spine, &socket); + let h = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let c = AienRuntimeClient::new(&socket); + for _ in 0..250 { + if c.is_alive().await { + return Daemon { c, socket, h }; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +async fn down(d: Daemon) { + let _ = d.c.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), d.h).await; +} + +async fn submit(c: &AienRuntimeClient, p: &ApprovedProposal, ws: &Path) -> ControlResponse { + c.send_command(ControlCommand::ComposeApprovedProposal { + proposal: p.clone(), + workspace: ws.display().to_string(), + }) + .await + .unwrap() +} + +/// (records_total, every host record's text). +async fn journal(c: &AienRuntimeClient) -> (u64, Vec) { + match c + .send_command(ControlCommand::ComposeRecall { + ids: vec![], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(r) => ( + r.records_total, + r.host.iter().filter_map(|h| h.text.clone()).collect(), + ), + other => panic!("recall: {other:?}"), + } +} + +fn phase_count(texts: &[String], phase: &str) -> usize { + let needle = format!("\"approved_submission\":\"{phase}\""); + texts.iter().filter(|t| t.contains(&needle)).count() +} + +/// The refusal (refused_by, name), or panic naming the attack as successful. +fn refused(r: ControlResponse, attack: &str) -> (String, String) { + match r { + ControlResponse::ComposeApprovedRefused(e) => (e.refused_by.clone(), e.name.clone()), + other => panic!("ATTACK SUCCEEDED ({attack}): {other:?}"), + } +} + +fn committed(r: ControlResponse) -> aien_runtime::approved::ApprovedComposeReport { + match r { + ControlResponse::ComposeApprovedResult(r) => *r, + other => panic!("honest approval did not commit: {other:?}"), + } +} + +/// One field of an honestly signed approval changed after signing (hashes +/// recomputed where the field feeds them, so only the MAC can catch it). +async fn tampered(attack: &str, edit: impl FnOnce(&Path, &mut ApprovedProposal)) { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let good = signed(tmp.path(), "req-t", "appr-t"); + let mut p = good.clone(); + edit(tmp.path(), &mut p); + let (n0, _) = journal(&d.c).await; + let (by, name) = refused(submit(&d.c, &p, &ws(tmp.path())).await, attack); + assert_eq!( + (by.as_str(), name.as_str()), + ("PROPOSAL_REFUSED", "Unauthenticated") + ); + assert_eq!( + journal(&d.c).await.0, + n0, + "{attack}: refusal appended records" + ); + // The forgery did not consume the honest approval. + assert_eq!( + committed(submit(&d.c, &good, &ws(tmp.path())).await).state, + "COMMITTED" + ); + down(d).await; +} + +fn rehash(p: &mut ApprovedProposal) { + p.approved_proposal_sha256 = approved_proposal_sha256(&p.path, &p.content); + p.content_sha256 = sha(p.content.as_bytes()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c01_forged_approver() { + tampered("forged approver", |_, p| p.approver = "drake".into()).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c02a_invalid_mac_random() { + tampered("random MAC", |_, p| p.approval_mac = "ab".repeat(32)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c02b_invalid_mac_empty_and_short() { + tampered("empty MAC", |_, p| p.approval_mac.clear()).await; + tampered("short MAC", |_, p| p.approval_mac.truncate(63)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c02c_invalid_mac_uppercase_of_the_real_one() { + tampered("uppercase MAC", |_, p| { + p.approval_mac = p.approval_mac.to_uppercase() + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c02d_mac_from_another_desk_key() { + tampered("MAC under another desk key", |tmp, p| { + let other = DeskKey::create(&tmp.join("other-desk").join("k")).unwrap(); + p.approval_mac = other.sign(p, &ws(tmp)); + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c03_changed_trace_id() { + tampered("changed trace_id", |_, p| p.trace_id = "trace-other".into()).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c04_changed_request_id() { + tampered("changed request_id", |_, p| { + p.request_id = "req-other".into() + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c05_changed_approval_id() { + tampered("changed approval_id", |_, p| { + p.approval_id = "appr-other".into() + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c06_changed_path() { + tampered("changed path", |_, p| { + p.path = "OTHER.md".into(); + rehash(p); + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c07_changed_content() { + tampered("changed content", |_, p| { + p.content = "attacker content\n".into(); + rehash(p); + }) + .await; +} + +/// Invalid authentication evidence on the daemon side: a desk key file other +/// users can read, or no desk key, refuses everything (NoDesk), nothing runs. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c08_desk_key_open_to_others_or_missing() { + use std::os::unix::fs::PermissionsExt; + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let p = signed(tmp.path(), "req-k", "appr-k"); + let key = desk_key_path(&home(tmp.path())); + let (n0, _) = journal(&d.c).await; + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o644)).unwrap(); + let (_, name) = refused(submit(&d.c, &p, &ws(tmp.path())).await, "desk key 0644"); + assert_eq!(name, "NoDesk"); + let saved = std::fs::read(&key).unwrap(); + std::fs::remove_file(&key).unwrap(); + let (_, name) = refused(submit(&d.c, &p, &ws(tmp.path())).await, "no desk key"); + assert_eq!(name, "NoDesk"); + assert_eq!( + journal(&d.c).await.0, + n0, + "a NoDesk refusal appended records" + ); + // Restored: the same approval was not consumed by the refusals. + std::fs::write(&key, saved).unwrap(); + std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!( + committed(submit(&d.c, &p, &ws(tmp.path())).await).state, + "COMMITTED" + ); + down(d).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c09_same_process_replay() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let w = ws(tmp.path()); + let p = signed(tmp.path(), "req-r", "appr-r"); + let first = committed(submit(&d.c, &p, &w).await); + assert_eq!(first.state, "COMMITTED"); + let (n1, _) = journal(&d.c).await; + // The same approval again: the original result, no second run. + let again = committed(submit(&d.c, &p, &w).await); + assert_eq!( + again.state, "ALREADY_COMMITTED", + "ATTACK SUCCEEDED: ran twice" + ); + assert!(again.task.is_none()); + assert_eq!(again.compose_proposal_sha256, first.compose_proposal_sha256); + // Either id reused under a fresh, validly signed approval: refused. + for q in [ + signed(tmp.path(), "req-r", "appr-new"), + signed(tmp.path(), "req-new", "appr-r"), + ] { + let (by, _) = refused(submit(&d.c, &q, &w).await, "id reuse"); + assert_eq!(by, "REPLAY_REFUSED"); + } + let (n2, texts) = journal(&d.c).await; + assert_eq!(n2, n1, "a replay appended records"); + assert_eq!(phase_count(&texts, "committed"), 1); + down(d).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c10_replay_after_daemon_restart() { + let _t = TURN.lock().await; + let tmp = fresh(); + let w = ws(tmp.path()); + let p = signed(tmp.path(), "req-a", "appr-a"); + let d = up(tmp.path(), "s1.sock").await; + let first = committed(submit(&d.c, &p, &w).await); + down(d).await; + let d = up(tmp.path(), "s2.sock").await; + let (n0, _) = journal(&d.c).await; + let again = committed(submit(&d.c, &p, &w).await); + assert_eq!( + again.state, "ALREADY_COMMITTED", + "ATTACK SUCCEEDED: ran after restart" + ); + assert_eq!(again.grant_links, first.grant_links); + let (by, _) = refused( + submit(&d.c, &signed(tmp.path(), "req-b", "appr-a"), &w).await, + "approval_id reuse after restart", + ); + assert_eq!(by, "REPLAY_REFUSED"); + let (n1, texts) = journal(&d.c).await; + assert_eq!(n1, n0, "replay after restart appended records"); + assert_eq!(phase_count(&texts, "committed"), 1); + down(d).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c11_concurrent_duplicate_submissions() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let w = ws(tmp.path()); + let p = signed(tmp.path(), "req-c", "appr-c"); + let mut tasks = Vec::new(); + for _ in 0..12 { + let (s, p, w) = (d.socket.clone(), p.clone(), w.clone()); + tasks.push(tokio::spawn(async move { + submit(&AienRuntimeClient::new(&s), &p, &w).await + })); + } + let mut ran = 0; + for t in tasks { + match t.await.unwrap() { + ControlResponse::ComposeApprovedResult(r) if r.task.is_some() => ran += 1, + ControlResponse::ComposeApprovedResult(r) => assert_eq!(r.state, "ALREADY_COMMITTED"), + ControlResponse::ComposeApprovedRefused(r) => { + assert_eq!(r.refused_by, "REPLAY_REFUSED") + } + other => panic!("{other:?}"), + } + } + let (_, texts) = journal(&d.c).await; + assert_eq!( + ran, 1, + "ATTACK SUCCEEDED: {ran} compose runs for one approval" + ); + assert_eq!(phase_count(&texts, "accepted"), 1); + assert_eq!(phase_count(&texts, "committed"), 1); + down(d).await; +} + +/// The response is lost: the caller hangs up after the daemon committed the +/// approval, without reading the answer. The retry gets the original result +/// back (ALREADY_COMMITTED); the approval ran exactly once. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c14a_retry_after_response_loss() { + lost_response(true).await; +} + +/// The caller hangs up at once, before any answer. Whatever the daemon did +/// with the abandoned request, the retry runs the approval at most once. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c14b_retry_after_immediate_hangup() { + lost_response(false).await; +} + +async fn lost_response(wait: bool) { + use tokio::io::AsyncWriteExt; + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let w = ws(tmp.path()); + let p = signed(tmp.path(), "req-l", "appr-l"); + let env = ControlEnvelope { + protocol_version: 1, + request_id: 7, + operation_id: 7, + operator_session: 1, + command: ControlCommand::ComposeApprovedProposal { + proposal: p.clone(), + workspace: w.display().to_string(), + }, + }; + let mut s = tokio::net::UnixStream::connect(&d.socket).await.unwrap(); + s.write_all(format!("{}\n", serde_json::to_string(&env).unwrap()).as_bytes()) + .await + .unwrap(); + // Read nothing; hang up only once the daemon has committed the approval, + // so the response (not the request) is what is lost. + let mut ran = !wait; + for _ in 0..(if wait { 400 } else { 0 }) { + if phase_count(&journal(&d.c).await.1, "committed") == 1 { + ran = true; + break; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + drop(s); // response lost + assert!(ran, "the first submission never committed"); + let mut last = None; + for _ in 0..200 { + match submit(&d.c, &p, &w).await { + ControlResponse::ComposeApprovedResult(r) => { + last = Some(r.state.clone()); + break; + } + ControlResponse::ComposeApprovedRefused(r) if r.name == "InFlight" => { + tokio::time::sleep(Duration::from_millis(25)).await + } + other => panic!("retry after a lost response: {other:?}"), + } + } + let (_, texts) = journal(&d.c).await; + if wait { + assert_eq!( + last.as_deref(), + Some("ALREADY_COMMITTED"), + "retry must get the original result" + ); + } + assert!(last.is_some(), "retry never got a result"); + assert_eq!(phase_count(&texts, "accepted"), 1); + assert_eq!( + phase_count(&texts, "committed"), + 1, + "ATTACK SUCCEEDED: ran twice" + ); + eprintln!("c14 (wait {wait}): retry state = {last:?}"); + down(d).await; +} + +/// Replay records cannot be written by a caller (a forged claim would consume, +/// a forged commit would validate an approval). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c15_forged_replay_records_via_compose_note() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + for phase in [ + "accepted", + "in_flight", + "committed", + "failed", + "not_executed", + "uncertain", + "declared", + ] { + let text = json!({"approved_submission": phase, "claim": 1, "request_id": "req-f", + "approval_id": "appr-f", "approval_key": "0".repeat(64)}); + match d + .c + .send_command(ControlCommand::ComposeNote { + kind: "effect".into(), + text: text.to_string(), + links: vec![], + }) + .await + .unwrap() + { + ControlResponse::Error(_) => {} + other => panic!("ATTACK SUCCEEDED: forged {phase} record written: {other:?}"), + } + } + let w = ws(tmp.path()); + assert_eq!( + committed(submit(&d.c, &signed(tmp.path(), "req-f", "appr-f"), &w).await).state, + "COMMITTED" + ); + down(d).await; +} + +/// Even a desk-signed approval may not name a path outside the workspace. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c16_desk_signed_path_escaping_the_workspace() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let w = ws(tmp.path()); + let (n0, _) = journal(&d.c).await; + for (i, path) in ["../escape.md", "/tmp/escape.md", "sub/../../escape.md"] + .iter() + .enumerate() + { + let p = sign( + tmp.path(), + unsigned(&format!("req-p{i}"), &format!("appr-p{i}"), path, CONTENT), + ); + let r = submit(&d.c, &p, &w).await; + let (by, name) = refused(r, &format!("path {path}")); + eprintln!("c16: {path} -> {by} {name}"); + } + assert_eq!(journal(&d.c).await.0, n0); + down(d).await; +} + +/// c17 / c17b: an approval signed for workspace A presented with workspace B +/// is Unauthenticated, appends nothing, and does not consume the approval: +/// presented with A afterwards it commits, and its grant targets A. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c17_approval_redirected_to_another_workspace() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let other = tmp.path().join("other-ws"); + std::fs::create_dir_all(&other).unwrap(); + let p = signed(tmp.path(), "req-w", "appr-w"); + let (n0, _) = journal(&d.c).await; + let (by, name) = refused( + submit(&d.c, &p, &other).await, + "approval for one workspace used in another", + ); + assert_eq!( + (by.as_str(), name.as_str()), + ("PROPOSAL_REFUSED", "Unauthenticated") + ); + assert_eq!( + journal(&d.c).await.0, + n0, + "c17b: the refusal appended records" + ); + let r = committed(submit(&d.c, &p, &ws(tmp.path())).await); + assert_eq!( + r.state, "COMMITTED", + "c17b: the refusal consumed the approval" + ); + let want = canon(&ws(tmp.path())).join(PATH).display().to_string(); + assert_eq!(r.target.as_deref(), Some(want.as_str())); + down(d).await; +} + +/// c17c: the bound workspace presented through a symlink to it canonicalises +/// to the same directory: accepted, and the grant targets the real directory +/// (never the link). A symlink to a DIFFERENT directory is Unauthenticated. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c17c_workspace_through_a_symlink() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let other = tmp.path().join("other-ws"); + std::fs::create_dir_all(&other).unwrap(); + let to_other = tmp.path().join("link-other"); + std::os::unix::fs::symlink(&other, &to_other).unwrap(); + let p = signed(tmp.path(), "req-y", "appr-y"); + let (_, name) = refused( + submit(&d.c, &p, &to_other).await, + "symlink to another workspace", + ); + assert_eq!(name, "Unauthenticated"); + let to_ws = tmp.path().join("link-ws"); + std::os::unix::fs::symlink(ws(tmp.path()), &to_ws).unwrap(); + let r = committed(submit(&d.c, &p, &to_ws).await); + let want = canon(&ws(tmp.path())).join(PATH).display().to_string(); + assert_eq!( + r.target.as_deref(), + Some(want.as_str()), + "grant target through the link" + ); + down(d).await; +} + +fn canon(p: &Path) -> PathBuf { + std::fs::canonicalize(p).unwrap() +} + +/// A compose home inside the workspace (the desk key within the model's reach). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c20_workspace_containing_the_compose_home() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + // Signed for the overlapping workspace itself: only confinement can refuse. + let mut p = unsigned("req-o", "appr-o", PATH, CONTENT); + p.approval_mac = DeskKey::load(&desk_key_path(&home(tmp.path()))) + .unwrap() + .sign(&p, tmp.path()); + let (_, name) = refused(submit(&d.c, &p, tmp.path()).await, "overlapping workspace"); + assert_eq!(name, "Confinement"); + down(d).await; +} + +/// A1: a caller writes its own `authorization` note (workspace, path and a +/// confined target, as #262 requires) for a proposal digest no approved +/// compose produced, then opens an effect intent on it. +/// +/// KNOWN GAP, sovereign-core #261 (the generic client-minted authorization +/// path, its own cut). This test asserts the gap is still OPEN; when #261 +/// closes it the test fails: then flip it to assert refusal. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c18_a1_raw_forged_authorization() { + let opened = forged_authorization(|tmp| { + let w = canon(&ws(tmp)); + (w.clone(), PATH.into(), w.join(PATH)) + }) + .await; + assert_eq!( + opened, "opened", + "sc#261 appears closed (A1 refused): flip c18 to assert refusal" + ); +} + +/// A1b: the same forgery naming a target that is not workspace/path: refused +/// at the note (#262 confinement). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c19_a1b_forged_authorization_outside_workspace() { + let opened = forged_authorization(|tmp| { + let w = canon(&ws(tmp)); + (w, PATH.into(), canon(tmp).join("outside.txt")) + }) + .await; + assert_eq!( + opened, "note refused", + "ATTACK SUCCEEDED: target outside its workspace" + ); +} + +/// A1c: the note names its OWN workspace: the parent of the real workspace, +/// which also holds the compose home. Confinement in a client-minted note +/// only says "inside the workspace the note names". Part of the #261 gap: +/// asserts the gap is OPEN (flip with c18). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c19c_a1c_forged_authorization_names_its_own_workspace() { + let opened = forged_authorization(|tmp| { + let w = canon(tmp); + (w.clone(), "outside.txt".into(), w.join("outside.txt")) + }) + .await; + assert_eq!( + opened, "opened", + "sc#261 appears closed (A1c refused): flip c19c to assert refusal" + ); +} + +/// "opened" = an effect intent opened on the caller-written authorization, +/// "note refused" = ComposeNote refused it, otherwise the intent's refusal. +async fn forged_authorization(at: impl FnOnce(&Path) -> (PathBuf, String, PathBuf)) -> String { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let (w, path, target) = at(tmp.path()); + let target = target.display().to_string(); + let psha = sha(b"never proposed by any approved compose"); + let csha = sha(b"forged\n"); + let note = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, + "approver": "attacker", "workspace": w.display().to_string(), "target": target, + "prior_sha256": null}); + let auth = match d + .c + .send_command(ControlCommand::ComposeNote { + kind: "authorization".into(), + text: note.to_string(), + links: vec![], + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(n) => n.id, + ControlResponse::Error(e) => { + eprintln!("forged authorization: note refused: {e}"); + down(d).await; + return "note refused".into(); + } + other => panic!("{other:?}"), + }; + let r = intent(&d.c, auth, &psha, &path, &target, &csha).await; + eprintln!("forged authorization: intent: {r:?}"); + down(d).await; + match r { + ControlResponse::ComposeNoted(_) => "opened".into(), + ControlResponse::Error(e) => e, + other => panic!("{other:?}"), + } +} + +async fn intent( + c: &AienRuntimeClient, + authorization: u64, + proposal_sha256: &str, + path: &str, + target: &str, + content_sha256: &str, +) -> ControlResponse { + let (pid, start) = effects::self_executor(); + c.send_command(ControlCommand::ComposeEffectIntent { + authorization, + proposal_sha256: proposal_sha256.into(), + path: path.into(), + target: target.into(), + content_sha256: content_sha256.into(), + executor_pid: pid, + executor_start: start, + }) + .await + .unwrap() +} + +/// The effect intent for an approved compose's grant. +async fn grant_intent( + c: &AienRuntimeClient, + r: &aien_runtime::approved::ApprovedComposeReport, + grant: u64, +) -> ControlResponse { + let target = r.target.clone().expect("grant target"); + intent( + c, + grant, + &r.compose_proposal_sha256, + &r.path, + &target, + &r.content_sha256, + ) + .await +} + +fn opened(r: ControlResponse, what: &str) -> u64 { + match r { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("{what}: intent did not open: {other:?}"), + } +} + +fn not_opened(r: ControlResponse, attack: &str) -> String { + match r { + ControlResponse::Error(e) => e, + other => panic!("ATTACK SUCCEEDED ({attack}): {other:?}"), + } +} + +/// The `state` the ack record for `intent` holds. +async fn ack_state(c: &AienRuntimeClient, intent: u64) -> String { + match c + .send_command(ControlCommand::ComposeEffectAck { + intent, + reported: json!({"executor": "attack-test"}), + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(_) => {} + other => panic!("ack: {other:?}"), + } + let needle = format!("\"intent\":{intent},"); + let (_, texts) = journal(c).await; + let t = texts + .iter() + .rev() + .find(|t| t.contains("\"phase\":\"ack\"") && t.contains(&needle)) + .expect("ack record"); + let v: serde_json::Value = serde_json::from_str(t).unwrap(); + v["state"].as_str().unwrap().to_string() +} + +/// An approved compose, committed, with its grant id. +async fn approved_grant( + d: &Daemon, + tmp: &Path, +) -> (aien_runtime::approved::ApprovedComposeReport, u64) { + let r = committed(submit(&d.c, &signed(tmp, "req-g", "appr-g"), &ws(tmp)).await); + let g = r.approved_grant.expect("COMMITTED report names its grant"); + (r, g) +} + +/// The host text and links of record `id`. +async fn text_of(c: &AienRuntimeClient, id: u64) -> (String, Vec) { + match c + .send_command(ControlCommand::ComposeRecall { + ids: vec![id], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(r) => r + .host + .iter() + .find(|h| h.id == id) + .map(|h| (h.text.clone().expect("record text"), h.links.clone())) + .expect("record"), + other => panic!("recall: {other:?}"), + } +} + +/// c26: the honest path. Approved compose -> grant -> intent -> write -> ack +/// DONE; a second intent on the same grant is AlreadySpent; the approval +/// presented again is ALREADY_COMMITTED and carries no new grant. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c26_happy_path_one_approval_one_effect() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let (r, g) = approved_grant(&d, tmp.path()).await; + let i = opened(grant_intent(&d.c, &r, g).await, "honest grant"); + std::fs::write(r.target.as_deref().unwrap(), CONTENT).unwrap(); + assert_eq!(ack_state(&d.c, i).await, "DONE"); + let e = not_opened( + grant_intent(&d.c, &r, g).await, + "second effect on one grant", + ); + assert!(e.contains("AlreadySpent"), "{e}"); + let again = committed( + submit( + &d.c, + &signed(tmp.path(), "req-g", "appr-g"), + &ws(tmp.path()), + ) + .await, + ); + assert_eq!(again.state, "ALREADY_COMMITTED"); + assert_eq!(again.approved_grant, None); + down(d).await; +} + +/// c21: after the intent opens, the target is swapped for a symlink to a file +/// outside the workspace holding the approved bytes. The ack must not record +/// DONE. A symlink placed BEFORE the intent: the intent is refused. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c21_symlink_swap_of_the_target() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let (r, g) = approved_grant(&d, tmp.path()).await; + let target = PathBuf::from(r.target.clone().unwrap()); + let outside = tmp.path().join("outside.txt"); + std::fs::write(&outside, CONTENT).unwrap(); + // Before the intent: refused. + std::os::unix::fs::symlink(&outside, &target).unwrap(); + let e = not_opened( + grant_intent(&d.c, &r, g).await, + "intent on a symlinked target", + ); + eprintln!("c21 before: {e}"); + std::fs::remove_file(&target).unwrap(); + // After the intent: the ack reads the world and must not say DONE. + let i = opened(grant_intent(&d.c, &r, g).await, "honest grant"); + std::os::unix::fs::symlink(&outside, &target).unwrap(); + let st = ack_state(&d.c, i).await; + assert_ne!( + st, "DONE", + "ATTACK SUCCEEDED: DONE recorded through a symlink" + ); + eprintln!("c21 after: ack state {st}"); + down(d).await; +} + +/// c28: the approved path is in a subdirectory. After the intent opens, the +/// subdirectory is swapped for a symlink to a directory outside the +/// workspace, and the approved bytes are written there. The ack must not +/// record DONE (the bytes are outside the workspace). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c28_parent_directory_swap_after_the_intent() { + let _t = TURN.lock().await; + let tmp = fresh(); + let w = ws(tmp.path()); + std::fs::create_dir_all(w.join("sub")).unwrap(); + let d = up(tmp.path(), "s.sock").await; + let p = sign( + tmp.path(), + unsigned("req-p", "appr-p", "sub/NOTES.md", CONTENT), + ); + let r = committed(submit(&d.c, &p, &w).await); + let g = r.approved_grant.expect("grant"); + let i = opened(grant_intent(&d.c, &r, g).await, "honest grant"); + let outdir = tmp.path().join("outdir"); + std::fs::create_dir_all(&outdir).unwrap(); + std::fs::rename(w.join("sub"), w.join("sub-moved")).unwrap(); + std::os::unix::fs::symlink(&outdir, w.join("sub")).unwrap(); + std::fs::write(outdir.join("NOTES.md"), CONTENT).unwrap(); + let st = ack_state(&d.c, i).await; + eprintln!("c28: ack state {st}"); + down(d).await; + assert_ne!( + st, "DONE", + "ATTACK SUCCEEDED: DONE recorded for bytes outside the workspace (parent symlink)" + ); +} + +/// c28b: the same parent swap, settled by reconcile instead of the ack. The +/// intent names an executor that has already exited, so ComposeReconcile +/// decides it from the world: it must not record DONE. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c28b_parent_directory_swap_settled_by_reconcile() { + let _t = TURN.lock().await; + let tmp = fresh(); + let w = ws(tmp.path()); + std::fs::create_dir_all(w.join("sub")).unwrap(); + let d = up(tmp.path(), "s.sock").await; + let p = sign( + tmp.path(), + unsigned("req-q", "appr-q", "sub/NOTES.md", CONTENT), + ); + let r = committed(submit(&d.c, &p, &w).await); + let g = r.approved_grant.expect("grant"); + // An executor that is gone: a child that has exited. A dead pid reads as + // not alive whatever start ticks the intent names. + let mut child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id(); + child.wait().unwrap(); + let (_, start) = effects::self_executor(); + let i = match d + .c + .send_command(ControlCommand::ComposeEffectIntent { + authorization: g, + proposal_sha256: r.compose_proposal_sha256.clone(), + path: r.path.clone(), + target: r.target.clone().unwrap(), + content_sha256: r.content_sha256.clone(), + executor_pid: pid, + executor_start: start, + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("intent did not open: {other:?}"), + }; + let outdir = tmp.path().join("outdir"); + std::fs::create_dir_all(&outdir).unwrap(); + std::fs::rename(w.join("sub"), w.join("sub-moved")).unwrap(); + std::os::unix::fs::symlink(&outdir, w.join("sub")).unwrap(); + std::fs::write(outdir.join("NOTES.md"), CONTENT).unwrap(); + let out = + d.c.send_command(ControlCommand::ComposeReconcile { declare: None }) + .await + .unwrap(); + down(d).await; + let ControlResponse::ComposeReconciled(rep) = out else { + panic!("reconcile: {out:?}"); + }; + let o = rep + .outcomes + .iter() + .find(|o| o.intent == i) + .expect("the intent was looked at"); + eprintln!("c28b: reconcile {} ({})", o.state, o.note); + assert_ne!( + o.state, "DONE", + "ATTACK SUCCEEDED: reconcile settled DONE for bytes outside the workspace" + ); +} + +/// c22: an `approved_grant` record sent through the socket's ComposeNote +/// (a copy of the daemon's own grant, same links) is refused and appends +/// nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c22_forged_approved_grant_via_socket() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let (_, g) = approved_grant(&d, tmp.path()).await; + let (text, links) = text_of(&d.c, g).await; + let (n0, _) = journal(&d.c).await; + let out = + d.c.send_command(ControlCommand::ComposeNote { + kind: "authorization".into(), + text, + links, + }) + .await + .unwrap(); + assert!( + matches!(out, ControlResponse::Error(_)), + "ATTACK SUCCEEDED: second approved_grant noted: {out:?}" + ); + assert_eq!(journal(&d.c).await.0, n0); + down(d).await; +} + +/// Journal level: a ComposeBridge on the compose home with the daemon down +/// writes records directly (no ComposeNote reserved-record check). This is +/// an attacker who can already write the compose home; the tests check the +/// ledger's own consistency rules, not the socket boundary. +fn bridge(tmp: &Path) -> aien_runtime::spine::ComposeBridge { + let never: aien_runtime::spine::ComposeProposer = + std::sync::Arc::new(|_: &str, _: Duration| Err("no model".to_string())); + aien_runtime::spine::ComposeBridge::new(home(tmp), never, "attack") +} + +fn raw_note(b: &aien_runtime::spine::ComposeBridge, kind: &str, text: &str, links: &[u64]) -> u64 { + match b.note(kind, text, links) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("raw note: {other:?}"), + } +} + +/// A forged approved grant backed by a claim left in `end` (failed, +/// uncertain, uncertain-declared-committed): open_intent must refuse it. +async fn grant_on_unfinished_claim(end: &str) { + use aien_runtime::approved_replay as rp; + let _t = TURN.lock().await; + let tmp = fresh(); + std::env::set_var("AIEN_COMPOSE_DIR", home(tmp.path())); + let (g, csha, psha, target) = { + let b = bridge(tmp.path()); + let w = canon(&ws(tmp.path())); + let csha = sha(CONTENT.as_bytes()); + // A complete bound identity: the grant parses and its identity hashes + // to the claim's key, so only the claim's state can refuse it. + let ident = aien_runtime::approved_auth::ApprovalIdentity { + trace_id: "t".into(), + request_id: format!("req-{end}"), + approval_id: format!("appr-{end}"), + approver: "attacker".into(), + path: PATH.into(), + content_sha256: csha.clone(), + approved_proposal_sha256: approved_proposal_sha256(PATH, CONTENT), + desk_key_id: "forged".into(), + workspace: w.display().to_string(), + }; + let keys = rp::ClaimKeys { + approval_key: aien_runtime::approved_auth::approval_key(&ident), + request_id: ident.request_id.clone(), + approval_id: ident.approval_id.clone(), + trace_id: ident.trace_id.clone(), + }; + let c = rp::claim(&b, &keys).unwrap(); + rp::mark_in_flight(&b, &c).unwrap(); + match end { + "failed" => rp::fail(&b, &c, "attack").unwrap(), + _ => rp::uncertain(&b, &c, "attack").unwrap(), + } + if end == "declared" { + rp::declare(&b, c.id, true, "attacker", "attack").unwrap(); + } + let target = w.join(PATH).display().to_string(); + let psha = sha(b"forged compose proposal"); + // Promotion and evidence: any two existing records, linked. + let pr = raw_note(&b, "constraint", "{\"fake\":\"promotion\"}", &[]); + let ev = raw_note(&b, "constraint", "{\"fake\":\"evidence\"}", &[]); + let text = json!({ + "approved_grant": 1, "proposal_sha256": psha, "path": PATH, + "content_sha256": csha, "approver": "attacker", "target": target, + "workspace": w.display().to_string(), "prior_sha256": null, + "approval_key": keys.approval_key, "replay_claim": c.id, + "cx_promotion": pr, "cx_evidence": ev, + "trace_id": ident.trace_id, "request_id": ident.request_id, + "approval_id": ident.approval_id, + "approved_proposal_sha256": ident.approved_proposal_sha256, + "desk_key_id": ident.desk_key_id, + }); + let g = raw_note(&b, "authorization", &text.to_string(), &[pr, ev, c.id]); + (g, csha, psha, target) + }; + let d = up(tmp.path(), "s.sock").await; + let e = not_opened( + intent(&d.c, g, &psha, PATH, &target, &csha).await, + &format!("approved grant on a {end} claim"), + ); + assert!(e.contains("NotAuthorized"), "{end}: {e}"); + down(d).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c23_forged_grant_on_failed_claim() { + grant_on_unfinished_claim("failed").await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c24a_forged_grant_on_uncertain_claim() { + grant_on_unfinished_claim("uncertain").await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c24b_forged_grant_on_uncertain_claim_declared_committed() { + grant_on_unfinished_claim("declared").await; +} + +/// c25 (journal level): a byte-for-byte copy of the daemon's real grant, +/// same links, appended directly. One approval must never open two effect +/// intents. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +async fn c25_duplicate_approved_grant_for_one_committed_claim() { + let _t = TURN.lock().await; + let tmp = fresh(); + let d = up(tmp.path(), "s.sock").await; + let (r, g) = approved_grant(&d, tmp.path()).await; + let (text, links) = text_of(&d.c, g).await; + down(d).await; + let g2 = raw_note(&bridge(tmp.path()), "authorization", &text, &links); + let d = up(tmp.path(), "s2.sock").await; + let first = grant_intent(&d.c, &r, g).await; + let second = grant_intent(&d.c, &r, g2).await; + let both = matches!( + (&first, &second), + ( + ControlResponse::ComposeNoted(_), + ControlResponse::ComposeNoted(_) + ) + ); + eprintln!("c25: real grant #{g}: {first:?}\nc25: copy #{g2}: {second:?}"); + down(d).await; + assert!( + !both, + "ATTACK SUCCEEDED (journal level): two effect intents from one approval" + ); +} + +/// Crash tests: a child process runs a whole daemon, submits one approval +/// over its socket and is aborted at a crash point inside the daemon. The +/// parent restarts a daemon over the same compose home and retries. +#[cfg(feature = "fault-hold")] +mod crash { + use super::*; + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore] + async fn crash_child_daemon() { + let Ok(tmp) = std::env::var("ATTACK_CRASH_TMP") else { + return; + }; + let tmp = PathBuf::from(tmp); + let d = up(&tmp, "child.sock").await; + let p = signed(&tmp, "req-x", "appr-x"); + let out = submit(&d.c, &p, &ws(&tmp)).await; + panic!("child was not stopped at its crash point: {out:?}"); + } + + fn run_child(tmp: &Path, hold: &str) { + use std::os::unix::process::ExitStatusExt; + let st = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "crash::crash_child_daemon", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("AIEN_FAULT_HOLD", hold) + .env("ATTACK_CRASH_TMP", tmp) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .unwrap(); + assert_eq!(st.signal(), Some(6), "child must abort at {hold}: {st:?}"); + } + + async fn after_crash(hold: &str, want_phase: &str, want_refusal: &str) { + let _t = TURN.lock().await; + let tmp = fresh(); + run_child(tmp.path(), hold); + let d = up(tmp.path(), "after.sock").await; + let (n0, texts) = journal(&d.c).await; + assert_eq!(phase_count(&texts, "accepted"), 1, "the child claimed once"); + assert_eq!( + phase_count(&texts, want_phase), + 1, + "restart reconcile: {texts:?}" + ); + let w = ws(tmp.path()); + let p = signed(tmp.path(), "req-x", "appr-x"); + let r = submit(&d.c, &p, &w).await; + let (by, name) = refused(r, &format!("retry after crash at {hold}")); + assert_eq!( + (by.as_str(), name.as_str()), + ("REPLAY_REFUSED", want_refusal) + ); + let (n1, texts) = journal(&d.c).await; + assert_eq!(n1, n0, "a refused retry appended records"); + assert_eq!(phase_count(&texts, "committed"), 0); + assert!(!w.join(PATH).exists()); + down(d).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" + )] + async fn c12_crash_before_execution() { + after_crash("approved_after_claim", "not_executed", "AlreadyConsumed").await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" + )] + async fn c13_crash_after_execution_started() { + after_crash("approved_after_compose", "uncertain", "Uncertain").await; + } + + /// c27: crash after the claim is COMMITTED, before the grant is written. + /// The approval stays spent and no grant ever appears: no effect possible. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" + )] + async fn c27_crash_after_commit_before_grant() { + let _t = TURN.lock().await; + let tmp = fresh(); + run_child(tmp.path(), "approved_after_commit"); + let d = up(tmp.path(), "after.sock").await; + let (n0, texts) = journal(&d.c).await; + assert_eq!(phase_count(&texts, "committed"), 1, "{texts:?}"); + let grants = |t: &[String]| { + t.iter() + .filter(|x| x.contains("\"approved_grant\"")) + .count() + }; + assert_eq!(grants(&texts), 0, "a grant was written before the crash"); + let w = ws(tmp.path()); + let r = submit(&d.c, &signed(tmp.path(), "req-x", "appr-x"), &w).await; + match &r { + ControlResponse::ComposeApprovedResult(rep) => { + assert_eq!(rep.state, "ALREADY_COMMITTED"); + assert_eq!( + rep.approved_grant, None, + "ATTACK SUCCEEDED: retry minted a grant" + ); + } + ControlResponse::ComposeApprovedRefused(_) => {} + other => panic!("retry: {other:?}"), + } + let (n1, texts) = journal(&d.c).await; + assert_eq!( + grants(&texts), + 0, + "ATTACK SUCCEEDED: a grant appeared after restart" + ); + assert_eq!(n1, n0, "the retry appended records"); + assert!(!w.join(PATH).exists()); + eprintln!("c27: retry -> {r:?}"); + down(d).await; + } +} diff --git a/crates/aien-runtime/tests/approved_confinement_test.rs b/crates/aien-runtime/tests/approved_confinement_test.rs new file mode 100644 index 00000000..78badf0f --- /dev/null +++ b/crates/aien-runtime/tests/approved_confinement_test.rs @@ -0,0 +1,368 @@ +//! sovereign-core #249: the A1/A1b fix (workspace confinement of every grant, +//! the reserved approved grant), driven over the daemon's real control socket +//! (AienRuntimeServer with a mock backend). 476ca4's attack file +//! (approved_attacks_test.rs, review/249-attacks) stays theirs. +//! +//! A1 (raw socket forgery, found by 476ca4 on 6258a6e): a caller that never ran +//! an approved compose writes its own `authorization` note naming a +//! compose_proposal_sha256 nothing produced, opens a ComposeEffectIntent on it, +//! writes, and acks. A1b: the same forgery aimed outside the workspace. +//! +//! After the #249 fix: +//! - a grant must name its workspace; a target outside it (after +//! canonicalisation and symlink checks) is refused at the note and at the +//! intent (A1b, symlinked file, symlinked directory, workspace "/"); +//! - the approved grant kind (`approved_grant`) cannot be written through +//! ComposeNote at all; +//! - STILL OPEN (sc#261, out of #249 scope): a same-user caller can write a +//! generic grant inside a workspace it names and reach DONE. The last block +//! asserts that observed behaviour so the follow-up flips it visibly. +//! +//! Needs librx_compose.a (AIEN_OMEGA_COMPOSE_LIB); in a stub build the compose +//! commands refuse and the test returns early. +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_omega_compose::hex; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::effects; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::time::Duration; +use tempfile::TempDir; + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +async fn start(dir: &TempDir) -> AienRuntimeClient { + let socket = dir.path().join("runtime.sock"); + let spine = AienRuntimeSpine::new( + 1024, + SchedulerConfig { + max_batch_size: 64, + max_batch_tokens: 4096, + prefill_chunk_size: 64, + watermark_blocks: 16, + chunk_prefill: true, + max_prefill_tokens: 4096, + }, + create_shared_kv_manager(1024, 16), + ); + let server = AienRuntimeServer::new(spine, &socket); + tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + for _ in 0..100 { + if client.is_alive().await { + return client; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +async fn note(c: &AienRuntimeClient, kind: &str, text: serde_json::Value) -> ControlResponse { + c.send_command(ControlCommand::ComposeNote { + kind: kind.into(), + text: text.to_string(), + links: vec![], + }) + .await + .unwrap() +} + +async fn intent( + c: &AienRuntimeClient, + auth: u64, + psha: &str, + path: &str, + target: &str, + csha: &str, +) -> ControlResponse { + let (pid, start) = effects::self_executor(); + c.send_command(ControlCommand::ComposeEffectIntent { + authorization: auth, + proposal_sha256: psha.into(), + path: path.into(), + target: target.into(), + content_sha256: csha.into(), + executor_pid: pid, + executor_start: start, + }) + .await + .unwrap() +} + +fn refused(r: ControlResponse, want: &str) -> String { + match r { + ControlResponse::Error(e) => { + assert!(e.contains(want), "want {want}, got {e}"); + e + } + other => panic!("want refusal {want}, got {other:?}"), + } +} + +#[tokio::test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn forged_grants_are_confined_and_the_approved_kind_is_reserved() { + if !aien_omega_compose::LINKED { + return; + } + let dir = TempDir::new().unwrap(); + let root = std::fs::canonicalize(dir.path()).unwrap(); + let ws = root.join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let w = ws.to_str().unwrap().to_string(); + // The only test in this file: the env var is process-wide. + std::env::set_var("AIEN_COMPOSE_DIR", root.join("compose")); + let c = start(&dir).await; + + // A proposal digest no compose run ever produced. + let psha = sha(b"never proposed by any approved compose"); + let content = b"forged\n"; + let csha = sha(content); + let target = ws.join("NOTES.md").to_string_lossy().to_string(); + let grant = |path: &str, target: &str, ws: Option<&str>| { + let mut g = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, + "approver": "attacker", "target": target, "prior_sha256": null}); + if let Some(w) = ws { + g["workspace"] = json!(w); + } + g + }; + + // A1 as found: a grant that names no workspace is refused. + refused( + note(&c, "authorization", grant("NOTES.md", &target, None)).await, + "must name its workspace", + ); + + // A1b: target outside the workspace, in every shape. + let outside = root.join("outside.txt").to_string_lossy().to_string(); + refused( + note(&c, "authorization", grant("NOTES.md", &outside, Some(&w))).await, + "OutsideWorkspace", + ); + refused( + note( + &c, + "authorization", + grant("../outside.txt", &outside, Some(&w)), + ) + .await, + "OutsideWorkspace", + ); + refused( + note( + &c, + "authorization", + grant("etc/passwd", "/etc/passwd", Some("/")), + ) + .await, + "OutsideWorkspace", + ); + // A symlinked file and a symlinked directory inside the workspace. + std::fs::write(&outside, "outside\n").unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("link.txt")).unwrap(); + let lt = ws.join("link.txt").to_string_lossy().to_string(); + refused( + note(&c, "authorization", grant("link.txt", <, Some(&w))).await, + "OutsideWorkspace", + ); + let elsewhere = root.join("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, ws.join("sub")).unwrap(); + let st = ws.join("sub/x.txt").to_string_lossy().to_string(); + refused( + note(&c, "authorization", grant("sub/x.txt", &st, Some(&w))).await, + "OutsideWorkspace", + ); + + // The approved grant kind cannot be forged through ComposeNote. + let mut fake = grant("NOTES.md", &target, Some(&w)); + fake["approved_grant"] = json!(1); + fake["approval_key"] = json!("0".repeat(64)); + fake["replay_claim"] = json!(1); + fake["cx_promotion"] = json!(1); + fake["cx_evidence"] = json!(1); + refused(note(&c, "authorization", fake).await, "approved_grant"); + + // A grant written while its target was inside, retargeted at the intent: + // the intent names a target outside -> refused (no intent record). + let ok = match note(&c, "authorization", grant("NOTES.md", &target, Some(&w))).await { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("in-workspace generic grant: {other:?}"), + }; + refused( + intent(&c, ok, &psha, "NOTES.md", &outside, &csha).await, + "NotAuthorized", + ); + // The target swapped for a symlink after the grant: refused at the intent + // (the target read refuses a non-regular file before confinement does). + std::os::unix::fs::symlink(&outside, &target).unwrap(); + refused( + intent(&c, ok, &psha, "NOTES.md", &target, &csha).await, + "EFFECT_REFUSED", + ); + std::fs::remove_file(&target).unwrap(); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), "outside\n"); + + // STILL OPEN (sc#261): the generic grant inside the named workspace opens. + let i = match intent(&c, ok, &psha, "NOTES.md", &target, &csha).await { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("generic grant intent: {other:?}"), + }; + std::fs::write(&target, content).unwrap(); + let ack = match c + .send_command(ControlCommand::ComposeEffectAck { + intent: i, + reported: json!({"wrote": true}), + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("ack: {other:?}"), + }; + let state = match c + .send_command(ControlCommand::ComposeRecall { + ids: vec![ack], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(r) => { + serde_json::from_str::(r.cited[0].text.as_deref().unwrap()).unwrap() + ["state"] + .as_str() + .unwrap() + .to_string() + } + other => panic!("recall: {other:?}"), + }; + eprintln!("A1 generic path (sc#261, still open to same-user callers): {state}"); + assert_eq!(state, "DONE", "observed behaviour changed: update sc#261"); + + // 476ca4 c28 shape: the target's parent directory is swapped for a symlink + // to a directory outside the workspace after the intent opened, and the + // bytes land there. Ack and reconcile re-run the confinement: UNRESOLVED, + // never DONE, and an operator cannot declare it DONE. + std::fs::create_dir_all(ws.join("swp1")).unwrap(); + std::fs::create_dir_all(ws.join("swp2")).unwrap(); + let outdir = root.join("outdir"); + std::fs::create_dir_all(&outdir).unwrap(); + let recall_state = |id: u64| { + let c = &c; + async move { + match c + .send_command(ControlCommand::ComposeRecall { + ids: vec![id], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(r) => { + serde_json::from_str::(r.cited[0].text.as_deref().unwrap()) + .unwrap() + } + other => panic!("recall: {other:?}"), + } + } + }; + let swap = |d: &str| { + std::fs::rename(ws.join(d), ws.join(format!("{d}-moved"))).unwrap(); + std::os::unix::fs::symlink(&outdir, ws.join(d)).unwrap(); + std::fs::write(outdir.join("NOTES.md"), content).unwrap(); + }; + // (a) ack by the live executor. + let t1 = ws.join("swp1/NOTES.md").to_string_lossy().to_string(); + let g1 = match note(&c, "authorization", grant("swp1/NOTES.md", &t1, Some(&w))).await { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("swp1 grant: {other:?}"), + }; + let i1 = match intent(&c, g1, &psha, "swp1/NOTES.md", &t1, &csha).await { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("swp1 intent: {other:?}"), + }; + swap("swp1"); + let a1 = match c + .send_command(ControlCommand::ComposeEffectAck { + intent: i1, + reported: json!({"wrote": true}), + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("ack: {other:?}"), + }; + let v = recall_state(a1).await; + assert_eq!(v["state"], "UNRESOLVED", "{v}"); + assert!( + v["disk_error"] + .as_str() + .unwrap() + .starts_with("OutsideWorkspace"), + "{v}" + ); + // (b) start-up style reconcile of an intent whose executor is gone. + let t2 = ws.join("swp2/NOTES.md").to_string_lossy().to_string(); + let g2 = match note(&c, "authorization", grant("swp2/NOTES.md", &t2, Some(&w))).await { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("swp2 grant: {other:?}"), + }; + let i2 = match c + .send_command(ControlCommand::ComposeEffectIntent { + authorization: g2, + proposal_sha256: psha.clone(), + path: "swp2/NOTES.md".into(), + target: t2.clone(), + content_sha256: csha.clone(), + executor_pid: 1, + executor_start: 1, + }) + .await + .unwrap() + { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("swp2 intent: {other:?}"), + }; + swap("swp2"); + let declared = c + .send_command(ControlCommand::ComposeReconcile { + declare: Some(aien_runtime::control::ReconcileDeclare { + intent: i2, + state: "done".into(), + approver: "drake".into(), + }), + }) + .await + .unwrap(); + refused(declared, "cannot be declared DONE"); + let rec = match c + .send_command(ControlCommand::ComposeReconcile { declare: None }) + .await + .unwrap() + { + ControlResponse::ComposeReconciled(r) => *r, + other => panic!("reconcile: {other:?}"), + }; + let o = rec + .outcomes + .iter() + .find(|o| o.intent == i2) + .expect("reconciled i2"); + assert_eq!(o.state, "UNRESOLVED", "{o:?}"); + assert!( + rec.outcomes + .iter() + .all(|o| o.intent != i1 || o.state != "DONE"), + "{rec:?}" + ); +} diff --git a/crates/aien-runtime/tests/approved_crash_test.rs b/crates/aien-runtime/tests/approved_crash_test.rs new file mode 100644 index 00000000..852c1206 --- /dev/null +++ b/crates/aien-runtime/tests/approved_crash_test.rs @@ -0,0 +1,215 @@ +//! #249 B crash boundaries of the approved-proposal path, with a real process +//! crash: a child process (this test binary, re-run on the hidden helper +//! test) submits one approved proposal and aborts at a fault-hold point; the +//! parent then opens the same compose home as a restarted daemon would +//! (start-up replay reconcile) and retries. +//! +//! approved_after_claim boundary 1: accepted, dies before compose +//! approved_after_compose boundary 2: the World committed, dies before the +//! replay commit record +//! approved_after_commit boundary 3: the replay claim committed, dies +//! before the daemon's grant record +//! +//! Needs the `fault-hold` feature (test builds only): +//! `cargo test -p aien-runtime --features fault-hold --test approved_crash_test`. +#![cfg(feature = "fault-hold")] +use aien_omega_compose::hex; +use aien_runtime::approved::{ApprovedProposal, ProposerHook}; +use aien_runtime::approved_auth::{desk_key_path, DeskKey}; +use aien_runtime::approved_replay; +use aien_runtime::control::{ComposeRecallReport, ControlResponse}; +use aien_runtime::effects::Ledger; +use aien_runtime::spine::{ComposeBridge, ComposeProposer}; +use sha2::{Digest, Sha256}; +use std::path::Path; +use std::sync::Arc; + +const PATH: &str = "NOTES.md"; +const CONTENT: &str = "approved by the INTERPLANE desk\n"; + +fn never() -> ComposeProposer { + Arc::new(|_: &str, _: std::time::Duration| panic!("model proposer ran on the hook path")) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn proposal(b: &ComposeBridge) -> ApprovedProposal { + let mut p = ApprovedProposal { + request_id: "req-crash".into(), + trace_id: "trace-crash".into(), + approval_id: "appr-crash".into(), + approver: "interplane-host".into(), + path: PATH.into(), + content: CONTENT.into(), + approved_proposal_sha256: aien_runtime::approved::approved_proposal_sha256(PATH, CONTENT), + content_sha256: sha(CONTENT.as_bytes()), + approval_mac: String::new(), + }; + p.approval_mac = DeskKey::load(&desk_key_path(b.dir())) + .unwrap() + .sign(&p, &b.dir().parent().unwrap().join("ws")); + p +} + +fn recalled(b: &ComposeBridge) -> ComposeRecallReport { + match b.recall(&[], None) { + ControlResponse::ComposeRecalled(r) => *r, + other => panic!("recall: {other:?}"), + } +} + +/// Hidden helper: the child. Does nothing unless the parent set the env. +#[test] +#[ignore] +fn crash_child() { + let (Ok(dir), Ok(ws)) = (std::env::var("CRASH_DIR"), std::env::var("CRASH_WS")) else { + return; + }; + let b = Arc::new(ComposeBridge::new(dir.into(), never(), "t")); + let hook = ProposerHook::new(b.clone()); + let out = hook.submit(&proposal(&b), &ws); + // Reaching here means the hold point did not fire. + panic!("child was not stopped at its hold point: {out:?}"); +} + +fn run_child(hold: &str, dir: &Path, ws: &Path) { + let st = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "crash_child", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("AIEN_FAULT_HOLD", hold) + .env("CRASH_DIR", dir) + .env("CRASH_WS", ws) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .unwrap(); + use std::os::unix::process::ExitStatusExt; + assert_eq!( + st.signal(), + Some(libc_sigabrt()), + "child must abort at {hold}: {st:?}" + ); +} + +fn libc_sigabrt() -> i32 { + 6 +} + +/// Replay claims (`accepted` records) in the journal. +fn claims(r: &ComposeRecallReport) -> usize { + r.host + .iter() + .filter(|h| { + h.text + .as_deref() + .is_some_and(|t| t.contains("\"approved_submission\":\"accepted\"")) + }) + .count() +} + +static HOMES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn boundary(hold: &str, want_reconciled: &str, want_refusal: Option<&str>) { + let _turn = HOMES.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let dir = tmp.path().join("compose"); + DeskKey::create(&desk_key_path(&dir)).unwrap(); + run_child(hold, &dir, &ws); + + // The restarted daemon: a fresh bridge, start-up reconcile first. + let b = Arc::new(ComposeBridge::new(dir.clone(), never(), "t")); + let line = approved_replay::reconcile_at_start(&b).unwrap(); + assert!(line.contains(want_reconciled), "{line}"); + let before = recalled(&b); + assert_eq!(claims(&before), 1, "the child claimed once"); + // Any compose run appends goal, candidate, evidence and promotion + // records: an unchanged total proves nothing ran again. + let total = before.records_total; + + // Retry of the same approval and replays under either id: refused, never run. + let hook = ProposerHook::new(b.clone()); + let p = proposal(&b); + match (hook.submit(&p, ws.to_str().unwrap()), want_refusal) { + (Err(e), Some(want)) => { + assert_eq!(e.name, want, "{e}"); + assert_eq!(e.refused_by, "REPLAY_REFUSED"); + } + // Committed before the crash: the same approval gets the original + // result back, and no grant (the daemon never wrote one). + (Ok(r), None) => { + assert_eq!(r.state, "ALREADY_COMMITTED"); + assert!(r.task.is_none() && r.approved_grant.is_none()); + } + (other, want) => panic!("want {want:?}, got {other:?}"), + } + let want_refusal = want_refusal.unwrap_or("AlreadyCommitted"); + let mut q = p.clone(); + q.request_id = "req-crash-2".into(); + q.approval_mac = DeskKey::load(&desk_key_path(&dir)).unwrap().sign(&q, &ws); + assert_eq!( + hook.submit(&q, ws.to_str().unwrap()).unwrap_err().name, + want_refusal + ); + let after = recalled(&b); + assert_eq!( + after.records_total, total, + "a refused retry appended records" + ); + // No effect: no grant, no intent, nothing on disk. + let l = Ledger::from_records(&after.host).unwrap(); + assert!(l.grants.is_empty() && l.intents.is_empty()); + assert!(!ws.join(PATH).exists()); +} + +/// Boundary 1: accepted, the process dies before compose. After restart the +/// claim is NOT_EXECUTED and the approval stays consumed (a new approval is +/// needed); nothing ran. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn crash_after_claim_is_consumed_never_run() { + if !aien_omega_compose::LINKED { + return; + } + boundary( + "approved_after_claim", + "1 -> NOT_EXECUTED", + Some("AlreadyConsumed"), + ); +} + +/// Boundary 2: the World committed, the process dies before the replay commit +/// record. After restart the claim is UNCERTAIN (recorded), every retry is +/// refused: no second World commit, no effect. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn crash_after_compose_is_uncertain_never_rerun() { + if !aien_omega_compose::LINKED { + return; + } + boundary( + "approved_after_compose", + "1 -> UNCERTAIN", + Some("Uncertain"), + ); +} + +/// Boundary 3: the replay claim committed, the process dies before the +/// daemon's grant is written. After restart the approval is spent and no +/// grant exists, so no effect is possible: a new approval is needed. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn crash_before_grant_leaves_no_effect_possible() { + if !aien_omega_compose::LINKED { + return; + } + boundary("approved_after_commit", "", None); +} diff --git a/crates/aien-runtime/tests/approved_daemon_ipc_test.rs b/crates/aien-runtime/tests/approved_daemon_ipc_test.rs new file mode 100644 index 00000000..4c66afb6 --- /dev/null +++ b/crates/aien-runtime/tests/approved_daemon_ipc_test.rs @@ -0,0 +1,248 @@ +//! #249 C: `ComposeApprovedProposal` over the daemon socket (the production +//! entry), against the real server: an authenticated approval commits; a +//! forged approver is refused with nothing appended; replay records cannot be +//! forged through `ComposeNote` (so a forgery can neither consume nor +//! validate an approval); after a daemon restart over the same compose home +//! every replay is refused and the same approval's retry gets the original +//! result back without a second run. One test per binary (it sets +//! AIEN_COMPOSE_DIR). +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_omega_compose::hex; +use aien_runtime::approved::{approved_proposal_sha256, ApprovedProposal}; +use aien_runtime::approved_auth::{desk_key_path, DeskKey}; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::path::Path; +use std::time::Duration; + +const PATH: &str = "NOTES.md"; +const CONTENT: &str = "approved through the daemon\n"; + +fn signed(dir: &Path, request: &str, approval: &str, approver: &str) -> ApprovedProposal { + let mut p = ApprovedProposal { + request_id: request.into(), + trace_id: format!("trace-{request}"), + approval_id: approval.into(), + approver: approver.into(), + path: PATH.into(), + content: CONTENT.into(), + approved_proposal_sha256: approved_proposal_sha256(PATH, CONTENT), + content_sha256: hex(&Sha256::digest(CONTENT.as_bytes())), + approval_mac: String::new(), + }; + p.approval_mac = DeskKey::load(&desk_key_path(dir)) + .unwrap() + .sign(&p, &dir.parent().unwrap().join("ws")); + p +} + +async fn start( + socket: &Path, +) -> ( + AienRuntimeClient, + tokio::task::JoinHandle>, +) { + let cfg = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16)); + let server = AienRuntimeServer::new(spine, socket); + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(socket); + for _ in 0..200 { + if client.is_alive().await { + return (client, handle); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +async fn submit(c: &AienRuntimeClient, p: &ApprovedProposal, ws: &Path) -> ControlResponse { + c.send_command(ControlCommand::ComposeApprovedProposal { + proposal: p.clone(), + workspace: ws.display().to_string(), + }) + .await + .unwrap() +} + +async fn records(c: &AienRuntimeClient) -> u64 { + match c + .send_command(ControlCommand::ComposeRecall { + ids: vec![], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(r) => r.records_total, + other => panic!("recall: {other:?}"), + } +} + +async fn note(c: &AienRuntimeClient, kind: &str, text: serde_json::Value) -> ControlResponse { + c.send_command(ControlCommand::ComposeNote { + kind: kind.into(), + text: text.to_string(), + links: vec![], + }) + .await + .unwrap() +} + +fn refusal(r: ControlResponse) -> (String, String) { + match r { + ControlResponse::ComposeApprovedRefused(e) => (e.refused_by.clone(), e.name.clone()), + other => panic!("want a refusal, got {other:?}"), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn approved_proposal_over_the_daemon_socket() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("compose"); + std::env::set_var("AIEN_COMPOSE_DIR", &dir); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + DeskKey::create(&desk_key_path(&dir)).unwrap(); + let socket = tmp.path().join("runtime.sock"); + let (c, handle) = start(&socket).await; + + // Before anything: forged approver (correct bytes, hashes and the MAC of + // the honest approval) is refused, nothing appended. + let good = signed(&dir, "req-1", "appr-1", "interplane-host"); + let mut forged = good.clone(); + forged.approver = "drake".into(); + let out = submit(&c, &forged, &ws).await; + assert_eq!( + refusal(out), + ("PROPOSAL_REFUSED".into(), "Unauthenticated".into()) + ); + if !aien_omega_compose::LINKED { + // Stub build: the authenticated proposal is refused at the claim. + let (by, _) = refusal(submit(&c, &good, &ws).await); + assert_eq!(by, "REPLAY_REFUSED"); + let _ = c.send_command(ControlCommand::Shutdown).await; + return; + } + // The forgery opened the home only to read nothing: no record written. + let n0 = records(&c).await; + + // Replay records cannot be forged through ComposeNote: neither a claim + // (which would consume req-2/appr-2) nor a commit. + for text in [ + json!({"approved_submission": "accepted", "approval_key": "0".repeat(64), + "request_id": "req-2", "approval_id": "appr-2", "trace_id": "trace-req-2", + "executor": {"pid": 1, "start": 1}}), + json!({"approved_submission": "committed", "claim": 1, + "evidence": {"compose_proposal_sha256": "x", "cx_promotion": 1, "cx_evidence": 1, "task": 1}}), + ] { + match note(&c, "effect", text).await { + ControlResponse::Error(e) => assert!(e.contains("approved_submission"), "{e}"), + other => panic!("forged replay record accepted: {other:?}"), + } + } + // Under another kind the field is plain text: written, but never read as a claim. + match note( + &c, + "constraint", + json!({"approved_submission": "accepted", "request_id": "req-2", "approval_id": "appr-2"}), + ) + .await + { + ControlResponse::ComposeNoted(_) => {} + other => panic!("constraint note: {other:?}"), + } + assert_eq!(records(&c).await, n0 + 1); + + // The authenticated approval commits through the production path. + let first = match submit(&c, &good, &ws).await { + ControlResponse::ComposeApprovedResult(r) => *r, + other => panic!("want COMMITTED, got {other:?}"), + }; + assert_eq!(first.state, "COMMITTED"); + assert_eq!( + ( + first.request_id.as_str(), + first.trace_id.as_str(), + first.approval_id.as_str() + ), + ("req-1", "trace-req-1", "appr-1") + ); + let t = first.task.as_ref().unwrap(); + assert!(t.committed && t.aegis_pass_mask & 1 == 1 && t.cx_promotion != 0); + assert_eq!(first.grant_links, vec![t.cx_promotion, t.cx_evidence]); + // The daemon wrote the one grant for this approval, confined to the workspace. + assert!(first.approved_grant.is_some()); + assert_eq!( + first.target.as_deref().map(Path::new), + Some(std::fs::canonicalize(&ws).unwrap().join(PATH).as_path()) + ); + assert!(!ws.join(PATH).exists(), "the command writes nothing"); + // The forged notes did not consume req-2/appr-2. + let second = signed(&dir, "req-2", "appr-2", "interplane-host"); + match submit(&c, &second, &ws).await { + ControlResponse::ComposeApprovedResult(r) => assert_eq!(r.state, "COMMITTED"), + other => panic!("req-2 must commit: {other:?}"), + } + // Replay in the same daemon. + let n1 = records(&c).await; + match submit(&c, &good, &ws).await { + ControlResponse::ComposeApprovedResult(r) => { + assert_eq!(r.state, "ALREADY_COMMITTED"); + assert!(r.task.is_none()); + } + other => panic!("{other:?}"), + } + assert_eq!( + refusal(submit(&c, &signed(&dir, "req-3", "appr-1", "interplane-host"), &ws).await), + ("REPLAY_REFUSED".into(), "AlreadyCommitted".into()) + ); + assert_eq!(records(&c).await, n1); + + // Daemon restart over the same compose home. + let _ = c.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; + let socket2 = tmp.path().join("runtime2.sock"); + let (c2, handle2) = start(&socket2).await; + let n2 = records(&c2).await; + match submit(&c2, &good, &ws).await { + ControlResponse::ComposeApprovedResult(r) => { + assert_eq!(r.state, "ALREADY_COMMITTED"); + assert_eq!(r.compose_proposal_sha256, first.compose_proposal_sha256); + assert_eq!(r.grant_links, first.grant_links); + } + other => panic!("{other:?}"), + } + for p in [ + signed(&dir, "req-1", "appr-9", "interplane-host"), + signed(&dir, "req-9", "appr-1", "interplane-host"), + signed(&dir, "req-2", "appr-2", "another-approver"), + ] { + let (by, name) = refusal(submit(&c2, &p, &ws).await); + assert_eq!( + (by.as_str(), name.as_str()), + ("REPLAY_REFUSED", "AlreadyCommitted") + ); + } + assert_eq!( + records(&c2).await, + n2, + "a replay after restart appended records" + ); + let _ = c2.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), handle2).await; +} diff --git a/crates/aien-runtime/tests/approved_proposal_test.rs b/crates/aien-runtime/tests/approved_proposal_test.rs index 133199c9..a2e44562 100644 --- a/crates/aien-runtime/tests/approved_proposal_test.rs +++ b/crates/aien-runtime/tests/approved_proposal_test.rs @@ -1,11 +1,16 @@ //! Proposer hook (crate::approved): an approved proposal goes through the //! production compose run (J-Space branch, AEGIS verify, World commit) and -//! then the durable effect ledger; unverified and duplicate proposals are -//! refused with nothing appended. CPU only, no model, no socket: the bridge -//! is driven exactly as the daemon drives it. In a stub build only the -//! refusal paths run. +//! then the durable effect ledger; unverified, unauthenticated (#249 A) and +//! replayed (#249 B) proposals are refused with no compose run. CPU only, no +//! model, no socket: the bridge is driven exactly as the daemon drives it. In +//! a stub build only the refusal paths run. use aien_omega_compose::hex; -use aien_runtime::approved::{self, ApprovedProposal, ProposerHook}; +use aien_runtime::approved::{ + self, ApprovedComposeReport, ApprovedProposal, ApprovedRefusal, ProposerHook, +}; +use aien_runtime::approved_auth::{ + approval_key, canonical_workspace, desk_key_path, ApprovalIdentity, DeskKey, +}; use aien_runtime::control::{ComposeRecallReport, ControlResponse}; use aien_runtime::effects::{self, IntentRequest, Ledger}; use aien_runtime::spine::{ComposeBridge, ComposeProposer, APPROVED_PROPOSER_LABEL}; @@ -37,7 +42,8 @@ fn interplane_sha(path: &str, content: &str) -> String { sha(s.as_bytes()) } -fn proposal(request: &str, approval: &str) -> ApprovedProposal { +/// Unsigned: tests sign with [`sign`] after any edit. +fn unsigned(request: &str, approval: &str) -> ApprovedProposal { ApprovedProposal { request_id: request.into(), trace_id: format!("trace-{request}"), @@ -47,9 +53,31 @@ fn proposal(request: &str, approval: &str) -> ApprovedProposal { content: CONTENT.into(), approved_proposal_sha256: interplane_sha(PATH, CONTENT), content_sha256: sha(CONTENT.as_bytes()), + approval_mac: String::new(), } } +/// The desk key of a compose home (the test is the desk). +fn desk(b: &ComposeBridge) -> DeskKey { + DeskKey::load(&desk_key_path(b.dir())).unwrap() +} + +/// The workspace every test home pairs with its compose home (`setup`: +/// `/compose` and `/ws`); the approval binds it. +fn ws_of(b: &ComposeBridge) -> std::path::PathBuf { + b.dir().parent().unwrap().join("ws") +} + +fn sign(b: &ComposeBridge, mut p: ApprovedProposal) -> ApprovedProposal { + p.approval_mac = desk(b).sign(&p, &ws_of(b)); + p +} + +/// Re-sign after editing fields (an honest desk approving the edited change). +fn resign(b: &ComposeBridge, p: &ApprovedProposal) -> ApprovedProposal { + sign(b, p.clone()) +} + fn recalled(b: &ComposeBridge, ids: &[u64]) -> ComposeRecallReport { match b.recall(ids, None) { ControlResponse::ComposeRecalled(r) => *r, @@ -57,16 +85,42 @@ fn recalled(b: &ComposeBridge, ids: &[u64]) -> ComposeRecallReport { } } -fn refused(r: Result, name: &str) { +fn refused( + r: Result>, + name: &str, +) -> Box { match r { - Err(e) => assert!( - e.starts_with(&format!("PROPOSAL_REFUSED {name}:")), - "want {name}, got {e}" - ), - Ok(v) => panic!("want PROPOSAL_REFUSED {name}, got {v:?}"), + Err(e) => { + assert_eq!(e.name, name, "want {name}, got {e}"); + e + } + Ok(v) => panic!("want refusal {name}, got {v:?}"), } } +/// Stub build: nothing opens the compose home, so the claim is refused. +fn stub_refused(r: Result>) { + let e = r.expect_err("stub build must refuse"); + assert!( + e.refused_by == "REPLAY_REFUSED" || e.name == "ComposeError", + "{e}" + ); +} + +fn committed(r: Result>) -> ApprovedComposeReport { + let r = r.unwrap_or_else(|e| panic!("want COMMITTED, got {e}")); + assert_eq!(r.state, "COMMITTED"); + r +} + +/// omega caps the compose homes one process may hold open (E_FULL): the +/// tests of this binary take turns. +static HOMES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn turn() -> std::sync::MutexGuard<'static, ()> { + HOMES.lock().unwrap_or_else(|e| e.into_inner()) +} + fn setup() -> (tempfile::TempDir, Arc, ProposerHook, String) { let tmp = tempfile::tempdir().unwrap(); let ws = tmp.path().join("ws"); @@ -76,31 +130,50 @@ fn setup() -> (tempfile::TempDir, Arc, ProposerHook, String) { model_never_called(), "test:model-never-called", )); + DeskKey::create(&desk_key_path(b.dir())).unwrap(); let hook = ProposerHook::new(b.clone()); let ws = ws.display().to_string(); (tmp, b, hook, ws) } #[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] fn approved_proposal_commits_then_effect_is_done() { + let _turn = turn(); let (_tmp, b, hook, ws) = setup(); - let out = hook.submit(&proposal("req-1", "appr-1"), &ws); + let p = sign(&b, unsigned("req-1", "appr-1")); + let out = hook.submit(&p, &ws); if !aien_omega_compose::LINKED { - refused(out, "ComposeError"); + stub_refused(out); return; } - let r = out.unwrap(); - // Correlation and both hash semantics, side by side. + let r = committed(out); + // Correlation unchanged, authentication and replay identity reported. assert_eq!( - (r.request_id.as_str(), r.trace_id.as_str()), - ("req-1", "trace-req-1") + ( + r.request_id.as_str(), + r.trace_id.as_str(), + r.approval_id.as_str() + ), + ("req-1", "trace-req-1", "appr-1") ); + let d = desk(&b); + assert_eq!(r.desk_key_id, d.id()); + assert_eq!( + r.approval_key, + approval_key(&ApprovalIdentity::of( + &p, + &canonical_workspace(&ws_of(&b)).unwrap(), + d.id() + )) + ); + assert!(r.replay_claim != 0); assert_eq!(r.approved_proposal_sha256, interplane_sha(PATH, CONTENT)); let text = format!("filename: {PATH}\n{CONTENT}"); assert_eq!(r.compose_proposal_sha256, sha(text.as_bytes())); assert_ne!(r.approved_proposal_sha256, r.compose_proposal_sha256); // The compose run: one J-Space branch, AEGIS pass, World commit. - let t = &r.task; + let t = r.task.as_ref().unwrap(); assert!(t.committed, "{t:?}"); assert_eq!((t.outcome, t.branch_count, t.winner), (1, 1, Some(0))); assert_eq!(t.aegis_pass_mask & 1, 1); @@ -118,15 +191,34 @@ fn approved_proposal_commits_then_effect_is_done() { let target = Path::new(&ws).join(PATH); assert!(!target.exists()); - // Effect: grant (named as aien compose authorize names it), intent, write, ack. - let tgt = target.display().to_string(); - let grant = json!({"proposal_sha256": r.compose_proposal_sha256, "path": r.path, - "content_sha256": r.content_sha256, "approver": r.approver, "target": tgt, - "prior_sha256": Value::Null}); - let a = match b.note("authorization", &grant.to_string(), &r.grant_links) { - ControlResponse::ComposeNoted(n) => n.id, - other => panic!("grant: {other:?}"), - }; + // Effect: the daemon's own grant (reserved, keyed on the compose hash, + // linked to promotion, evidence and the replay claim), intent, write, ack. + let a = r.approved_grant.expect("the daemon wrote the grant"); + let tgt = r.target.clone().expect("grant target"); + assert_eq!( + Path::new(&tgt), + std::fs::canonicalize(&ws).unwrap().join(PATH) + ); + let g = recalled(&b, &[a]); + assert!(g.cited[0].verified); + assert_eq!(g.cited[0].note.as_deref(), Some("authorization")); + for x in [t.cx_promotion, t.cx_evidence, r.replay_claim] { + assert!(g.cited[0].links.contains(&x), "{:?}", g.cited[0]); + } + let gv: Value = serde_json::from_str(g.cited[0].text.as_deref().unwrap()).unwrap(); + assert_eq!(gv["approved_grant"], 1); + assert_eq!(gv["proposal_sha256"], json!(r.compose_proposal_sha256)); + assert_eq!( + gv["approved_proposal_sha256"], + json!(r.approved_proposal_sha256) + ); + assert_eq!(gv["approval_key"], json!(r.approval_key)); + assert_eq!( + (gv["request_id"].as_str(), gv["trace_id"].as_str()), + (Some(r.request_id.as_str()), Some(r.trace_id.as_str())) + ); + assert_eq!(gv["prior_sha256"], Value::Null); + let target = Path::new(&tgt).to_path_buf(); let (pid, start) = effects::self_executor(); let req = IntentRequest { authorization: a, @@ -154,6 +246,7 @@ fn approved_proposal_commits_then_effect_is_done() { #[test] fn unverified_proposal_is_refused_with_zero_effects() { + let _turn = turn(); let (_tmp, b, hook, ws) = setup(); println!( "approved_proposal_test: compose LINKED={} (zero-journal assertions {})", @@ -166,6 +259,7 @@ fn unverified_proposal_is_refused_with_zero_effects() { ); let before = aien_omega_compose::LINKED.then(|| recalled(&b, &[]).records_total); let mut cases: Vec<(&str, ApprovedProposal)> = Vec::new(); + let proposal = |r: &str, a: &str| unsigned(r, a); let mut p = proposal("u1", "a1"); p.content_sha256 = sha(b"other bytes\n"); cases.push(("content sha mismatch", p)); @@ -189,7 +283,8 @@ fn unverified_proposal_is_refused_with_zero_effects() { p.request_id = String::new(); cases.push(("no request id", p)); for (what, p) in &cases { - let r = hook.submit(p, &ws); + // Signed by the desk: verification still refuses. + let r = hook.submit(&resign(&b, p), &ws); assert!(r.is_err(), "{what}: {r:?}"); refused(r, "Unverified"); } @@ -206,43 +301,286 @@ fn unverified_proposal_is_refused_with_zero_effects() { } } +/// Replay in the same process: the same approval again returns the original +/// result without a second run (ALREADY_COMMITTED); the request id or the +/// approval id under another approval is refused; nothing is appended. #[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] fn duplicate_proposal_is_refused() { + let _turn = turn(); let (_tmp, b, hook, ws) = setup(); - let first = hook.submit(&proposal("req-d", "appr-d"), &ws); + let p = sign(&b, unsigned("req-d", "appr-d")); + let first = hook.submit(&p, &ws); if !aien_omega_compose::LINKED { - refused(first, "ComposeError"); - // Consumed before the run: the replay is refused even in a stub build. - refused(hook.submit(&proposal("req-d", "appr-d"), &ws), "Duplicate"); + stub_refused(first); + stub_refused(hook.submit(&p, &ws)); return; } - assert!(first.unwrap().task.committed); + let first = committed(first); let n = recalled(&b, &[]).records_total; - refused(hook.submit(&proposal("req-d", "appr-d"), &ws), "Duplicate"); - refused( - hook.submit(&proposal("req-other", "appr-d"), &ws), - "Duplicate", + let again = hook.submit(&p, &ws).unwrap(); + assert_eq!(again.state, "ALREADY_COMMITTED"); + assert!(again.task.is_none()); + assert_eq!(again.compose_proposal_sha256, first.compose_proposal_sha256); + assert_eq!(again.grant_links, first.grant_links); + assert_eq!(again.replay_claim, first.replay_claim); + // Same approval id, new request (desk-signed): refused, not "already committed". + let e = refused( + hook.submit(&sign(&b, unsigned("req-other", "appr-d")), &ws), + "AlreadyCommitted", ); + assert_eq!(e.refused_by, "REPLAY_REFUSED"); + assert_eq!(e.replay_claim, Some(first.replay_claim)); refused( - hook.submit(&proposal("req-d", "appr-other"), &ws), - "Duplicate", + hook.submit(&sign(&b, unsigned("req-d", "appr-other")), &ws), + "AlreadyCommitted", ); + // Same ids, another trace: refused too. + let mut t = unsigned("req-d", "appr-d"); + t.trace_id = "trace-other".into(); + refused(hook.submit(&sign(&b, t), &ws), "AlreadyCommitted"); assert_eq!( recalled(&b, &[]).records_total, n, - "a duplicate appended records" + "a replay appended records" ); // The same change under a fresh request and approval is a new proposal. - assert!( - hook.submit(&proposal("req-e", "appr-e"), &ws) - .unwrap() - .task - .committed + committed(hook.submit(&sign(&b, unsigned("req-e", "appr-e")), &ws)); +} + +/// #249 A: a caller without the desk key cannot make the hook trust any +/// field. Every variant is refused Unauthenticated before anything runs: +/// zero records, nothing on disk. +#[test] +fn unauthenticated_approval_is_refused_with_no_compose() { + let _turn = turn(); + let (tmp, b, hook, ws) = setup(); + let good = sign(&b, unsigned("req-a", "appr-a")); + let before = aien_omega_compose::LINKED.then(|| recalled(&b, &[]).records_total); + let mut cases: Vec<(&str, ApprovedProposal)> = Vec::new(); + let mut p = good.clone(); + p.approver = "drake".into(); + cases.push(("forged approver, correct bytes and hashes", p)); + let mut p = good.clone(); + p.request_id = "req-a2".into(); + cases.push(("changed request_id", p)); + let mut p = good.clone(); + p.trace_id = "trace-x".into(); + cases.push(("changed trace_id", p)); + let mut p = good.clone(); + p.approval_id = "appr-a2".into(); + cases.push(("changed approval_id", p)); + let mut p = good.clone(); + p.path = "OTHER.md".into(); + p.approved_proposal_sha256 = interplane_sha(&p.path, &p.content); + cases.push(("changed path, hashes recomputed", p)); + let mut p = good.clone(); + p.content = "other approved bytes\n".into(); + p.content_sha256 = sha(p.content.as_bytes()); + p.approved_proposal_sha256 = interplane_sha(PATH, &p.content); + cases.push(("changed content, hashes recomputed", p)); + let mut p = good.clone(); + p.approval_mac = String::new(); + cases.push(("no MAC", p)); + let mut p = good.clone(); + p.approval_mac = sha(b"caller text is not approval"); + cases.push(("MAC made of caller text", p)); + let other = DeskKey::create(&tmp.path().join("other.key")).unwrap(); + let mut p = good.clone(); + p.approval_mac = other.sign(&p, &ws_of(&b)); + cases.push(("MAC under another key", p)); + let mut p = good.clone(); + p.approval_mac = p.approval_mac.to_uppercase(); + cases.push(("MAC in another hex case", p)); + for (what, p) in &cases { + let e = refused(hook.submit(p, &ws), "Unauthenticated"); + assert_eq!(e.refused_by, "PROPOSAL_REFUSED", "{what}"); + assert_eq!(e.request_id, p.request_id, "{what}: correlation kept"); + } + assert!(!Path::new(&ws).join(PATH).exists()); + if let Some(n) = before { + assert_eq!( + recalled(&b, &[]).records_total, + n, + "a refusal appended records" + ); + // The honest approval was not consumed by the forgeries. + committed(hook.submit(&good, &ws)); + } +} + +/// #249 A key rules: absent, group/other-readable, symlinked or malformed +/// keys are refused NoDesk; refusals and reports never carry the key. +#[test] +fn desk_key_file_rules() { + let _turn = turn(); + use std::os::unix::fs::PermissionsExt; + let (tmp, b, hook, ws) = setup(); + let path = desk_key_path(b.dir()); + let key_text = std::fs::read_to_string(&path).unwrap(); + let p = sign(&b, unsigned("req-k", "appr-k")); + for mode in [0o640, 0o604, 0o644] { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + let e = refused(hook.submit(&p, &ws), "NoDesk"); + assert!(e.detail.contains("group or other"), "{e}"); + assert!(!e.to_string().contains(key_text.trim())); + } + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + // A symlink to a well-formed 0600 key is refused. + let real = tmp.path().join("real.key"); + std::fs::rename(&path, &real).unwrap(); + std::os::unix::fs::symlink(&real, &path).unwrap(); + let e = refused(hook.submit(&p, &ws), "NoDesk"); + assert!(e.detail.contains("symlink"), "{e}"); + std::fs::remove_file(&path).unwrap(); + // Absent. + refused(hook.submit(&p, &ws), "NoDesk"); + // Malformed. + std::fs::write(&path, "not a key\n").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + refused(hook.submit(&p, &ws), "NoDesk"); + // create never overwrites. + assert!(DeskKey::create(&path).is_err()); + std::fs::remove_file(&path).unwrap(); + // Restored key: the MAC verifies again. Rotation: a new key refuses the old MAC. + std::fs::rename(&real, &path).unwrap(); + let k = desk(&b); + assert!(!format!("{k:?}").contains(key_text.trim())); + std::fs::remove_file(&path).unwrap(); + DeskKey::create(&path).unwrap(); + let e = refused(hook.submit(&p, &ws), "Unauthenticated"); + assert!(!e.to_string().contains(key_text.trim())); + if aien_omega_compose::LINKED { + let r = committed(hook.submit(&resign(&b, &p), &ws)); + assert!(!serde_json::to_string(&r).unwrap().contains(key_text.trim())); + assert_ne!(r.desk_key_id, k.id(), "rotation changes the key id"); + } +} + +/// #249 A confinement: a compose home (desk key, journal) inside the +/// workspace, or a workspace inside the compose home, refuses the desk. +#[test] +fn compose_home_overlapping_the_workspace_is_refused() { + let _turn = turn(); + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + let inner = ws.join(".aien-compose"); + std::fs::create_dir_all(&inner).unwrap(); + let b = Arc::new(ComposeBridge::new(inner.clone(), model_never_called(), "t")); + DeskKey::create(&desk_key_path(&inner)).unwrap(); + let hook = ProposerHook::new(b.clone()); + let p = sign(&b, unsigned("req-c", "appr-c")); + refused(hook.submit(&p, ws.to_str().unwrap()), "Confinement"); + // The other way round: the workspace inside the compose home. + let home = tmp.path().join("home"); + let ws2 = home.join("ws"); + std::fs::create_dir_all(&ws2).unwrap(); + let b2 = Arc::new(ComposeBridge::new(home.clone(), model_never_called(), "t")); + DeskKey::create(&desk_key_path(&home)).unwrap(); + let p2 = sign(&b2, unsigned("req-c", "appr-c")); + refused( + ProposerHook::new(b2).submit(&p2, ws2.to_str().unwrap()), + "Confinement", ); + // Nothing was ever opened: no journal in either home. + assert!(!inner.join("cortex.cx").exists() && !home.join("cortex.cx").exists()); +} + +/// #249 B, CENTRAL: a fresh bridge over the same compose home (what a +/// daemon restart is) refuses every replay; the retry of the same approval +/// gets the original result back and nothing runs again. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn replay_is_refused_after_restart() { + let _turn = turn(); + let (tmp, b, hook, ws) = setup(); + let p = sign(&b, unsigned("req-r", "appr-r")); + let first = hook.submit(&p, &ws); + if !aien_omega_compose::LINKED { + stub_refused(first); + return; + } + let first = committed(first); + drop(hook); + let dir = b.dir().to_path_buf(); + drop(b); + let b2 = Arc::new(ComposeBridge::new(dir, model_never_called(), "t")); + let hook2 = ProposerHook::new(b2.clone()); + let n = recalled(&b2, &[]).records_total; + let again = hook2.submit(&p, &ws).unwrap(); + assert_eq!(again.state, "ALREADY_COMMITTED"); + assert_eq!(again.compose_proposal_sha256, first.compose_proposal_sha256); + refused( + hook2.submit(&sign(&b2, unsigned("req-r2", "appr-r")), &ws), + "AlreadyCommitted", + ); + refused( + hook2.submit(&sign(&b2, unsigned("req-r", "appr-r2")), &ws), + "AlreadyCommitted", + ); + assert_eq!( + recalled(&b2, &[]).records_total, + n, + "a replay after restart appended records" + ); + let _ = tmp; +} + +/// #249 B: concurrent duplicates. Eight threads submit the same approval and +/// eight more submit new request ids under one approval id: exactly one +/// compose run per approval id. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn concurrent_duplicates_run_once() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + if !aien_omega_compose::LINKED { + return; + } + let hook = Arc::new(hook); + let same = sign(&b, unsigned("req-cc", "appr-cc")); + let mut handles = Vec::new(); + for i in 0..16 { + let (h, ws) = (hook.clone(), ws.clone()); + let p = if i < 8 { + same.clone() + } else { + sign(&b, unsigned(&format!("req-cc-{i}"), "appr-cc")) + }; + handles.push(std::thread::spawn(move || h.submit(&p, &ws))); + } + let outs: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect(); + let ran: Vec<_> = outs + .iter() + .filter_map(|o| o.as_ref().ok()) + .filter(|r| r.task.is_some()) + .collect(); + assert_eq!(ran.len(), 1, "exactly one submission runs: {outs:?}"); + for o in &outs { + match o { + Ok(r) => assert!(r.state == "COMMITTED" || r.state == "ALREADY_COMMITTED"), + Err(e) => assert!( + ["InFlight", "AlreadyCommitted"].contains(&e.name.as_str()), + "{e}" + ), + } + } + // One promotion in the journal for this approval: one World commit. + let host = recalled(&b, &[]).host; + let claims = host + .iter() + .filter(|r| { + r.text + .as_deref() + .is_some_and(|t| t.contains("\"approved_submission\":\"accepted\"")) + }) + .count(); + assert_eq!(claims, 1); } #[test] fn approved_hash_is_the_interplane_form() { + let _turn = turn(); assert_eq!( approved::approved_proposal_sha256("a/b.md", "x \"q\"\n\u{1}é\n"), interplane_sha("a/b.md", "x \"q\"\n\u{1}é\n") @@ -253,23 +591,26 @@ fn approved_hash_is_the_interplane_form() { /// and merge the reply into the seed (v7 T5). An approved whole-file /// proposal must commit byte-exact, with no seed line merged in. #[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] fn approved_proposal_over_existing_file_commits_byte_exact() { + let _turn = turn(); let (_tmp, _b, hook, ws) = setup(); let seed = "# Notes\nseed line one\nseed line two\n"; std::fs::write(Path::new(&ws).join(PATH), seed).unwrap(); // Shares "# Notes" with the seed, so an edit merge would keep both seed lines. let content = "# Notes\napproved replacement line\n"; - let mut p = proposal("req-x", "appr-x"); + let mut p = unsigned("req-x", "appr-x"); p.content = content.into(); p.content_sha256 = sha(content.as_bytes()); p.approved_proposal_sha256 = interplane_sha(PATH, content); + let p = sign(&_b, p); let out = hook.submit(&p, &ws); if !aien_omega_compose::LINKED { - refused(out, "ComposeError"); + stub_refused(out); return; } - let r = out.unwrap(); - let t = &r.task; + let r = committed(out); + let t = r.task.as_ref().unwrap(); assert!(t.committed, "{t:?}"); let text = format!("filename: {PATH}\n{content}"); assert_eq!(t.proposal.as_deref(), Some(text.as_str())); @@ -285,3 +626,85 @@ fn approved_proposal_over_existing_file_commits_byte_exact() { seed ); } + +/// 476ca4 c17: a valid approval presented with another workspace is refused +/// as Unauthenticated (the workspace is in the MAC), nothing is consumed, and +/// the same approval still commits for the workspace it was made for; the +/// daemon's grant targets the bound workspace. +#[test] +fn approval_redirected_to_another_workspace_is_refused() { + let _turn = turn(); + let (tmp, b, hook, ws) = setup(); + let other = tmp.path().join("elsewhere"); + std::fs::create_dir_all(&other).unwrap(); + // A symlink to the right workspace resolves to it: same canonical path. + let alias = tmp.path().join("ws-alias"); + std::os::unix::fs::symlink(&ws, &alias).unwrap(); + let p = sign(&b, unsigned("req-w", "appr-w")); + let before = aien_omega_compose::LINKED.then(|| recalled(&b, &[]).records_total); + for w in [other.to_str().unwrap(), "/", tmp.path().to_str().unwrap()] { + let e = hook.submit(&p, w).unwrap_err(); + assert!( + e.name == "Unauthenticated" || e.name == "Confinement", + "{w}: {e}" + ); + } + if let Some(n) = before { + assert_eq!(recalled(&b, &[]).records_total, n, "nothing consumed"); + } + assert!(!other.join(PATH).exists()); + let out = hook.submit(&p, alias.to_str().unwrap()); + if !aien_omega_compose::LINKED { + stub_refused(out); + return; + } + let r = committed(out); + assert_eq!( + r.target.as_deref().map(Path::new), + Some( + canonical_workspace(Path::new(&ws)) + .map(|w| Path::new(&w).join(PATH)) + .unwrap() + .as_path() + ) + ); +} + +/// 476ca4 c25: a journal-level byte copy of the daemon's grant (written past +/// ComposeNote's reserved check, as only direct journal access could) gives +/// one approval two grants: neither opens an intent, nothing is written. +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn copied_approved_grant_opens_nothing() { + let _turn = turn(); + let (_tmp, b, hook, ws) = setup(); + let r = committed(hook.submit(&sign(&b, unsigned("req-g", "appr-g")), &ws)); + let a = r.approved_grant.unwrap(); + let g = recalled(&b, &[a]); + let text = g.cited[0].text.clone().unwrap(); + let copy = match b.note("authorization", &text, &g.cited[0].links) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("bridge-level copy: {other:?}"), + }; + let (pid, start) = effects::self_executor(); + for id in [a, copy] { + let req = IntentRequest { + authorization: id, + proposal_sha256: r.compose_proposal_sha256.clone(), + path: r.path.clone(), + target: r.target.clone().unwrap(), + content_sha256: r.content_sha256.clone(), + executor_pid: pid, + executor_start: start, + }; + match effects::open_intent(&b, &req) { + ControlResponse::Error(e) => { + assert!(e.contains("more than one approved grant"), "#{id}: {e}") + } + other => panic!("#{id} opened: {other:?}"), + } + } + let l = Ledger::from_records(&recalled(&b, &[]).host).unwrap(); + assert!(l.intents.is_empty()); + assert!(!Path::new(&r.target.unwrap()).exists()); +} diff --git a/crates/aien-runtime/tests/approved_replay_test.rs b/crates/aien-runtime/tests/approved_replay_test.rs new file mode 100644 index 00000000..c624692a --- /dev/null +++ b/crates/aien-runtime/tests/approved_replay_test.rs @@ -0,0 +1,399 @@ +//! Replay ledger for approved proposals (crate::approved_replay, sovereign-core #249 part B). +//! Pure ledger rules run in every build; the journal tests need the linked +//! composition library and are IGNORED in a stub build (cfg compose_linked, set by +//! build.rs from aien-omega-compose's links metadata). +//! A "crashed" claim is made by a child process (this test binary re-run with +//! REPLAY_CHILD set) that claims and exits without settling. +use aien_runtime::approved_replay::{ + self as replay, ClaimKeys, ClaimState, CommitEvidence, ReplayLedger, FIELD, +}; +use aien_runtime::control::ComposeRecordView; +use aien_runtime::effects; +use aien_runtime::spine::{ComposeBridge, ComposeProposer}; +use serde_json::json; +use std::path::Path; +use std::sync::{Arc, Barrier}; + +fn proposer() -> ComposeProposer { + Arc::new(|_: &str, _: std::time::Duration| panic!("no model on the replay path")) +} + +fn bridge(dir: &Path) -> ComposeBridge { + ComposeBridge::new(dir.join("compose"), proposer(), "test:replay") +} + +fn keys(n: &str) -> ClaimKeys { + let k = format!( + "{:0>64}", + n.bytes().map(|b| format!("{:02x}", b)).collect::() + ); + ClaimKeys { + approval_key: k[k.len() - 64..].to_string(), + request_id: format!("req-{n}"), + approval_id: format!("appr-{n}"), + trace_id: format!("trace-{n}"), + } +} + +fn evidence() -> CommitEvidence { + CommitEvidence { + compose_proposal_sha256: "ab".repeat(32), + cx_promotion: 17, + cx_evidence: 15, + task: 99, + } +} + +fn refused_as(r: Result, name: &str) -> replay::Refusal { + match r { + Err(e) => { + assert_eq!(e.name, name, "want {name}, got {e}"); + assert!(e + .to_string() + .starts_with(&format!("REPLAY_REFUSED {name}:"))); + e + } + Ok(v) => panic!("want REPLAY_REFUSED {name}, got {v:?}"), + } +} + +// ---------- pure ledger rules (every build) ---------- + +fn view(id: u64, text: serde_json::Value) -> ComposeRecordView { + ComposeRecordView { + id, + cls: 0, + kind: 0, + subject: 0, + tag: 4, + links: vec![], + digest: String::new(), + verified: true, + note: Some("effect".into()), + text: Some(text.to_string()), + } +} + +fn accepted(id: u64, k: &ClaimKeys) -> ComposeRecordView { + // pid 0: an executor that is never alive (effects::executor_alive). + view( + id, + json!({FIELD: "accepted", "approval_key": k.approval_key, "request_id": k.request_id, + "approval_id": k.approval_id, "trace_id": k.trace_id, + "executor": {"pid": 0, "start": 0}}), + ) +} + +fn step(id: u64, claim: u64, phase: &str) -> ComposeRecordView { + view( + id, + json!({FIELD: phase, "claim": claim, "reason": "test", "evidence": evidence()}), + ) +} + +#[test] +fn ledger_lifecycle_and_refusal_names() { + let k = keys("a"); + let cases: Vec<(Vec, ClaimState, &str)> = vec![ + ( + vec![accepted(1, &k)], + ClaimState::Accepted, + "AlreadyConsumed", + ), + ( + vec![accepted(1, &k), step(2, 1, "in_flight")], + ClaimState::InFlight, + "Uncertain", + ), + ( + vec![ + accepted(1, &k), + step(2, 1, "in_flight"), + step(3, 1, "committed"), + ], + ClaimState::Committed, + "AlreadyCommitted", + ), + ( + vec![ + accepted(1, &k), + step(2, 1, "in_flight"), + step(3, 1, "failed"), + ], + ClaimState::Failed, + "AlreadyFailed", + ), + ( + vec![ + accepted(1, &k), + step(2, 1, "in_flight"), + step(3, 1, "uncertain"), + ], + ClaimState::Uncertain, + "Uncertain", + ), + ( + vec![accepted(1, &k), step(2, 1, "not_executed")], + ClaimState::NotExecuted, + "AlreadyConsumed", + ), + ]; + for (recs, state, name) in cases { + let l = ReplayLedger::from_records(&recs).unwrap(); + assert_eq!(l.claims[&1].state, state); + let r = l.check(&k).expect("claimed keys are refused"); + assert_eq!(r.name, name, "{state:?}"); + assert_eq!(r.claim, Some(1)); + assert_eq!(r.evidence.is_some(), state == ClaimState::Committed); + } +} + +#[test] +fn ledger_each_key_is_claimed_on_its_own() { + let k = keys("a"); + let l = ReplayLedger::from_records(&[accepted(1, &k)]).unwrap(); + let mut only_request = keys("b"); + only_request.request_id = k.request_id.clone(); + let mut only_approval = keys("c"); + only_approval.approval_id = k.approval_id.clone(); + let mut only_key = keys("d"); + only_key.approval_key = k.approval_key.clone(); + for (what, other) in [ + ("request", only_request), + ("approval", only_approval), + ("key", only_key), + ] { + assert!(l.check(&other).is_some(), "same {what} id must be refused"); + } + assert!(l.check(&keys("e")).is_none(), "fresh keys are free"); +} + +#[test] +fn ledger_refuses_corrupt_histories() { + let k = keys("a"); + let bad: Vec> = vec![ + vec![accepted(1, &k), accepted(2, &k)], // a key claimed twice + vec![accepted(1, &k), step(2, 1, "committed")], // committed without in_flight + vec![ + accepted(1, &k), + step(2, 1, "in_flight"), + step(3, 1, "not_executed"), + ], + vec![ + accepted(1, &k), + step(2, 1, "in_flight"), + step(3, 1, "committed"), + step(4, 1, "failed"), + ], + vec![step(2, 1, "in_flight")], // names no claim + vec![accepted(1, &k), step(2, 1, "bogus")], + ]; + for recs in bad { + let e = ReplayLedger::from_records(&recs).unwrap_err(); + assert_eq!(e.name, "CorruptLedger", "{e}"); + } + let mut unverified = accepted(1, &k); + unverified.verified = false; + assert_eq!( + ReplayLedger::from_records(&[unverified]).unwrap_err().name, + "CorruptLedger" + ); +} + +#[test] +fn compose_note_cannot_forge_replay_records() { + for phase in ["accepted", "in_flight", "committed", "declared"] { + let t = json!({FIELD: phase, "claim": 1}).to_string(); + assert!( + effects::check_reserved_note("effect", &t).is_err(), + "{phase}" + ); + } +} + +// ---------- journal (linked composition library) ---------- + +#[test] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +fn claim_is_durable_and_single_use_across_restart() { + let tmp = tempfile::tempdir().unwrap(); + let k = keys("restart"); + { + let b = bridge(tmp.path()); + let c = replay::claim(&b, &k).unwrap(); + // Same process, same keys: the running claim refuses. + refused_as(replay::claim(&b, &k), "InFlight"); + replay::mark_in_flight(&b, &c).unwrap(); + replay::commit(&b, &c, &evidence()).unwrap(); + // Lifecycle cannot go backwards or repeat. + refused_as(replay::commit(&b, &c, &evidence()), "WrongState"); + refused_as(replay::fail(&b, &c, "x"), "WrongState"); + } + // A new bridge on the same compose home = a daemon restart. + let b = bridge(tmp.path()); + assert!(replay::reconcile_at_start(&b) + .unwrap() + .contains("0 -> NOT_EXECUTED")); + let e = refused_as(replay::claim(&b, &k), "AlreadyCommitted"); + assert_eq!( + e.evidence, + Some(evidence()), + "a lost response can be recovered" + ); + for (what, changed) in [ + ( + "request", + ClaimKeys { + approval_key: keys("x").approval_key, + approval_id: "appr-x".into(), + ..k.clone() + }, + ), + ( + "approval", + ClaimKeys { + approval_key: keys("y").approval_key, + request_id: "req-y".into(), + ..k.clone() + }, + ), + ( + "key", + ClaimKeys { + request_id: "req-z".into(), + approval_id: "appr-z".into(), + ..k.clone() + }, + ), + ] { + refused_as(replay::claim(&b, &changed), "AlreadyCommitted"); + let _ = what; + } + // A fresh approval is accepted. + replay::claim(&b, &keys("fresh")).unwrap(); +} + +#[test] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +fn failed_and_not_executed_claims_stay_consumed() { + let tmp = tempfile::tempdir().unwrap(); + let b = bridge(tmp.path()); + let c = replay::claim(&b, &keys("ne")).unwrap(); + replay::not_executed(&b, &c, "authentication refused after claim").unwrap(); + refused_as(replay::claim(&b, &keys("ne")), "AlreadyConsumed"); + let c = replay::claim(&b, &keys("f")).unwrap(); + replay::mark_in_flight(&b, &c).unwrap(); + replay::fail(&b, &c, "World did not commit").unwrap(); + refused_as(replay::claim(&b, &keys("f")), "AlreadyFailed"); + let c = replay::claim(&b, &keys("u")).unwrap(); + replay::mark_in_flight(&b, &c).unwrap(); + replay::uncertain(&b, &c, "run returned an error").unwrap(); + refused_as(replay::claim(&b, &keys("u")), "Uncertain"); + replay::declare(&b, c.id, false, "operator", "World checked: no commit").unwrap(); + refused_as(replay::claim(&b, &keys("u")), "Uncertain"); + refused_as( + replay::declare(&b, c.id, true, "operator", "again"), + "WrongState", + ); +} + +#[test] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +fn concurrent_duplicates_at_most_one_claim() { + let tmp = tempfile::tempdir().unwrap(); + let b = Arc::new(bridge(tmp.path())); + let n = 16; + let gate = Arc::new(Barrier::new(n)); + let hs: Vec<_> = (0..n) + .map(|i| { + let (b, gate) = (b.clone(), gate.clone()); + std::thread::spawn(move || { + // Half the threads reuse only the request id, half the whole keys. + let mut k = keys("race"); + if i % 2 == 1 { + k.approval_key = keys(&format!("r{i}")).approval_key; + k.approval_id = format!("appr-r{i}"); + } + gate.wait(); + replay::claim(&b, &k) + }) + }) + .collect(); + let ok = hs + .into_iter() + .map(|h| h.join().unwrap()) + .filter(|r| r.is_ok()) + .count(); + assert_eq!(ok, 1, "exactly one concurrent claim wins"); +} + +/// Child mode: claim (and optionally go in flight), then exit without settling. +/// Run only by crash_child. +#[test] +#[ignore = "child mode, run by crash_before_and_during_execution_fail_closed"] +fn child_claim_then_crash() { + let Ok(mode) = std::env::var("REPLAY_CHILD") else { + return; + }; + let dir = std::env::var("REPLAY_DIR").unwrap(); + let b = bridge(Path::new(&dir)); + let c = replay::claim(&b, &keys(&mode)).unwrap(); + if mode == "inflight" { + replay::mark_in_flight(&b, &c).unwrap(); + } + std::process::exit(0); +} + +fn crash_child(dir: &Path, mode: &str) { + let st = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "child_claim_then_crash", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env("REPLAY_CHILD", mode) + .env("REPLAY_DIR", dir) + .status() + .unwrap(); + assert!(st.success(), "child {mode}: {st}"); +} + +#[test] +#[cfg_attr( + not(compose_linked), + ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)" +)] +fn crash_before_and_during_execution_fail_closed() { + let tmp = tempfile::tempdir().unwrap(); + crash_child(tmp.path(), "before"); + crash_child(tmp.path(), "inflight"); + let b = bridge(tmp.path()); + // Before the start-up reconcile: a gone process is never "in flight", and + // neither claim can be taken again. + refused_as(replay::claim(&b, &keys("before")), "AlreadyConsumed"); + refused_as(replay::claim(&b, &keys("inflight")), "Uncertain"); + let s = replay::reconcile_at_start(&b).unwrap(); + assert!( + s.contains("1 -> NOT_EXECUTED") && s.contains("1 -> UNCERTAIN"), + "{s}" + ); + refused_as(replay::claim(&b, &keys("before")), "AlreadyConsumed"); + refused_as(replay::claim(&b, &keys("inflight")), "Uncertain"); + // The reconcile is idempotent: nothing left to settle. + let s = replay::reconcile_at_start(&b).unwrap(); + assert!( + s.contains("0 -> NOT_EXECUTED") && s.contains("0 -> UNCERTAIN"), + "{s}" + ); +} diff --git a/crates/aien-runtime/tests/effects_test.rs b/crates/aien-runtime/tests/effects_test.rs index 75bf4e04..a03000c4 100644 --- a/crates/aien-runtime/tests/effects_test.rs +++ b/crates/aien-runtime/tests/effects_test.rs @@ -95,7 +95,8 @@ impl Fixture { let prior = effects::file_sha256(Path::new(&self.target)).unwrap(); let text = json!({"proposal_sha256": self.psha, "path": "NOTES.md", "content_sha256": self.csha, "approver": "drake", "target": self.target, - "prior_sha256": prior}); + "prior_sha256": prior, + "workspace": Path::new(&self.target).parent().unwrap().display().to_string()}); noted(b.note("authorization", &text.to_string(), &[])).id } @@ -124,6 +125,7 @@ fn effect_intents_are_at_most_once_or_unresolved() { let home = tmp.path().join("compose"); let ws = tmp.path().join("ws"); std::fs::create_dir_all(&ws).unwrap(); + let ws = std::fs::canonicalize(&ws).unwrap(); let b = ComposeBridge::new(home.clone(), proposer(), "test:fixed-proposer"); let run = b.run_task("write the note", ws.to_str().unwrap()); if !aien_omega_compose::LINKED { diff --git a/docs/COMPOSE_PROPOSER_HOOK.md b/docs/COMPOSE_PROPOSER_HOOK.md index 8c1126c9..1a57c40f 100644 --- a/docs/COMPOSE_PROPOSER_HOOK.md +++ b/docs/COMPOSE_PROPOSER_HOOK.md @@ -25,11 +25,107 @@ file change), the winner commits through the World, Cortex records goal, candidates, evidence and promotion (`cx_*` in `ComposeTaskReport`). The hook returns Ok only if the run committed exactly the approved text. -## What the ledger hands over (`ApprovedProposal`, approved.rs:39) +## What the ledger hands over (`ApprovedProposal`) request_id, trace_id, approval_id, approver, path, content, -approved_proposal_sha256, content_sha256. The hook returns -`ApprovedComposeReport` (approved.rs:57): the same ids plus -compose_proposal_sha256, grant_links and the compose `task` report. +approved_proposal_sha256, content_sha256, approval_mac. The hook returns +`ApprovedComposeReport`: state (COMMITTED | ALREADY_COMMITTED), the same +ids, compose_proposal_sha256, grant_links, desk_key_id, approval_key, +replay_claim and the compose `task` report (None for ALREADY_COMMITTED); or +`ApprovedRefusal` {refused_by, name, detail, request_id, trace_id, +approval_id, replay_claim}. + +## Daemon command (#249 C) +`ControlCommand::ComposeApprovedProposal { proposal, workspace }` on the +daemon socket (same-user peer check, 0600 socket, like every compose +command). Answered `ComposeApprovedResult(report)` or +`ComposeApprovedRefused(refusal)`. It runs `ProposerHook::submit`; there is +no unauthenticated variant. It writes nothing to the workspace. After the +replay commit the daemon itself writes the one grant for the approval +(`approved_grant` below) and returns its id (`approved_grant`) and target; +the caller then needs only `ComposeEffectIntent` and `ComposeEffectAck`, +both naming compose_proposal_sha256. A caller never writes its own grant +for an approved write. + +## Daemon-written grant and workspace confinement (476ca4 A1/A1b) +- **Approved grant.** Kind `authorization`, field `approved_grant: 1`, + keyed on `proposal_sha256 = compose_proposal_sha256`, naming `workspace` + (canonical), `target = workspace/path`, `prior_sha256`, `approval_key`, + `replay_claim`, `cx_promotion`, `cx_evidence`, `request_id`, `trace_id`, + `approval_id`, `desk_key_id`, `approved_proposal_sha256`; Cortex links + [cx_promotion, cx_evidence, replay_claim]. Reserved: `ComposeNote` refuses + any authorization carrying `approved_grant`. At the intent the daemon + requires the replay claim to be COMMITTED with the same approval key and + commit evidence naming the same proposal, promotion and evidence, and the + record to link all three. A crash between the replay commit and the grant + leaves the approval spent with no grant: no effect, a new approval is + needed (`approved_crash_test` boundary 3). +- **Confinement, every grant.** `effects::confine_target`: the workspace is + an absolute canonical directory other than `/`; `path` has plain + components only; `target == workspace/path`; the target's directory + resolves (symlinks followed) to itself inside the workspace; an existing + target is a regular file, never a symlink. Checked when a grant is written + through `ComposeNote` and again at every `ComposeEffectIntent`. A grant + with no `workspace` opens no intent. `aien compose authorize` now writes + `workspace`; older unspent grants without it are refused (fail closed). +- **Still open (sc#261, out of scope here):** the generic, client-written + `ComposeNote` authorization used by the `aien compose` operator flow. A + same-user socket caller can still write a generic grant for a proposal + nothing produced, inside a workspace it names, and reach DONE. The + workspace is the caller's claim, as it is for `aien compose authorize`. + `approved_confinement_test` asserts this observed behaviour so the follow-up + flips it visibly. `aien compose desk-key [--create 1]` prints the +desk key id and path (never the key) and creates the key if none exists. + +## Authentication design (#249 A) +Reused primitive: none of the existing grant records can carry it. A +`ComposeNote` `authorization` grant is written by any same-user socket +caller, so binding the approval to one would be caller text in two steps; +the aien-mcp `ApprovalGrant` lives in the INTERPLANE process memory and the +daemon cannot check it. So the smallest verifiable evidence is used: +`approval_mac` = HMAC-SHA256 (RFC 2104 over the existing sha2 crate, no new +dependency) keyed by the approval desk key, over the canonical binding +(`approved_auth::binding_bytes`): compact JSON, keys sorted, of +approval_id, approved_proposal_sha256, approver, content_sha256, +desk_key_id, path, request_id, trace_id, workspace and +`"v":"aien.approval.v2"`. `workspace` is the canonical absolute path +(symlinks resolved): the daemon canonicalises the command's `workspace` +and binds that, so a valid approval presented with another workspace fails +the MAC (`Unauthenticated`, nothing consumed; 476ca4 c17), and the daemon's +grant target is derived only from the bound workspace plus path. v2 because +the binding gained a field (nothing was released under v1). +The daemon recomputes it with its copy of the key and compares in constant +time; anything else is `PROPOSAL_REFUSED Unauthenticated`. +- Key: 32 bytes from /dev/urandom, `/approval-desk.key`, + 64 lowercase hex, created 0600 with O_EXCL|O_NOFOLLOW. Every submission + re-loads it: a symlink, a non-regular file, another owner, any group or + other permission bit, or a malformed key is `NoDesk`. Only desk_key_id + (first 16 hex of sha256 of the key) is ever printed or recorded. +- Confinement: the compose home and the submission's workspace must not + overlap (either inside the other), else `Confinement`: the model-facing + tools read inside the workspace, never the key or the journal. +- What it proves: the holder of the desk key approved exactly these fields. + Not which human pressed approve: the desk (INTERPLANE host-only approval + continuation) names the approver, and the MAC stops anyone without the key + from changing it. Caller text can never carry a valid MAC. +- Rotation / loss: replacing the key refuses every MAC made with the old + one (approvals issued and not yet submitted must be approved again); + claims already recorded keep their keys. Without a key every submission + is `NoDesk`. +- Limit: the OS user is still the outer boundary; a process of the + daemon's user that can read the compose home can read the key. + +## Replay (#249 B, crate::approved_replay, session 476ca4) +`approval_key` = sha256 of the binding above; the claim keys are the +approval key, the request id and the approval id, each on its own. Order in +`ProposerHook::submit`: verify -> reconcile gate -> desk key -> confinement +-> MAC -> `claim` (durable `accepted`) -> `mark_in_flight` -> one +`run_approved_task` -> `commit` | `fail` (ran, not committed) | `uncertain` +(run error, or committed but not the approved text). A refused claim is +returned with its state; a retry of the very same approval (all keys equal) +whose claim committed gets the original result back as ALREADY_COMMITTED, +never a second run. Daemon start runs `approved_replay::reconcile_at_start` +after the effect reconcile (accepted -> not_executed, in_flight -> +uncertain); a failure gates effect commands and approved proposals. ## Hash semantics (fix) - approved_proposal_sha256 = sha256 of compact JSON {"content","path"} with @@ -44,16 +140,39 @@ compose_proposal_sha256, grant_links and the compose `task` report. blank line, code fence) is refused, so content_sha256 is the committed one. ## Refusals (never silent) -`PROPOSAL_REFUSED Unverified` (hash, ids, path, template round trip; nothing -appended), `Duplicate` (request or approval id already submitted in this -process), `ComposeError`, `NotCommitted`, `Mismatch`. +`PROPOSAL_REFUSED` `Unverified` (hash, ids, path, template round trip), +`ReconcileFailed`, `NoDesk`, `Confinement`, `Unauthenticated` (nothing +appended for any of these); `REPLAY_REFUSED ` from the claim +(AlreadyCommitted, AlreadyFailed, AlreadyConsumed, Uncertain, InFlight, ...); +after a claim: `ComposeError` and `Mismatch` (claim UNCERTAIN), +`NotCommitted` (claim FAILED); after the replay commit: `GrantNotWritten` +(the approval is spent, no grant, no effect). At the intent: +`EFFECT_REFUSED OutsideWorkspace`, and `NotAuthorized` for a grant with no +workspace or an approved grant without its committed backing. At ack and +reconcile the confinement runs again (476ca4 c28/c28b: a parent directory +swapped for a symlink after the intent): if it refuses, the state recorded is +UNRESOLVED with `disk_error` `OutsideWorkspace: ...`, never DONE, and an +operator declaration of DONE is refused. ## Deferred -- No socket command: the hook is in-process only. A daemon command (and the - `AIEN_COMPOSE_PROPOSER=interplane:` selection) is the next cut. -- Replay set is in memory; after a daemon restart a replay is stopped by the - upstream desk (pending approvals are in memory) and by single-use grants, - not by this hook. A durable request-id record is not written. -- The effect receipt (`record_effect_receipt`) still has no request_id. +- The effect receipt (`record_effect_receipt`) still has no request_id or + trace_id (#76; see below). The replay `accepted` record carries + `request_id` and `trace_id` (and `approval_id`, `approval_key`). - Real model leg NOT_RUN; no GPU. -- approver / approval_id are caller-supplied: authenticate + durable replay first (#249). + +## Correlation for retained records (#76, design note only) +Today trace_id and request_id survive in: the command's report and refusal +(`request_id`, `trace_id`), the replay `accepted` record (Cortex host +record, kind effect, fields `request_id`, `trace_id`, `approval_id`, +`approval_key`), and the compose goal text (request only). Since the A1 fix the +daemon's approved grant carries `request_id`, `trace_id` and `approval_id` +and links the replay claim; the intent and ack records and +`record_effect_receipt` still carry neither. +Recommended: option B, bind rather than re-version: a verifier walks +ack -> intent (`authorization`) -> approved grant (`replay_claim`, Cortex +link) -> claim and reads trace_id/request_id from the immutable claim +record (and the grant text). Receipt files stay version 1. Done by the A1 +fix: the grant links the claim; a grant whose claim is not COMMITTED with +matching evidence is refused at intent; the approved grant cannot be +forged. Tests still to add: walk from an ack recovers trace_id and +request_id; `record_effect_receipt` for approved writes names the grant. ```