diff --git a/.crumb b/.crumb index 91e8f069..5d7f729d 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-07T22:16:47Z", + "compiled_at": "2026-10-07T22:46:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:13e4b128a6a9660899f874a62d5311172a09e30bc5965ec4c5eb04e79960abf1", + "digest": "sha256:7cb076b9f153971012ac154ca45889743d341869a6904ed8eac9392b4c914ed3", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1304, - "generated_at_commit": "a7533566439ec4cc6745f872b49f1906bc6b21a2", - "source_tree": "sha256:7fa9e5efcec034e5ff6f7b272cfc5e2952f2196e1a3c60a6977b2de1c8874e92" + "files": 1307, + "generated_at_commit": "1bb259d5cfa3a40d8aad185351cd3e3cd5700abf", + "source_tree": "sha256:c32d786ed9f12ca3c3ec0314527cbb892277c126666b48c2b32c0e1f8799dcd8" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 125fe4b8..3194199b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,6 +67,7 @@ version = "0.1.0" dependencies = [ "aien-inference-abi", "aien-kv-cache", + "aien-omega-compose", "aien-omega-gpu", "aien-runtime", "aien-scheduler", @@ -306,6 +307,7 @@ dependencies = [ "aien-kv-cache", "aien-omega-compose", "aien-platform", + "aien-runtime", "aien-scheduler", "aien-security", "async-trait", diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 520aa93c..8611a986 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "cfc668867bddd6187aa0d6a857e652dae96d56fb14298dbdeed227f81c7ff1a6", - "last_commit": "33f4545", + "digest": "19bf33a9aa4a78fdb1582f6f5894babd98fe2e0fe3c62d09d73ed2aed5411035", + "last_commit": "38ca311", "name": "src", "purpose": "" } ], - "children_root": "sha256:9212b793d339da52b1d1bb34acfc10e1d3235635a23d924b5882fdaa55baae6c", - "compiled_at": "2026-10-07T07:35:38Z", + "children_root": "sha256:49467d31ab0ba245bfddd5141e95face7fa02a9b55acb0aac0b7c3cdf7f64018", + "compiled_at": "2026-10-07T22:36:23Z", "compiler": "crumb-compile/1", - "digest": "sha256:498535a45b2cd632f9a54fd8e073016f2bb865e26367e9f9a2c5cb5cce4b886b", + "digest": "sha256:d134dc0047d8fe54025f5ee3a2c9936c3e098891a94d7f974d0b6cf9f9938774", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 28, - "generated_at_commit": "33f4545950bd11f0aeed6bb860cd5d8a398e90d1", - "source_tree": "sha256:d2f61e73e66eb59e49c44f77425672cc0c6f65f666da15906ace7984e59663ec" + "files": 30, + "generated_at_commit": "c45a100ddb348a857470e5a38d3cf1d04f9a8524", + "source_tree": "sha256:9021a26e204fd47bbf34910256dced2de35ce7b58c7da5ba848dc149fcf3ba5d" } }, "history": [ diff --git a/crates/aien-cli/Cargo.toml b/crates/aien-cli/Cargo.toml index cafa0175..34da5083 100644 --- a/crates/aien-cli/Cargo.toml +++ b/crates/aien-cli/Cargo.toml @@ -7,6 +7,7 @@ authors = ["Drake Stapleton "] description = "Sovereign Gemini-style Terminal CLI & Agent Harness for DGX Spark" [dependencies] +aien-omega-compose = { path = "../aien-omega-compose" } tokio = { version = "1", features = ["full"] } reqwest = { version = "0.12", features = ["json", "stream"] } serde = { version = "1", features = ["derive"] } @@ -33,3 +34,4 @@ fault-hold = ["aien-runtime/fault-hold"] [dev-dependencies] tempfile = "3.10" +aien-runtime = { path = "../aien-runtime", features = ["test-support"] } diff --git a/crates/aien-cli/build.rs b/crates/aien-cli/build.rs new file mode 100644 index 00000000..2bd89402 --- /dev/null +++ b/crates/aien-cli/build.rs @@ -0,0 +1,10 @@ +//! `cfg(compose_linked)` when aien-omega-compose linked the real +//! librx_compose.a, 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-cli/src/.crumb b/crates/aien-cli/src/.crumb index 4b86ea95..308cebab 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-07T07:35:38Z", + "compiled_at": "2026-10-07T21:44:55Z", "compiler": "crumb-compile/1", - "digest": "sha256:cfc668867bddd6187aa0d6a857e652dae96d56fb14298dbdeed227f81c7ff1a6", + "digest": "sha256:19bf33a9aa4a78fdb1582f6f5894babd98fe2e0fe3c62d09d73ed2aed5411035", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "33f4545950bd11f0aeed6bb860cd5d8a398e90d1", - "source_tree": "sha256:58b50149de5f1849afc406ce2572c9be3abcc35f7678f4d3100f7cd92b65c318" + "generated_at_commit": "38ca311b97d20ecbdf8ddb082cfb76b540005912", + "source_tree": "sha256:41032bb2d04d39c8fadfb415cac438a4cbc54bf4fa608099d8b0595bfc54f7ef" } }, "history": [ diff --git a/crates/aien-cli/src/compose.rs b/crates/aien-cli/src/compose.rs index bb90f6bb..57d3f041 100644 --- a/crates/aien-cli/src/compose.rs +++ b/crates/aien-cli/src/compose.rs @@ -273,22 +273,37 @@ async fn step(sub: &str, m: &HashMap) -> Result { )); } 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. - let prior = effects::file_sha256(&target)?; + // sovereign-core #261: the daemon mints the grant. The CLI names + // the committed proposal (promotion + digest), the workspace it + // expects and the approver; path, content and target come from + // the daemon's own commit record, so nothing here is a grant the + // daemon has to trust. A raw `authorization` note is refused. + let constraints = m + .get("constraint") + .map(|s| ids(s)) + .transpose()? + .unwrap_or_default(); + let n = match send(ControlCommand::ComposeAuthorize { + cx_promotion: r.cx_promotion, + proposal_sha256: psha.clone(), + workspace: wsc.display().to_string(), + approver: approver.to_string(), + constraints: constraints.clone(), + }) + .await? + { + ControlResponse::ComposeNoted(n) => { + serde_json::to_value(n).map_err(|e| e.to_string())? + } + ControlResponse::Error(e) => return Err(e), + other => return Err(format!("unexpected response {other:?}")), + }; let tgt = target.display().to_string(); let args = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, "approver": approver, "cx_promotion": r.cx_promotion, "target": tgt, - "prior_sha256": prior}); - let result = json!({"approved": true, "target": target.display().to_string()}); + "constraints": constraints}); + let result = json!({"approved": true, "target": tgt, "authorization": n["id"]}); let rc = receipt("authorize", &args, &result, true)?; - let constraint = m.get("constraint").map(|s| ids(s)).transpose()?; - let mut links = vec![r.cx_promotion, r.cx_evidence]; - 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, "workspace": wsc.display().to_string()}); - let n = note("authorization", &text.to_string(), links).await?; Ok(json!({"step": "S4", "receipt": rc, "authorization": n, "approvals": 1})) } "execute" => { diff --git a/crates/aien-cli/tests/compose_ordinary_flow_test.rs b/crates/aien-cli/tests/compose_ordinary_flow_test.rs new file mode 100644 index 00000000..8c54821d --- /dev/null +++ b/crates/aien-cli/tests/compose_ordinary_flow_test.rs @@ -0,0 +1,221 @@ +//! sovereign-core #261: the ordinary `aien compose` flow (propose, authorize, +//! execute) with the daemon minting the grant, driven through the real CLI +//! binary against an in-process daemon whose compose bridge has a fixed +//! proposer (no model). Needs the linked composition archive; in a stub +//! build each test is IGNORED (cfg compose_linked from build.rs), never passed. +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::{AienRuntimeSpine, ComposeBridge, ComposeProposer, Generation}; +use aien_scheduler::SchedulerConfig; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +const PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n"; +const CONTENT: &str = "keep every change inside the workspace\n"; + +fn proposer() -> ComposeProposer { + Arc::new(|_prompt: &str, _limit: Duration| { + Ok(Generation { + text: PROPOSAL.to_string(), + tokens: 8, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +struct Rig { + _tmp: tempfile::TempDir, + socket: PathBuf, + ws: PathBuf, + dir: PathBuf, + client: AienRuntimeClient, + handle: tokio::task::JoinHandle>, +} + +async fn rig() -> Option { + if !aien_omega_compose::LINKED { + panic!("built without compose_linked"); + } + let tmp = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + let ws = root.join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let socket = root.join("aien.sock"); + let bridge = Arc::new(ComposeBridge::new( + root.join("compose"), + proposer(), + "test:fixed-proposer", + )); + 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).with_compose_bridge(bridge); + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + for _ in 0..250 { + if client.is_alive().await { + return Some(Rig { + dir: root.clone(), + _tmp: tmp, + socket, + ws, + client, + handle, + }); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +impl Rig { + /// Run `aien-cli compose `; returns (exit code, JSON on stdout). + async fn cli(&self, args: Vec) -> (i32, Value) { + let (sock, prov) = (self.socket.clone(), self.dir.join("prov")); + tokio::task::spawn_blocking(move || { + let o = std::process::Command::new(env!("CARGO_BIN_EXE_aien-cli")) + .arg("compose") + .args(&args) + .env("AIEN_RUNTIME_SOCK", &sock) + .env("AIEN_PROVENANCE_DIR", &prov) + .output() + .expect("run aien-cli"); + let out = String::from_utf8_lossy(&o.stdout).to_string(); + let v = out + .lines() + .rev() + .find_map(|l| serde_json::from_str::(l).ok()) + .unwrap_or_else(|| json!({"unparsed": out})); + (o.status.code().unwrap_or(-1), v) + }) + .await + .unwrap() + } + + async fn propose(&self) -> PathBuf { + let ws = self.ws.display().to_string(); + let (code, v) = self + .cli(vec![ + "propose".into(), + "--goal".into(), + "write the note".into(), + "--workspace".into(), + ws, + ]) + .await; + assert_eq!(code, 0, "{v}"); + let report = self.dir.join("S3.json"); + std::fs::write(&report, v.to_string()).unwrap(); + report + } + + fn args(&self, sub: &str, report: &Path, extra: &[&str]) -> Vec { + let mut a = vec![ + sub.to_string(), + "--report".into(), + report.display().to_string(), + "--workspace".into(), + self.ws.display().to_string(), + ]; + a.extend(extra.iter().map(|s| s.to_string())); + a + } + + async fn down(self) { + let _ = self.client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), self.handle).await; + } +} + +static ONE_HOME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] +async fn ordinary_flow_propose_authorize_execute_reaches_done() { + let _t = ONE_HOME.lock().await; + let Some(r) = rig().await else { return }; + let report = r.propose().await; + let (code, auth) = r + .cli(r.args("authorize", &report, &["--approver", "drake"])) + .await; + assert_eq!(code, 0, "{auth}"); + let id = auth["authorization"]["id"].as_u64().expect("grant id"); + // The grant is the daemon's own record, not a client note. + let text = match r + .client + .send_command(ControlCommand::ComposeRecall { + ids: vec![id], + prefix: None, + }) + .await + .unwrap() + { + ControlResponse::ComposeRecalled(x) => x.cited[0].text.clone().unwrap(), + other => panic!("{other:?}"), + }; + assert!(text.contains("\"minted_grant\":1"), "{text}"); + let ids = id.to_string(); + let (code, done) = r + .cli(r.args("execute", &report, &["--authorization", &ids])) + .await; + assert_eq!(code, 0, "{done}"); + assert_eq!(done["state"], "DONE", "{done}"); + assert_eq!( + std::fs::read_to_string(r.ws.join("NOTES.md")).unwrap(), + CONTENT + ); + // Replay: the same grant opens nothing a second time. + let (code, again) = r + .cli(r.args("execute", &report, &["--authorization", &ids])) + .await; + assert_ne!(code, 0, "{again}"); + assert!(again.to_string().contains("AlreadySpent"), "{again}"); + r.down().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] +async fn a_client_written_authorization_note_is_refused_and_opens_nothing() { + let _t = ONE_HOME.lock().await; + let Some(r) = rig().await else { return }; + let report = r.propose().await; + let rep: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap(); + let psha = rep["report"]["proposal_sha256"].as_str().unwrap(); + let csha = rep["report"]["proposal_content_sha256"].as_str().unwrap(); + // What the old CLI wrote: a complete, confined, well-formed grant note. + let note = json!({"proposal_sha256": psha, "path": "NOTES.md", "content_sha256": csha, + "approver": "attacker", "target": r.ws.join("NOTES.md").display().to_string(), + "prior_sha256": null, "workspace": r.ws.display().to_string()}); + match r + .client + .send_command(ControlCommand::ComposeNote { + kind: "authorization".into(), + text: note.to_string(), + links: vec![], + }) + .await + .unwrap() + { + ControlResponse::Error(e) => assert!(e.contains("sovereign-core #261"), "{e}"), + other => panic!("ATTACK SUCCEEDED: {other:?}"), + } + // Nothing was authorized, so nothing is written, whatever id is named. + let (code, v) = r + .cli(r.args("execute", &report, &["--authorization", "1"])) + .await; + assert_ne!(code, 0, "{v}"); + assert!(!r.ws.join("NOTES.md").exists()); + r.down().await; +} diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index 0833289b..aebd047c 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -33,6 +33,10 @@ thiserror = "1.0" # NEXT-PHASE-2 fault harness only (ACCEPTANCE-v3 2.6): forced start-up # reconcile failure. Enabled through aien-cli's `fault-hold`. fault-hold = [] +# Test seams that bypass the reserved-record guard (`note_unchecked`, +# `with_compose_bridge`). Enabled only by dev-dependencies, never by the daemon. +test-support = [] [dev-dependencies] tempfile = "3.10" +aien-runtime = { path = ".", features = ["test-support"] } diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 791c3516..ccbc7d84 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -123,6 +123,19 @@ pub enum ControlCommand { proposal: crate::approved::ApprovedProposal, workspace: String, }, + /// sovereign-core #261: the operator approves ONE proposal this daemon + /// committed (`RunComposeTask`), and the daemon mints the grant itself. + /// The caller names only the promotion, the proposal digest, the workspace + /// it expects and who approves; path, content and target come from the + /// daemon's own commit record. Answered with `ComposeNoted` (the grant). + /// This replaces a client-written `authorization` note, which is refused. + ComposeAuthorize { + cx_promotion: u64, + proposal_sha256: String, + workspace: String, + approver: String, + constraints: Vec, + }, /// NEXT-PHASE-2: operator `stop`, `resume`, `revoke` (ACCEPTANCE-v2 2.5, 2.6). ComposeControl { action: String, @@ -327,6 +340,10 @@ mod tests { /// Cortex ids name records in `/cortex.cx`; digests are hex. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ComposeTaskReport { + /// The daemon's compose-commit record for this run (#261), when it + /// committed a one-file proposal on the ordinary (non-approved) path. + #[serde(default)] + pub compose_commit: Option, /// Composition home (holds machine.id, cortex.cx, jspace). pub compose_dir: String, /// AienMachineId (32 bytes, hex) the home is bound to. diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index 1c674b11..c7819148 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -20,6 +20,17 @@ //! `stop`, `resume`, `revoke`. A stop is durable; a grant older than the //! newest stop is stale forever. //! +//! Grants (sovereign-core #261). The ledger honours only grants the daemon wrote +//! itself: `approved_grant` (ComposeApprovedProposal, backed by a COMMITTED +//! replay claim) and `minted_grant` (ComposeAuthorize, backed by a +//! `compose_commit` record the daemon wrote when its own compose run +//! committed the proposal). A caller-written `authorization` note (any record +//! with neither marker, including ones already in a journal from before this +//! rule) is read but never honoured: it opens no intent, and an intent it +//! opened earlier is settled UNRESOLVED by the world check (never DONE, never +//! NOT_DONE by the daemon itself) and an operator may not declare it DONE; an +//! operator `--declare not_done` is still accepted. +//! //! The ledger is rebuilt from the journal on every call, under the //! compose-home lock, so the check and the intent append are one step. use crate::control::{ @@ -109,14 +120,53 @@ pub struct Grant { pub workspace: Option, /// Set on the grant the daemon writes after an approved compose (#249). pub approved: Option, + /// Set on the grant `ComposeAuthorize` minted (#261). + pub minted: Option, /// The record's links. pub links: Vec, } +impl Grant { + /// True for a grant the daemon wrote itself (approved or minted). A + /// caller-written note, or an old one already in a journal, is not. + pub fn honoured(&self) -> bool { + self.approved.is_some() || self.minted.is_some() + } +} + /// 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"; +/// Marker field of the grant `ComposeAuthorize` mints (sovereign-core #261). +/// Reserved: `ComposeNote` refuses every `authorization` note. +/// Prefix of the `disk_error` of an intent whose grant the daemon did not mint. +pub const NOT_DAEMON_MINTED: &str = "NotDaemonMinted"; + +pub const MINTED_GRANT: &str = "minted_grant"; + +/// Marker field of the record the daemon writes when its own compose run +/// COMMITTED a one-file proposal (sovereign-core #261). Reserved. +pub const COMPOSE_COMMIT: &str = "compose_commit"; + +/// What a minted grant is backed by: the daemon's own compose-commit record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MintedGrant { + pub commit: u64, +} + +/// A compose-commit record as the ledger reads it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommitRow { + pub id: u64, + pub cx_promotion: u64, + pub cx_evidence: u64, + pub proposal_sha256: String, + pub path: String, + pub content_sha256: String, + pub workspace: String, +} + /// 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)] @@ -171,6 +221,10 @@ pub struct Ledger { pub grants: BTreeMap, /// Approved grants by replay claim: more than one for a claim opens none. pub approved_by_claim: BTreeMap>, + /// Compose-commit records the daemon wrote (#261), by record id. + pub commits: BTreeMap, + /// Minted grants by compose-commit record, oldest first. + pub minted_by_commit: BTreeMap>, pub intents: BTreeMap, /// authorization id -> intent id (one intent per authorization). pub spent: BTreeMap, @@ -269,6 +323,14 @@ impl Ledger { .get("workspace") .and_then(Value::as_str) .map(str::to_string), + minted: match v.get(MINTED_GRANT) { + None => None, + Some(_) => { + let commit = u(&v, "compose_commit", id)?; + self.minted_by_commit.entry(commit).or_default().push(id); + Some(MintedGrant { commit }) + } + }, approved: match v.get(APPROVED_GRANT) { None => None, Some(_) => { @@ -308,6 +370,21 @@ impl Ledger { let Ok(v) = serde_json::from_str::(text) else { return Ok(()); }; + if v.get(COMPOSE_COMMIT).is_some() { + self.commits.insert( + id, + CommitRow { + id, + cx_promotion: u(&v, "cx_promotion", id)?, + cx_evidence: u(&v, "cx_evidence", id)?, + proposal_sha256: s(&v, "proposal_sha256", id)?, + path: s(&v, "path", id)?, + content_sha256: s(&v, "content_sha256", id)?, + workspace: s(&v, "workspace", id)?, + }, + ); + return Ok(()); + } let Some(phase) = v.get("phase") else { // NEXT-PHASE-1 effect notes: a write_file spends its authorization. if v.get("tool").and_then(Value::as_str) == Some("write_file") { @@ -403,6 +480,14 @@ impl Ledger { format!("cortex.cx#{a} is not a verified authorization"), ) })?; + if !g.honoured() { + return Err(Refusal::new( + "NotAuthorized", + format!( + "authorization #{a} is a caller-written note; the daemon honours only grants it minted itself (sovereign-core #261): run aien compose authorize" + ), + )); + } if g.proposal_sha256 != req.proposal_sha256 || g.path != req.path || g.content_sha256 != req.content_sha256 @@ -531,11 +616,30 @@ pub fn world_state(row: &IntentRow) -> (EffectState, Result, Stri /// 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. +/// workspace, or its grant is not daemon-minted, the state is UNRESOLVED, never +/// DONE or NOT_DONE. pub fn confined_world_state( l: &Ledger, row: &IntentRow, ) -> (EffectState, Result, String>) { + // sovereign-core #261: an intent whose grant the daemon did not write + // (a caller-written note, opened before this rule) is never settled + // DONE or NOT_DONE by the world check; it stays UNRESOLVED and the operator + // is told why. (An operator declaration of NOT_DONE is still accepted; + // DONE is refused.) + if !l + .grants + .get(&row.authorization) + .is_some_and(Grant::honoured) + { + return ( + EffectState::Unresolved, + Err(format!( + "{NOT_DAEMON_MINTED}: authorization #{} was not minted by the daemon (sovereign-core #261)", + row.authorization + )), + ); + } let ws = l .grants .get(&row.authorization) @@ -592,6 +696,15 @@ fn reconcile_gate(b: &ComposeBridge) -> Result<(), String> { /// ComposeNote may not forge gated records (ACCEPTANCE-v2 2.7). pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { + // sovereign-core #261: no caller writes an authorization, whatever it + // says. Grants come from ComposeAuthorize and ComposeApprovedProposal, + // control records from ComposeControl; all are written by the daemon. + if kind == "authorization" { + return Err( + "ComposeNote: authorization records are written only by the daemon (ComposeAuthorize, ComposeApprovedProposal, ComposeControl); a caller-written grant is never honoured (sovereign-core #261)" + .into(), + ); + } let Ok(v) = serde_json::from_str::(text) else { return Ok(()); }; @@ -605,30 +718,10 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { "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 #261: the daemon's own compose-commit record. + "effect" if v.get(COMPOSE_COMMIT).is_some() => Err( + "ComposeNote: compose_commit records are written only by the compose run".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" @@ -792,6 +885,170 @@ pub(crate) fn write_approved_grant( }) } +/// A minted grant must be backed by the compose-commit record the daemon +/// wrote when its own compose run committed this proposal (#261): same +/// proposal, path, content and workspace, target = workspace + path, and the +/// grant links the record. +fn check_minted_backing(l: &Ledger, g: &Grant) -> Result<(), Refusal> { + let Some(m) = &g.minted else { + return Ok(()); + }; + let no = |w: &str| { + Refusal::new( + "NotAuthorized", + format!( + "minted grant #{} is not backed by a committed compose: {w}", + g.id + ), + ) + }; + let c = l + .commits + .get(&m.commit) + .ok_or_else(|| no("no such compose-commit record"))?; + let bound_target = Path::new(&c.workspace).join(&c.path); + if c.proposal_sha256 != g.proposal_sha256 + || c.path != g.path + || c.content_sha256 != g.content_sha256 + || g.workspace.as_deref() != Some(c.workspace.as_str()) + || g.target.as_deref().map(Path::new) != Some(bound_target.as_path()) + || !g.links.contains(&m.commit) + { + return Err(no("grant fields differ from the committed proposal")); + } + Ok(()) +} + +/// The record the daemon writes when its own compose run COMMITTED a +/// one-file proposal (#261): the only thing `ComposeAuthorize` mints from. +/// Linked to the promotion and evidence. Returns the record id. +#[allow(clippy::too_many_arguments)] +pub(crate) fn write_compose_commit( + home: &mut ComposeHome, + workspace: &str, + task: u64, + cx_promotion: u64, + cx_evidence: u64, + proposal_sha256: &str, + path: &str, + content_sha256: &str, +) -> Result { + let text = json!({ + COMPOSE_COMMIT: 1, "task": task, "cx_promotion": cx_promotion, + "cx_evidence": cx_evidence, "proposal_sha256": proposal_sha256, + "path": path, "content_sha256": content_sha256, "workspace": workspace, + }); + append(home, NoteKind::Effect, &[cx_promotion, cx_evidence], &text).map(|n| n.id) +} + +/// What `ComposeAuthorize` asks for: the operator's approval of one committed +/// proposal. Only ids and digests; path, content and target come from the +/// daemon's own commit record, never from the caller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MintRequest { + pub cx_promotion: u64, + pub proposal_sha256: String, + pub workspace: String, + pub approver: String, + /// Constraint records the grant links (at most 3). + pub constraints: Vec, +} + +/// ComposeAuthorize (#261): mint the one grant for a proposal this daemon +/// committed. Refused when no commit record names (promotion, proposal), the +/// workspace differs from the one the compose ran for, the target escapes it +/// (`confine_target`), or an earlier grant for the same commit is still live +/// or has an unsettled intent. A revoked, stale or NOT_DONE grant does not block a new one (each grant +/// is spent exactly once); a grant that settled DONE does: one committed +/// proposal gives at most one DONE effect. +pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { + if let Err(e) = reconcile_gate(b) { + return ControlResponse::Error(e); + } + noted(b.with_home(|home| { + let no = |name: &'static str, why: String| Refusal::new(name, why).to_string(); + if req.approver.trim().is_empty() { + return Err(no("NotAuthorized", "ComposeAuthorize needs an approver".into())); + } + if req.constraints.len() > 3 { + return Err(no("NotAuthorized", "at most 3 constraint links".into())); + } + let l = ledger(home)?; + let mut hits = l + .commits + .values() + .filter(|c| c.cx_promotion == req.cx_promotion && c.proposal_sha256 == req.proposal_sha256); + let (Some(c), None) = (hits.next(), hits.next()) else { + return Err(no( + "NotAuthorized", + format!( + "no compose-commit record names promotion #{} and this proposal: only a proposal this daemon committed (aien compose propose) can be authorized", + req.cx_promotion + ), + )); + }; + let ws = std::fs::canonicalize(&req.workspace) + .map_err(|e| no("OutsideWorkspace", format!("workspace {}: {e}", req.workspace)))? + .display() + .to_string(); + if ws != c.workspace { + return Err(no( + "OutsideWorkspace", + format!("the proposal was committed for workspace {}, not {ws}", c.workspace), + )); + } + let target = Path::new(&c.workspace).join(&c.path).display().to_string(); + confine_target(&c.workspace, &c.path, &target).map_err(|r| r.to_string())?; + let prior = file_sha256(Path::new(&target))?; + for &gid in l.minted_by_commit.get(&c.id).into_iter().flatten() { + if l.revoked.contains_key(&gid) || l.stops.iter().any(|&s| s > gid) { + continue; + } + let g = &l.grants[&gid]; + match l.spent.get(&gid).map(|i| &l.intents[i]) { + // Settled: the grant is spent for good (a new effect needs a + // new grant, as before). + Some(row) if row.state == EffectState::Done => { + return Err(no( + "AlreadySpent", + format!( + "grant #{gid} for this proposal settled DONE (intent #{}); one committed proposal gives at most one effect, new content needs a new compose", + row.id + ), + )) + } + Some(row) if row.state.terminal() => continue, + Some(row) => { + return Err(no( + "ReconciliationRequired", + format!( + "intent #{} for grant #{gid} is {}; run aien compose reconcile", + row.id, + row.state.name() + ), + )) + } + None if g.prior_sha256.as_ref() != Some(&prior) => continue, // stale + None => { + return Err(no( + "AlreadyAuthorized", + format!("grant #{gid} for this proposal is still live; revoke it first"), + )) + } + } + } + let mut links = vec![c.id]; + links.extend(&req.constraints); + let text = json!({ + MINTED_GRANT: 1, "compose_commit": c.id, "proposal_sha256": c.proposal_sha256, + "path": c.path, "content_sha256": c.content_sha256, + "approver": req.approver.trim(), "target": target, "workspace": c.workspace, + "prior_sha256": prior, "cx_promotion": c.cx_promotion, "cx_evidence": c.cx_evidence, + }); + append(home, NoteKind::Authorization, &links, &text) + })) +} + fn host_views(home: &mut ComposeHome) -> Result, String> { let (recs, total) = home .compose @@ -874,6 +1131,7 @@ pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { })?; 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())?; + check_minted_backing(&l, g).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, @@ -978,9 +1236,9 @@ pub fn reconcile( }; // 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")) + && disk.as_ref().is_err_and(|e| { + e.starts_with("OutsideWorkspace") || e.starts_with(NOT_DAEMON_MINTED) + }) { return Err(format!( "reconcile: intent #{} cannot be declared DONE: {}", @@ -1176,11 +1434,23 @@ mod tests { rec( id, "authorization", - json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", + json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", + "path": "N.md", "content_sha256": "c", "approver": "drake", "target": "/w/N.md", "prior_sha256": prior}), ) } + /// A grant record nobody minted: what a caller-written note looks like. + fn caller_grant(id: u64) -> ComposeRecordView { + rec( + id, + "authorization", + json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", + "approver": "attacker", "target": "/w/N.md", "prior_sha256": null, + "workspace": "/w"}), + ) + } + fn req(a: u64) -> IntentRequest { IntentRequest { authorization: a, @@ -1275,6 +1545,28 @@ mod tests { assert_eq!(refusal(&l, 2, None), "Revoked"); } + #[test] + fn a_caller_written_grant_is_never_honoured() { + // Fields that would pass every other check; no marker, so no grant. + let l = Ledger::from_records(&[caller_grant(2)]).unwrap(); + let e = l.check_intent(&req(2), &None).unwrap_err(); + assert_eq!(e.name, "NotAuthorized"); + assert!(e.detail.contains("caller-written"), "{}", e.detail); + // An intent it opened before the rule is never settled by the world. + let l = Ledger::from_records(&[caller_grant(2), intent(3, 2)]).unwrap(); + let (st, disk) = confined_world_state(&l, &l.intents[&3]); + assert_eq!(st, EffectState::Unresolved); + assert!(disk.unwrap_err().starts_with(NOT_DAEMON_MINTED)); + // A minted grant with no compose-commit record behind it opens nothing. + let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); + let e = check_minted_backing(&l, &l.grants[&2]).unwrap_err(); + assert!( + e.detail.contains("no such compose-commit record"), + "{}", + e.detail + ); + } + #[test] fn world_change_and_legacy_grants_are_stale() { let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); @@ -1282,7 +1574,8 @@ mod tests { let legacy = rec( 2, "authorization", - json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", "approver": "d"}), + json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", + "path": "N.md", "content_sha256": "c", "approver": "d"}), ); let l = Ledger::from_records(&[legacy]).unwrap(); assert_eq!(refusal(&l, 2, None), "Stale"); @@ -1422,12 +1715,23 @@ mod tests { } 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()); + // sovereign-core #261: every authorization note is refused, whatever it says. + for text in [ + g(json!({})), + g(json!({"approved_grant": 1})), + g(json!({"minted_grant": 1, "compose_commit": 1})), + g(json!({"target": "/etc/N.md"})), + json!({"control": "resume", "approver": "x"}).to_string(), + "not json".to_string(), + ] { + let e = check_reserved_note("authorization", &text).unwrap_err(); + assert!(e.contains("sovereign-core #261"), "{e}"); + } + assert!(check_reserved_note( + "effect", + &json!({"compose_commit": 1, "proposal_sha256": "p"}).to_string() + ) + .is_err()); // Approved grants (476ca4 c25): fields bound to the approval key, one per // claim, and a COMMITTED claim behind it. diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 792570f3..4d6c559f 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -28,6 +28,8 @@ pub struct AienRuntimeServer { is_running: Arc, tokenizer: Arc>>, warm_up: AtomicBool, + /// Test seam: a ready-made compose bridge (see `with_compose_bridge`). + compose_override: std::sync::Mutex>>, } /// NEXT-PHASE-1 v4 declared warm-up prompt (ACCEPTANCE-v4 Section 2(2)): @@ -52,9 +54,20 @@ impl AienRuntimeServer { is_running: Arc::new(AtomicBool::new(false)), tokenizer: Arc::new(RwLock::new(None)), warm_up: AtomicBool::new(false), + compose_override: std::sync::Mutex::new(None), } } + /// Test seam: serve compose commands from `bridge` (for example one with a + /// fixed proposer) instead of the bridge built from the environment and + /// the loaded model. The daemon binary never calls this. + #[doc(hidden)] + #[cfg(feature = "test-support")] + pub fn with_compose_bridge(self, bridge: Arc) -> Self { + *self.compose_override.lock().expect("compose override") = Some(bridge); + self + } + /// Installs the tokenizer that `StreamTurn` uses to encode prompts and decode tokens. pub fn set_tokenizer(&self, tokenizer: ChatTokenizer) { *self.tokenizer.write().expect("tokenizer lock") = Some(tokenizer); @@ -170,7 +183,13 @@ impl AienRuntimeServer { } // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). + let preset = self + .compose_override + .lock() + .expect("compose override") + .clone(); let compose = match compose_dir_from_env() { + _ if preset.is_some() => preset, Ok(dir) => Some(Arc::new( ComposeBridge::new( dir, @@ -678,12 +697,26 @@ async fn handle_connection( ref links, } => { let (k, t, l) = (kind.clone(), text.clone(), links.clone()); - // NEXT-PHASE-2: gated effect/control records cannot be forged here. + // Gated records (every authorization, effect phases, replay and + // commit records) are refused inside `note` itself (#261). + Some(Box::new(move |b: &Arc| b.note(&k, &t, &l))) + } + ControlCommand::ComposeAuthorize { + cx_promotion, + ref proposal_sha256, + ref workspace, + ref approver, + ref constraints, + } => { + let req = crate::effects::MintRequest { + cx_promotion, + proposal_sha256: proposal_sha256.clone(), + workspace: workspace.clone(), + approver: approver.clone(), + constraints: constraints.clone(), + }; 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), - } + crate::effects::mint_grant(b, &req) })) } ControlCommand::ComposeRecall { ref ids, prefix } => { diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index a9ecdbd1..dc00d6e2 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -416,6 +416,7 @@ impl AienRuntimeSpine { | ControlCommand::ComposeEffectAck { .. } | ControlCommand::ComposeReconcile { .. } | ControlCommand::ComposeControl { .. } + | ControlCommand::ComposeAuthorize { .. } | ControlCommand::ComposeApprovedProposal { .. } => ControlResponse::Error( "compose commands are handled on the socket connection, not as one-shot commands" .into(), @@ -1992,7 +1993,44 @@ impl ComposeBridge { Err(e) => (None, None, Some(e)), }; let parsed = proposal.as_deref().and_then(parse_file_proposal); + // sovereign-core #261: the daemon's own record that THIS run committed + // THIS proposal. `ComposeAuthorize` mints only from it. An approved + // proposal has its own replay claim and grant, so it gets none. + let mut compose_commit = None; + if let (true, None, Some(p), Some(text)) = ( + committed, + approved_text, + parsed.as_ref(), + proposal.as_deref(), + ) { + let wsc = std::fs::canonicalize(&ws) + .map_err(|e| format!("workspace {}: {e}", ws.display()))? + .display() + .to_string(); + let id = crate::effects::write_compose_commit( + home, + &wsc, + task, + r.cx_promotion, + r.cx_evidence, + &hex(&Sha256::digest(text.as_bytes())), + &p.path, + &hex(&Sha256::digest(p.content.as_bytes())), + ) + .map_err(|e| { + format!( + "compose run committed (promotion #{}) but its commit record was not written: {e}", + r.cx_promotion + ) + })?; + home.advance_mark().map_err(|e| { + format!("compose run: record mark update failed (E_MARK_WRITE): {e}") + })?; + compose_commit = Some(id); + } Ok(ComposeTaskReport { + compose_commit, + compose_dir: self.dir.display().to_string(), machine_id: home.machine_id.clone(), task, @@ -2050,8 +2088,27 @@ impl ComposeBridge { r } - /// S1 / S4 / S5: one operator record through the composition's writer. + /// S1 / S5: one operator record through the composition's writer. Gated + /// records cannot be forged here, on any path (the socket handler calls + /// this too): authorizations, effect phases, replay and compose-commit + /// records are written only by the daemon (sovereign-core #261). pub fn note(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { + if let Err(e) = crate::effects::check_reserved_note(kind, text) { + return ControlResponse::Error(e); + } + self.write_note(kind, text, links) + } + + /// `note` WITHOUT the reserved-record check. Cargo feature `test-support` + /// only: it stands for an attacker who can append to the journal directly, + /// so the ledger's own defences can be exercised. Not in a normal build. + #[doc(hidden)] + #[cfg(feature = "test-support")] + pub fn note_unchecked(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { + self.write_note(kind, text, links) + } + + fn write_note(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { let k = match kind { "constraint" => NoteKind::Constraint, "authorization" => NoteKind::Authorization, diff --git a/crates/aien-runtime/tests/approved_attacks_test.rs b/crates/aien-runtime/tests/approved_attacks_test.rs index 57926ece..79198524 100644 --- a/crates/aien-runtime/tests/approved_attacks_test.rs +++ b/crates/aien-runtime/tests/approved_attacks_test.rs @@ -713,9 +713,8 @@ async fn c20_workspace_containing_the_compose_home() { /// 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. +/// sovereign-core #261: the daemon refuses a raw `authorization` note on every +/// path, so the forged grant is never written and no intent can open. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr( not(compose_linked), @@ -728,8 +727,8 @@ async fn c18_a1_raw_forged_authorization() { }) .await; assert_eq!( - opened, "opened", - "sc#261 appears closed (A1 refused): flip c18 to assert refusal" + opened, "note refused", + "ATTACK SUCCEEDED (sc#261 A1): a caller-written authorization opened an effect intent" ); } @@ -753,9 +752,7 @@ async fn c19_a1b_forged_authorization_outside_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). +/// which also holds the compose home. Refused like c18 (sc#261). #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[cfg_attr( not(compose_linked), @@ -768,8 +765,8 @@ async fn c19c_a1c_forged_authorization_names_its_own_workspace() { }) .await; assert_eq!( - opened, "opened", - "sc#261 appears closed (A1c refused): flip c19c to assert refusal" + opened, "note refused", + "ATTACK SUCCEEDED (sc#261 A1c): a note naming its own workspace opened an effect intent" ); } @@ -1138,7 +1135,7 @@ fn bridge(tmp: &Path) -> aien_runtime::spine::ComposeBridge { } fn raw_note(b: &aien_runtime::spine::ComposeBridge, kind: &str, text: &str, links: &[u64]) -> u64 { - match b.note(kind, text, links) { + match b.note_unchecked(kind, text, links) { ControlResponse::ComposeNoted(n) => n.id, other => panic!("raw note: {other:?}"), } diff --git a/crates/aien-runtime/tests/approved_confinement_test.rs b/crates/aien-runtime/tests/approved_confinement_test.rs index 78badf0f..cd27e2e9 100644 --- a/crates/aien-runtime/tests/approved_confinement_test.rs +++ b/crates/aien-runtime/tests/approved_confinement_test.rs @@ -14,9 +14,9 @@ //! 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. +//! - sc#261 closed: every one of those forged notes is now refused at the note +//! (no `authorization` record is ever written by a caller). The parent +//! swap cases (c28, c28b) live in approved_attacks_test.rs. //! //! Needs librx_compose.a (AIEN_OMEGA_COMPOSE_LIB); in a stub build the compose //! commands refuse and the test returns early. @@ -135,234 +135,50 @@ async fn forged_grants_are_confined_and_the_approved_kind_is_reserved() { 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. + // sovereign-core #261: every shape of caller-written authorization is + // refused at the note, before any confinement question arises: no + // workspace, a target outside, `..`, an absolute path, a symlinked file, + // a symlinked directory, a well-formed in-workspace grant, and the + // reserved approved_grant kind. + let refused_note = |g: serde_json::Value| note(&c, "authorization", g); 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"); + let mut minted = grant("NOTES.md", &target, Some(&w)); + minted["minted_grant"] = json!(1); + minted["compose_commit"] = json!(1); + for g in [ + grant("NOTES.md", &target, None), + grant("NOTES.md", &outside, Some(&w)), + grant("../outside.txt", &outside, Some(&w)), + grant("etc/passwd", "/etc/passwd", Some("/")), + grant("link.txt", <, Some(&w)), + grant("sub/x.txt", &st, Some(&w)), + grant("NOTES.md", &target, Some(&w)), + fake, + minted, + ] { + refused(refused_note(g).await, "sovereign-core #261"); + } - // 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:?}"), - }; + // Nothing was written, and an intent on any id is refused. refused( - intent(&c, ok, &psha, "NOTES.md", &outside, &csha).await, + intent(&c, 1, &psha, "NOTES.md", &target, &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!(!std::path::Path::new(&target).exists()); 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:?}" - ); + // The parent-directory-swap cases (476ca4 c28, c28b) are covered on the + // daemon-written approved grant in approved_attacks_test.rs. } diff --git a/crates/aien-runtime/tests/approved_proposal_test.rs b/crates/aien-runtime/tests/approved_proposal_test.rs index 6eb3a9b9..3c786031 100644 --- a/crates/aien-runtime/tests/approved_proposal_test.rs +++ b/crates/aien-runtime/tests/approved_proposal_test.rs @@ -682,7 +682,7 @@ fn copied_approved_grant_opens_nothing() { 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) { + let copy = match b.note_unchecked("authorization", &text, &g.cited[0].links) { ControlResponse::ComposeNoted(n) => n.id, other => panic!("bridge-level copy: {other:?}"), }; diff --git a/crates/aien-runtime/tests/cortex_mark_test.rs b/crates/aien-runtime/tests/cortex_mark_test.rs index f9a30961..3d8f9cc6 100644 --- a/crates/aien-runtime/tests/cortex_mark_test.rs +++ b/crates/aien-runtime/tests/cortex_mark_test.rs @@ -59,8 +59,10 @@ fn mark_of(home: &Path) -> Mark { } fn grant(b: &ComposeBridge, n: u32) -> u64 { + // Any host record will do: only the journal length matters here, and a + // caller can no longer write an authorization (sovereign-core #261). noted(b.note( - "authorization", + "constraint", &json!({"approver": "drake", "n": n}).to_string(), &[], )) diff --git a/crates/aien-runtime/tests/effects_test.rs b/crates/aien-runtime/tests/effects_test.rs index a03000c4..bb92a0bb 100644 --- a/crates/aien-runtime/tests/effects_test.rs +++ b/crates/aien-runtime/tests/effects_test.rs @@ -85,6 +85,7 @@ fn state(b: &ComposeBridge, record: u64) -> String { } struct Fixture { + promotion: std::cell::Cell, target: String, psha: String, csha: String, @@ -92,12 +93,22 @@ struct Fixture { impl Fixture { fn grant(&self, b: &ComposeBridge) -> u64 { - 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, - "workspace": Path::new(&self.target).parent().unwrap().display().to_string()}); - noted(b.note("authorization", &text.to_string(), &[])).id + // sovereign-core #261: the daemon mints the grant from its own commit record. + noted(effects::mint_grant( + b, + &effects::MintRequest { + cx_promotion: self.promotion.get(), + proposal_sha256: self.psha.clone(), + workspace: Path::new(&self.target) + .parent() + .unwrap() + .display() + .to_string(), + approver: "drake".into(), + constraints: vec![], + }, + )) + .id } /// `alive`: this test process is the executor; otherwise a dead one. @@ -138,6 +149,7 @@ fn effect_intents_are_at_most_once_or_unresolved() { }; assert!(report.committed, "{report:?}"); let f = Fixture { + promotion: std::cell::Cell::new(report.cx_promotion), target: ws.join("NOTES.md").display().to_string(), psha: sha(PROPOSAL.as_bytes()), csha: sha(CONTENT.as_bytes()), @@ -167,10 +179,22 @@ fn effect_intents_are_at_most_once_or_unresolved() { let c = controlled(effects::control(&b, "revoke", "drake", Some(a1))); assert_eq!((c.revoked, c.recorded), (Some(false), None)); + // sovereign-core #261: a grant that settled DONE closes its commit (one + // committed proposal, at most one DONE effect); new content needs a new compose. + refused_mint(&f, &b); // 2. Executor died after the intent, before the write: NOT_DONE. // (Target removed first: a grant against the content itself would read - // DONE, ACCEPTANCE-v2 2.2 checks the content digest first.) + // DONE, ACCEPTANCE-v2 2.2 checks the content digest first. It also lets the + // second compose create NOTES.md again: since #288 a new-document compose + // never overwrites an existing file.) std::fs::remove_file(&f.target).unwrap(); + match b.run_task("write the note again", ws.to_str().unwrap()) { + ControlResponse::ComposeTaskResult(r) => { + assert!(r.committed, "second compose: {r:?}"); + f.promotion.set(r.cx_promotion) + } + other => panic!("second compose: {other:?}"), + } let a2 = f.grant(&b); let i2 = noted(effects::open_intent(&b, &f.req(a2, false))).id; let r = reconciled(effects::reconcile(&b, None, "test")); @@ -246,3 +270,19 @@ fn effect_intents_are_at_most_once_or_unresolved() { assert_eq!(ledger(&b).view(), before); assert!(effects::check_reserved_note("effect", r#"{"phase":"ack","intent":1}"#).is_err()); } + +fn refused_mint(f: &Fixture, b: &ComposeBridge) { + match effects::mint_grant( + b, + &effects::MintRequest { + cx_promotion: f.promotion.get(), + proposal_sha256: f.psha.clone(), + workspace: Path::new(&f.target).parent().unwrap().display().to_string(), + approver: "drake".into(), + constraints: vec![], + }, + ) { + ControlResponse::Error(e) => assert!(e.contains("settled DONE"), "{e}"), + other => panic!("ATTACK SUCCEEDED (second grant after DONE): {other:?}"), + } +} diff --git a/crates/aien-runtime/tests/minted_grant_test.rs b/crates/aien-runtime/tests/minted_grant_test.rs new file mode 100644 index 00000000..eaf2b434 --- /dev/null +++ b/crates/aien-runtime/tests/minted_grant_test.rs @@ -0,0 +1,379 @@ +//! sovereign-core #261: the daemon honours only grants it minted itself. +//! +//! The ordinary operator flow (propose -> authorize -> execute) is driven at +//! the bridge, exactly as the daemon runs it (no socket: the mock backend of +//! the socket tests cannot commit a proposal). Every test needs the linked +//! composition archive and is IGNORED in a stub build, never passed. The +//! socket-level refusal of a raw `authorization` note is +//! `c18_a1_raw_forged_authorization` in approved_attacks_test.rs. +use aien_omega_compose::hex; +use aien_runtime::control::{ComposeNoteReport, ComposeTaskReport, ControlResponse}; +use aien_runtime::effects::{self, IntentRequest, MintRequest}; +use aien_runtime::spine::{ComposeBridge, ComposeProposer, Generation}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +const PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n"; +const CONTENT: &str = "keep every change inside the workspace\n"; + +fn proposer() -> ComposeProposer { + Arc::new(|_prompt: &str, _limit: std::time::Duration| { + Ok(Generation { + text: PROPOSAL.to_string(), + tokens: 8, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn noted(r: ControlResponse) -> ComposeNoteReport { + match r { + ControlResponse::ComposeNoted(n) => n, + other => panic!("expected ComposeNoted, got {other:?}"), + } +} + +/// The refusal text of `r`; panics when the attack succeeded. +fn refusal(r: ControlResponse, attack: &str) -> String { + match r { + ControlResponse::Error(e) => e, + other => panic!("ATTACK SUCCEEDED ({attack}): {other:?}"), + } +} + +/// The composition engine holds one home at a time per process. +static ONE_HOME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +struct Fx { + _turn: std::sync::MutexGuard<'static, ()>, + _tmp: tempfile::TempDir, + home: PathBuf, + ws: PathBuf, + b: ComposeBridge, + report: ComposeTaskReport, +} + +impl Fx { + /// A home with one committed ordinary proposal; None in a stub build. + fn new() -> Option { + let turn = ONE_HOME.lock().unwrap_or_else(|e| e.into_inner()); + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("compose"); + let ws = std::fs::canonicalize({ + let w = tmp.path().join("ws"); + std::fs::create_dir_all(&w).unwrap(); + w + }) + .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 { + assert!(matches!(run, ControlResponse::Error(_))); + return None; + } + let ControlResponse::ComposeTaskResult(report) = run else { + panic!("run: {run:?}") + }; + assert!(report.committed, "{report:?}"); + Some(Fx { + _turn: turn, + _tmp: tmp, + home, + ws, + b, + report: *report, + }) + } + + fn target(&self) -> String { + self.ws.join("NOTES.md").display().to_string() + } + + fn mint_req(&self) -> MintRequest { + MintRequest { + cx_promotion: self.report.cx_promotion, + proposal_sha256: sha(PROPOSAL.as_bytes()), + workspace: self.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + } + } + + fn mint(&self) -> ControlResponse { + effects::mint_grant(&self.b, &self.mint_req()) + } + + fn req(&self, a: u64, alive: bool) -> IntentRequest { + let (pid, start) = if alive { + effects::self_executor() + } else { + (0, 0) + }; + IntentRequest { + authorization: a, + proposal_sha256: sha(PROPOSAL.as_bytes()), + path: "NOTES.md".into(), + target: self.target(), + content_sha256: sha(CONTENT.as_bytes()), + executor_pid: pid, + executor_start: start, + } + } + + fn open(&self, a: u64) -> ControlResponse { + effects::open_intent(&self.b, &self.req(a, true)) + } + + /// The text of record `id`. + fn text(&self, id: u64) -> Value { + match self.b.recall(&[id], None) { + ControlResponse::ComposeRecalled(r) => { + serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap() + } + other => panic!("recall: {other:?}"), + } + } + + fn ack_state(&self, intent: u64) -> String { + let n = noted(effects::ack(&self.b, intent, &json!({"executor": "test"}))); + self.text(n.id)["state"].as_str().unwrap().to_string() + } +} + +macro_rules! linked_test { + ($name:ident, |$fx:ident| $body:block) => { + #[test] + #[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] + fn $name() { + let Some($fx) = Fx::new() else { return }; + $body + } + }; +} + +linked_test!(ordinary_flow_end_to_end_with_a_daemon_minted_grant, |fx| { + // The run left the daemon's own commit record, and the report names it. + let commit = fx.report.compose_commit.expect("commit record id"); + let c = fx.text(commit); + assert_eq!(c["compose_commit"], 1); + assert_eq!(c["proposal_sha256"], sha(PROPOSAL.as_bytes())); + assert_eq!(c["workspace"], fx.ws.display().to_string()); + // Authorize, intent, write, ack: DONE. + let g = noted(fx.mint()); + let gt = fx.text(g.id); + assert_eq!(gt["minted_grant"], 1); + assert_eq!(gt["compose_commit"], commit); + assert_eq!(gt["target"], fx.target()); + assert!(g.links.contains(&commit), "{:?}", g.links); + let i = noted(fx.open(g.id)).id; + std::fs::write(fx.target(), CONTENT).unwrap(); + assert_eq!(fx.ack_state(i), "DONE"); + assert_eq!(std::fs::read_to_string(fx.target()).unwrap(), CONTENT); +}); + +linked_test!(a_replayed_grant_is_refused, |fx| { + let g = noted(fx.mint()).id; + let i = noted(fx.open(g)).id; + // Second intent while the first is open, then after it settled. + assert!(refusal(fx.open(g), "intent while open").contains("ReconciliationRequired")); + std::fs::write(fx.target(), CONTENT).unwrap(); + assert_eq!(fx.ack_state(i), "DONE"); + assert!(refusal(fx.open(g), "replay after DONE").contains("AlreadySpent")); +}); + +linked_test!(a_grant_names_only_what_the_daemon_committed, |fx| { + let g = noted(fx.mint()).id; + for (what, f) in [ + ( + "other path", + (|r: &mut IntentRequest| { + r.path = "OTHER.md".into(); + }) as fn(&mut IntentRequest), + ), + ("other content", |r| r.content_sha256 = sha(b"evil\n")), + ("other proposal", |r| r.proposal_sha256 = sha(b"evil")), + ("other target", |r| { + r.target = "/etc/passwd".into(); + }), + ] { + let mut r = fx.req(g, true); + f(&mut r); + let e = refusal(effects::open_intent(&fx.b, &r), what); + assert!(e.contains("NotAuthorized"), "{what}: {e}"); + } + assert!(!Path::new(&fx.target()).exists()); +}); + +linked_test!(minting_needs_a_proposal_the_daemon_committed, |fx| { + let mut r = fx.mint_req(); + r.proposal_sha256 = sha(b"never proposed by any compose"); + let e = refusal(effects::mint_grant(&fx.b, &r), "unknown proposal"); + assert!(e.contains("only a proposal this daemon committed"), "{e}"); + let mut r = fx.mint_req(); + r.cx_promotion += 1000; + refusal(effects::mint_grant(&fx.b, &r), "unknown promotion"); + // The workspace the compose ran for is the only one it can be authorized for. + let other = fx.ws.parent().unwrap().join("other"); + std::fs::create_dir_all(&other).unwrap(); + let mut r = fx.mint_req(); + r.workspace = other.display().to_string(); + let e = refusal(effects::mint_grant(&fx.b, &r), "other workspace"); + assert!(e.contains("OutsideWorkspace"), "{e}"); + let mut r = fx.mint_req(); + r.approver = " ".into(); + refusal(effects::mint_grant(&fx.b, &r), "no approver"); +}); + +linked_test!(workspace_confinement_still_binds_a_minted_grant, |fx| { + // The target is a symlink to a file outside the workspace. + let outside = fx.ws.parent().unwrap().join("outside.txt"); + std::fs::write(&outside, "outside\n").unwrap(); + std::os::unix::fs::symlink(&outside, fx.target()).unwrap(); + let e = refusal(fx.mint(), "symlink target"); + assert!(e.contains("OutsideWorkspace"), "{e}"); + std::fs::remove_file(fx.target()).unwrap(); + // Authorized while it was a regular path; swapped for a symlink after. + let g = noted(fx.mint()).id; + std::os::unix::fs::symlink(&outside, fx.target()).unwrap(); + refusal(fx.open(g), "symlink swapped in after the grant"); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), "outside\n"); +}); + +linked_test!(one_live_grant_per_proposal_until_revoked, |fx| { + let g1 = noted(fx.mint()).id; + let e = refusal(fx.mint(), "second live grant"); + assert!(e.contains("AlreadyAuthorized"), "{e}"); + effects::control(&fx.b, "revoke", "drake", Some(g1)); + let g2 = noted(fx.mint()).id; + assert_ne!(g1, g2); + assert!(refusal(fx.open(g1), "revoked grant").contains("Revoked")); + noted(fx.open(g2)); +}); + +linked_test!(a_forged_legacy_note_in_the_ledger_is_ignored, |fx| { + // What a pre-#261 caller could write: a complete, well-confined grant for + // a proposal no compose produced. Appended below the note guard, as an + // attacker with journal access (or an old record) would have it. + let psha = sha(b"never proposed by any compose"); + let csha = sha(b"forged\n"); + let forged = json!({"proposal_sha256": psha, "path": "NOTES.md", "content_sha256": csha, + "approver": "attacker", "target": fx.target(), "prior_sha256": null, + "workspace": fx.ws.display().to_string()}); + let a = noted(fx.b.note_unchecked("authorization", &forged.to_string(), &[])).id; + let mut r = fx.req(a, true); + r.proposal_sha256 = psha; + r.content_sha256 = csha; + let e = refusal(effects::open_intent(&fx.b, &r), "forged legacy note"); + assert!(e.contains("caller-written"), "{e}"); + // Even a forged grant that copies the REAL proposal's digests opens nothing. + let real = json!({"proposal_sha256": sha(PROPOSAL.as_bytes()), "path": "NOTES.md", + "content_sha256": sha(CONTENT.as_bytes()), "approver": "attacker", + "target": fx.target(), "prior_sha256": null, + "workspace": fx.ws.display().to_string()}); + let a2 = noted(fx.b.note_unchecked("authorization", &real.to_string(), &[])).id; + let e = refusal(fx.open(a2), "forged note with real digests"); + assert!(e.contains("caller-written"), "{e}"); + // The daemon's own minting is unaffected by the forged records. + noted(fx.mint()); +}); + +linked_test!( + an_in_flight_intent_on_a_forged_grant_is_never_settled_done, + |fx| { + // An intent opened on a caller-written grant before the rule existed: + // the bytes are even on disk, yet the ledger will not call it DONE. + let forged = json!({"proposal_sha256": sha(PROPOSAL.as_bytes()), "path": "NOTES.md", + "content_sha256": sha(CONTENT.as_bytes()), "approver": "attacker", + "target": fx.target(), "prior_sha256": null, + "workspace": fx.ws.display().to_string()}); + let a = noted(fx.b.note_unchecked("authorization", &forged.to_string(), &[])).id; + let intent = json!({"phase": "intent", "tool": "write_file", "authorization": a, + "proposal_sha256": sha(PROPOSAL.as_bytes()), "path": "NOTES.md", + "target": fx.target(), "content_sha256": sha(CONTENT.as_bytes()), + "prior_sha256": null, "executor": {"pid": 0, "start": 0}}); + let i = noted(fx.b.note_unchecked("effect", &intent.to_string(), &[a])).id; + std::fs::write(fx.target(), CONTENT).unwrap(); + assert_eq!(fx.ack_state(i), "UNRESOLVED"); + let d = aien_runtime::control::ReconcileDeclare { + intent: i, + state: "done".into(), + approver: "drake".into(), + }; + let e = refusal(effects::reconcile(&fx.b, Some(&d), "test"), "declare DONE"); + assert!(e.contains("NotDaemonMinted"), "{e}"); + } +); + +linked_test!( + a_minted_grant_survives_a_restart_and_recovery_still_settles, + |fx| { + let g = noted(fx.mint()).id; + let i = noted(effects::open_intent(&fx.b, &fx.req(g, false))).id; + let Fx { home, ws, b, .. } = fx; + drop(b); + // New daemon process: the ledger is rebuilt from the journal alone. + let b = ComposeBridge::new(home, proposer(), "test:fixed-proposer"); + let line = effects::reconcile_at_start(&b); + assert!(line.starts_with("Reconcile: checked 1"), "{line}"); + let l = match b.recall(&[], None) { + ControlResponse::ComposeRecalled(r) => effects::Ledger::from_records(&r.host).unwrap(), + other => panic!("{other:?}"), + }; + assert!(l.grants[&g].honoured()); + // The executor never wrote: NOT_DONE, from the world. + assert_eq!(l.intents[&i].state.name(), "NOT_DONE"); + assert!(!ws.join("NOTES.md").exists()); + } +); + +linked_test!(raw_authorization_notes_are_refused_on_every_path, |fx| { + for text in [ + json!({"proposal_sha256": "p"}).to_string(), + json!({"minted_grant": 1, "compose_commit": 1}).to_string(), + json!({"approved_grant": 1}).to_string(), + json!({"control": "resume", "approver": "x"}).to_string(), + "not json".to_string(), + ] { + let e = refusal(fx.b.note("authorization", &text, &[]), "raw authorization"); + assert!(e.contains("sovereign-core #261"), "{e}"); + } + let forged_commit = json!({"compose_commit": 1, "cx_promotion": 1, "cx_evidence": 1, + "proposal_sha256": "p", "path": "x", "content_sha256": "c", "workspace": "/"}); + refusal( + fx.b.note("effect", &forged_commit.to_string(), &[]), + "forged compose_commit", + ); +}); + +linked_test!(no_new_grant_after_a_grant_settled_done, |fx| { + let g = noted(fx.mint()).id; + let i = noted(fx.open(g)).id; + std::fs::write(fx.target(), CONTENT).unwrap(); + assert_eq!(fx.ack_state(i), "DONE"); + let e = refusal(fx.mint(), "second grant after DONE"); + assert!( + e.contains("AlreadySpent") && e.contains("settled DONE"), + "{e}" + ); + // New content needs a new compose: it has its own commit record. (Since + // #288 a new-document compose never overwrites an existing file, so the + // written note is removed first.) + std::fs::remove_file(fx.target()).unwrap(); + let ControlResponse::ComposeTaskResult(second) = + fx.b.run_task("write the note again", fx.ws.to_str().unwrap()) + else { + panic!("second compose") + }; + assert!(second.committed, "second compose: {second:?}"); + assert_ne!(second.compose_commit, fx.report.compose_commit); + let mut r = fx.mint_req(); + r.cx_promotion = second.cx_promotion; + noted(effects::mint_grant(&fx.b, &r)); +}); diff --git a/crates/aien-runtime/tests/requirements_test.rs b/crates/aien-runtime/tests/requirements_test.rs index 392aed3b..e96945a2 100644 --- a/crates/aien-runtime/tests/requirements_test.rs +++ b/crates/aien-runtime/tests/requirements_test.rs @@ -432,12 +432,17 @@ fn linked_passing_document_is_approved_and_saved_byte_for_byte() { assert!(!ws.join("DOC.md").exists(), "composing writes nothing"); // Approval (the authorization note) binds the digest; the effect writes. let target = ws.join(&saved.path); - let grant = serde_json::json!({ - "proposal_sha256": r.proposal_sha256.clone().unwrap(), "path": saved.path, - "content_sha256": content_sha, "approver": "drake", - "target": target.display().to_string(), "prior_sha256": null, - "workspace": ws.display().to_string()}); - let a = match bridge.note("authorization", &grant.to_string(), &[]) { + // sovereign-core #261: the daemon mints the grant from its own commit record. + let a = match effects::mint_grant( + &bridge, + &effects::MintRequest { + cx_promotion: r.cx_promotion, + proposal_sha256: r.proposal_sha256.clone().unwrap(), + workspace: ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + }, + ) { ControlResponse::ComposeNoted(n) => n.id, other => panic!("authorize: {other:?}"), }; diff --git a/docs/COMPOSE_PROPOSER_HOOK.md b/docs/COMPOSE_PROPOSER_HOOK.md index 1a57c40f..bd4a9c39 100644 --- a/docs/COMPOSE_PROPOSER_HOOK.md +++ b/docs/COMPOSE_PROPOSER_HOOK.md @@ -67,13 +67,42 @@ for an approved write. 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 +- **Closed (sc#261): only daemon-minted grants are honoured.** `ComposeNote` + refuses every `authorization` record, whatever it says (also inside + `ComposeBridge::note`, so no in-process path writes one). Two grant kinds + exist, both written by the daemon: + - `approved_grant`, from `ComposeApprovedProposal`, backed by a COMMITTED + replay claim and the desk-key MAC (above); + - `minted_grant`, from the new `ComposeAuthorize` command that + `aien compose authorize` now sends. When the daemon's own compose run + commits a one-file proposal on the ordinary path it writes a reserved + `compose_commit` record (promotion, evidence, proposal digest, path, + content digest, canonical workspace). `ComposeAuthorize` names only the + promotion, the proposal digest, the workspace the operator expects and + the approver; path, content and target come from the commit record, so + the caller never supplies them. It is refused when no commit record + matches, when the workspace differs from the one the compose ran for, + when `confine_target` fails, or when an earlier grant for the same commit + is still live or has an unsettled intent. Revoked, stale and settled + (NOT_DONE) grants do not block a new one; each grant is spent once. After a + grant for a commit settled DONE, no new grant is minted for that commit: + one committed proposal gives at most one DONE effect (new content needs a + new compose). + At `ComposeEffectIntent` the grant is checked against its commit record. + - Old records: an `authorization` record with neither marker (written by a + client before this change) is read but never honoured. It opens no intent; + an intent it opened earlier is settled UNRESOLVED with `disk_error` + `NotDaemonMinted` (the world check never yields DONE or NOT_DONE for it), + and an operator cannot declare it DONE (an operator `--declare not_done` is + still accepted). An old committed proposal has no commit record, so it must be + proposed again before it can be authorized. + - Limit: the approval in the ordinary flow is the operator's CLI call as + the daemon's OS user; it carries no desk-key MAC (accepted residual; optional MAC tracked in + sovereign-core #297). What changed is that a + grant can exist only for content the daemon itself committed, at the + workspace and path the daemon recorded, and only the daemon writes it. + The approved-proposal path keeps its MAC. + `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)