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
GitHub aien-dev/aien-sovereign-core-mv#304 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/d38fb9038fed2b96.bundle -o d38fb9038fed2b96.bundle git fetch d38fb9038fed2b96.bundle refs/pull/304/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
304
1f1fc8010a3712ff1a83dd6713fef79438f26fb1
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":304,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/304","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:45Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index e5303da7..93d1b5a4 100644 --- a/.crumb +++ b/.crumb @@ -64,8 +64,8 @@ "generated": { "children": [ { - "digest": "5113f380d92d17b79f3676f303677c86b6980132671208b070eb84ec6ceee3ba", - "last_commit": "07e447c", + "digest": "c34ee7424ed8e187cd76e8c971904972f2f839e592cbe52b8779158e00522713", + "last_commit": "c47a168", "name": "scripts", "purpose": "" }, @@ -76,15 +76,15 @@ "purpose": "" } ], - "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-08T01:28:53Z", + "children_root": "sha256:b1835fde755b4115f446535d70e7752fb4d4f00d7f4dd2ca2ed6291e7be43c94", + "compiled_at": "2026-10-08T02:27:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:ea64f7c95d6eca019466b3b261437d356abeb107239c8122ad75ab3066858305", - "evidence_files": 186, - "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1339, - "generated_at_commit": "7eaaf015cbb5c7738be049b18af482b7e834905f", - "source_tree": "sha256:c78cf9015d54e19fb3b4eac8d872b684b0f7a2cab97ef8e607af4cd04caf1483" + "digest": "sha256:f5f055cec3b684ebc51518d1a0e55c9fc810c33c57f001b3b54d98b07305ccfa", + "evidence_files": 187, + "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", + "files": 1343, + "generated_at_commit": "cffee10466c5621ed586faff5fff49f7bdf4a1ee", + "source_tree": "sha256:fc6403798b6ed4c04632904687e0af2e9b32a05b0a9df347555ca754e6dce34d" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index f39fcc38..a7b720c5 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "191a29d642fd9ab8d99389383c02f7a886690e667ac0d87bd3fb04a984c6c3f7", - "last_commit": "5ae4f1d", + "digest": "4b4b86277d8940abf2b9bcca24f88713b8644803cf152e70db79c7002c18eaf3", + "last_commit": "cffee10", "name": "src", "purpose": "" } ], - "children_root": "sha256:16e726539369c13d22cabd3d6b1d7fff2fd60e09a53465ab611a80aab494e16f", - "compiled_at": "2026-10-08T00:47:16Z", + "children_root": "sha256:eee9a68813eedfe360a808b72ae34df9f1809c1b546432dfb49f55408d1c49b2", + "compiled_at": "2026-10-08T02:27:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:03e2bc1517734a73205069d8d051a2a3cf16ee17f9e80ff506d4e8725bce4853", + "digest": "sha256:de0d928ec313de5c89b63db56c2d0f78285a15b662f3c6accbb9f2d0eacb2887", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 31, - "generated_at_commit": "0e1d79bd5ff9afd6335611f1d3db3776a91b8873", - "source_tree": "sha256:0b976c77231eb94ea18915f71ac40f846fd3ec6be2cf6feb7ff03c36957a78eb" + "generated_at_commit": "cffee10466c5621ed586faff5fff49f7bdf4a1ee", + "source_tree": "sha256:b546c2a954a074b35018042d04d2ce0af9471a27714e8c987a16f3d890ad75c0" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 3bc9d118..a0a68104 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-08T00:47:16Z", + "compiled_at": "2026-10-08T02:27:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:191a29d642fd9ab8d99389383c02f7a886690e667ac0d87bd3fb04a984c6c3f7", + "digest": "sha256:4b4b86277d8940abf2b9bcca24f88713b8644803cf152e70db79c7002c18eaf3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 26, - "generated_at_commit": "0e1d79bd5ff9afd6335611f1d3db3776a91b8873", - "source_tree": "sha256:ccf8abe76ec75173fa3b0b5417ada0c5c21a0660c4b2aea4c52289408a474f9f" + "generated_at_commit": "cffee10466c5621ed586faff5fff49f7bdf4a1ee", + "source_tree": "sha256:554057cf418ca25e4225375caf8267196ab3c500b44056eeb1c05edd664c3de0" } }, "history": [ diff --git a/crates/aien-cli/src/compose.rs b/crates/aien-cli/src/compose.rs index 57d3f041..98d40294 100644 --- a/crates/aien-cli/src/compose.rs +++ b/crates/aien-cli/src/compose.rs @@ -17,6 +17,12 @@ //! propose --goal G --workspace W S3 one RunComposeTask //! authorize --report S3.json --workspace W --approver NAME [--constraint ID] //! S4 the one approval +//! [--desk 1 | --desk-key PATH | --desk-mac HEX --desk-nonce N] +//! optional approval-desk MAC (#297); the daemon +//! checks it only with AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=1 +//! ON mode adds assurance only if the authorizing caller +//! cannot read the desk key file; a process as the same +//! OS user that can read it passes trivially (as in #249) //! execute --report S3.json --workspace W --authorization ID //! S5 the write, confined //! explain --report S3.json --cite ID,.. --receipts P,.. @@ -283,12 +289,50 @@ async fn step(sub: &str, m: &HashMap<String, String>) -> Result<Value, String> { .map(|s| ids(s)) .transpose()? .unwrap_or_default(); + // sovereign-core #297: the optional approval-desk proof. Only a + // daemon started with AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=1 checks + // it; without the switch the daemon ignores it. + let desk_proof = { + use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; + use aien_runtime::control::DeskProof; + match (m.get("desk-mac"), m.get("desk-key"), m.contains_key("desk")) { + (Some(mac), _, _) => Some(DeskProof { + nonce: need(m, "desk-nonce")?.to_string(), + mac: mac.to_string(), + }), + (None, key_path, desk) if key_path.is_some() || desk => { + let key_file = match key_path { + Some(p) => std::path::PathBuf::from(p), + None => desk_key_path(&aien_runtime::spine::compose_dir_from_env()?), + }; + let key = DeskKey::load(&key_file)?; + let mut raw = [0u8; 16]; + std::io::Read::read_exact(&mut std::fs::File::open("/dev/urandom").map_err(|e| e.to_string())?, &mut raw) + .map_err(|e| e.to_string())?; + let nonce = hex::encode(raw); + let mac = key.sign_authorize(&AuthorizeBinding { + cx_promotion: r.cx_promotion, + proposal_sha256: psha.clone(), + path: path.clone(), + content_sha256: csha.clone(), + workspace: wsc.display().to_string(), + approver: approver.trim().to_string(), + constraints: constraints.clone(), + nonce: nonce.clone(), + desk_key_id: key.id().to_string(), + }); + Some(DeskProof { nonce, mac }) + } + _ => None, + } + }; 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(), + desk_proof, }) .await? { diff --git a/crates/aien-runtime/src/approved_auth.rs b/crates/aien-runtime/src/approved_auth.rs index c81fcacd..39791384 100644 --- a/crates/aien-runtime/src/approved_auth.rs +++ b/crates/aien-runtime/src/approved_auth.rs @@ -401,6 +401,74 @@ impl DeskKey { } } +/// Version tag of the `ComposeAuthorize` binding (sovereign-core #297). +pub const AUTHORIZE_BINDING_VERSION: &str = "aien.authorize.v1"; + +/// Everything one operator `ComposeAuthorize` covers. `path`, +/// `content_sha256` and `workspace` are the daemon's own commit-record values +/// on the verifying side; the signer computes the same from its report. +/// `nonce` makes each authorize unique: the daemon records it in the grant and +/// refuses a second grant for the same nonce. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorizeBinding { + pub cx_promotion: u64, + pub proposal_sha256: String, + pub path: String, + pub content_sha256: String, + pub workspace: String, + pub approver: String, + pub constraints: Vec<u64>, + pub nonce: String, + pub desk_key_id: String, +} + +/// Canonical bytes of an authorize binding: a domain tag, then compact JSON +/// with sorted keys. The domain tag keeps it apart from every approval MAC. +pub fn authorize_binding_bytes(b: &AuthorizeBinding) -> Vec<u8> { + let mut m = Map::new(); + for (k, v) in [ + ("approver", &b.approver), + ("content_sha256", &b.content_sha256), + ("desk_key_id", &b.desk_key_id), + ("nonce", &b.nonce), + ("path", &b.path), + ("proposal_sha256", &b.proposal_sha256), + ("workspace", &b.workspace), + ] { + m.insert(k.into(), Value::String(v.clone())); + } + m.insert("cx_promotion".into(), Value::from(b.cx_promotion)); + m.insert("constraints".into(), Value::from(b.constraints.clone())); + m.insert("v".into(), Value::String(AUTHORIZE_BINDING_VERSION.into())); + let mut out = b"aien.authorize.mac\0".to_vec(); + out.extend(Value::Object(m).to_string().into_bytes()); + out +} + +impl DeskKey { + /// Desk side: the MAC (hex) for one authorize. `desk_key_id` is filled + /// from this key, whatever `b` carries. + pub fn sign_authorize(&self, b: &AuthorizeBinding) -> String { + let mut b = b.clone(); + b.desk_key_id = self.id.clone(); + hex(&hmac_sha256(&self.key, &authorize_binding_bytes(&b))) + } + + /// Daemon side: `Ok(())` only when `mac` is this key's MAC over `b`. + pub fn verify_authorize(&self, b: &AuthorizeBinding, mac: &str) -> Result<(), String> { + let mut b = b.clone(); + b.desk_key_id = self.id.clone(); + let want = hmac_sha256(&self.key, &authorize_binding_bytes(&b)); + match unhex32(mac) { + Some(g) if ct_eq(&g, &want) => Ok(()), + _ => Err(format!( + "authorize_mac is not the approval desk's (key {}) MAC over this proposal, path, content, workspace, approver and nonce", + 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. diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 052656c0..576cf3e7 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -156,6 +156,11 @@ pub enum ControlCommand { workspace: String, approver: String, constraints: Vec<u64>, + /// sovereign-core #297: the approval desk's MAC over this authorize. + /// Optional on the wire (old clients omit it; `None` is not written). + /// Required only when the daemon runs with the desk switch ON. + #[serde(default, skip_serializing_if = "Option::is_none")] + desk_proof: Option<DeskProof>, }, /// NEXT-PHASE-2: operator `stop`, `resume`, `revoke` (ACCEPTANCE-v2 2.5, 2.6). ComposeControl { @@ -165,6 +170,15 @@ pub enum ControlCommand { }, } +/// The desk key's proof for one `ComposeAuthorize` (sovereign-core #297): a +/// fresh nonce and the HMAC over the authorize binding +/// (`approved_auth::AuthorizeBinding`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeskProof { + pub nonce: String, + pub mac: String, +} + /// An operator's decision for one unsettled effect. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ReconcileDeclare { diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index ea4e2ef0..246e4934 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -225,6 +225,8 @@ pub struct Ledger { pub commits: BTreeMap<u64, CommitRow>, /// Minted grants by compose-commit record, oldest first. pub minted_by_commit: BTreeMap<u64, Vec<u64>>, + /// Desk-MAC nonces already used by a minted grant (#297): one grant per nonce. + pub desk_nonces: std::collections::BTreeSet<String>, pub intents: BTreeMap<u64, IntentRow>, /// authorization id -> intent id (one intent per authorization). pub spent: BTreeMap<u64, u64>, @@ -328,6 +330,9 @@ impl Ledger { Some(_) => { let commit = u(&v, "compose_commit", id)?; self.minted_by_commit.entry(commit).or_default().push(id); + if let Some(n) = v.get("desk_nonce").and_then(Value::as_str) { + self.desk_nonces.insert(n.to_string()); + } Some(MintedGrant { commit }) } }, @@ -984,6 +989,19 @@ pub struct MintRequest { /// 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 { + authorize(b, req, None) +} + +/// `ComposeAuthorize` with the optional approval-desk proof (#297). When the +/// bridge runs with the desk switch ON, a missing or wrong proof, a missing +/// desk key, a MAC over other fields, or a reused nonce is refused and +/// NOTHING is written. With the switch OFF the proof is ignored (legacy +/// behaviour: OS-user authentication only). +pub fn authorize( + b: &ComposeBridge, + req: &MintRequest, + proof: Option<&crate::control::DeskProof>, +) -> ControlResponse { if let Err(e) = reconcile_gate(b) { return ControlResponse::Error(e); } @@ -995,6 +1013,25 @@ pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { if req.constraints.len() > 3 { return Err(no("NotAuthorized", "at most 3 constraint links".into())); } + let desk = if b.authorize_requires_desk() { + let Some(p) = proof else { + return Err(no( + "DeskMacRequired", + "this daemon requires the approval desk MAC on ComposeAuthorize (AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=1); none was supplied".into(), + )); + }; + if p.nonce.is_empty() + || p.nonce.len() > 128 + || !p.nonce.bytes().all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c)) + { + return Err(no("DeskMacInvalid", "nonce must be 1 to 128 of [A-Za-z0-9._-]".into())); + } + let key = crate::approved_auth::DeskKey::load(&crate::approved_auth::desk_key_path(b.dir())) + .map_err(|e| no("NoDesk", e))?; + Some((key, p)) + } else { + None + }; let l = ledger(home)?; let mut hits = l .commits @@ -1021,6 +1058,29 @@ pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { } 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())?; + if let Some((key, p)) = &desk { + // Path, content and workspace are the daemon's own commit record; + // the MAC must cover exactly those. + let binding = crate::approved_auth::AuthorizeBinding { + cx_promotion: c.cx_promotion, + proposal_sha256: c.proposal_sha256.clone(), + path: c.path.clone(), + content_sha256: c.content_sha256.clone(), + workspace: c.workspace.clone(), + approver: req.approver.trim().to_string(), + constraints: req.constraints.clone(), + nonce: p.nonce.clone(), + desk_key_id: key.id().to_string(), + }; + key.verify_authorize(&binding, &p.mac) + .map_err(|e| no("DeskMacInvalid", e))?; + if l.desk_nonces.contains(&p.nonce) { + return Err(no( + "Replayed", + format!("authorize nonce {} already minted a grant; a replayed authorize mints nothing", p.nonce), + )); + } + } 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) { @@ -1061,12 +1121,16 @@ pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { } let mut links = vec![c.id]; links.extend(&req.constraints); - let text = json!({ + let mut 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, }); + if let Some((key, p)) = &desk { + text["desk_nonce"] = json!(p.nonce); + text["desk_key_id"] = json!(key.id()); + } append(home, NoteKind::Authorization, &links, &text) })) } diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 8c59db73..7186ea84 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -128,6 +128,7 @@ impl AienRuntimeServer { crate::spine::compose_doc_max_tokens_from_env() .map_err(|e| format!("compose limits: {e}"))?; + let authorize_desk = crate::spine::authorize_requires_desk_from_env()?; let listener = UnixListener::bind(&self.socket_path).map_err(|e| { format!( "Failed to bind runtime UNIX domain socket at {}: {}", @@ -218,7 +219,8 @@ impl AienRuntimeServer { self.spine.clone(), self.tokenizer.clone(), tokio::runtime::Handle::current(), - )?), + )?) + .with_authorize_requires_desk(authorize_desk), )), Err(e) => { tracing::warn!("compose bridge disabled: {e}"); @@ -230,6 +232,16 @@ impl AienRuntimeServer { // A failed or refused reconcile does not stop the daemon, but every // effect command refuses until an operator reconcile succeeds // (ACCEPTANCE-v3 2.5). + if let Some(b) = compose.as_ref() { + println!( + "Authorize MAC: {}", + if b.authorize_requires_desk() { + "on (aien compose authorize requires the approval desk key MAC)" + } else { + "off (authorize is authenticated by the OS user only)" + } + ); + } if let Some(b) = compose.clone() { let gate = b.clone(); let line = @@ -827,6 +839,7 @@ async fn handle_connection( ref workspace, ref approver, ref constraints, + ref desk_proof, } => { let req = crate::effects::MintRequest { cx_promotion, @@ -835,8 +848,9 @@ async fn handle_connection( approver: approver.clone(), constraints: constraints.clone(), }; + let proof = desk_proof.clone(); Some(Box::new(move |b: &Arc<ComposeBridge>| { - crate::effects::mint_grant(b, &req) + crate::effects::authorize(b, &req, proof.as_ref()) })) } ControlCommand::ComposeRecall { ref ids, prefix } => { diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index efa7b8ba..6a98fafd 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -977,6 +977,19 @@ fn env_opt(name: &str) -> Result<Option<String>, String> { } } +/// Env switch for the desk MAC on `ComposeAuthorize` (#297): `1` = required, +/// unset or `0` = off. Anything else stops the daemon (a typo must not leave +/// the requirement silently off). +pub const AUTHORIZE_DESK_ENV: &str = "AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK"; + +pub fn authorize_requires_desk_from_env() -> Result<bool, String> { + match env_opt(AUTHORIZE_DESK_ENV)?.as_deref() { + None | Some("0") => Ok(false), + Some("1") => Ok(true), + Some(o) => Err(format!("{AUTHORIZE_DESK_ENV} must be 1 or 0, got {o:?}")), + } +} + /// Both budgets from the environment. Refuses the retired single-budget /// setting (a stale `AIEN_COMPOSE_BUDGET_MS` must not be silently ignored). pub fn compose_budgets_from_env() -> Result<ComposeBudgets, String> { @@ -1730,6 +1743,9 @@ pub struct ComposeBridge { /// Set when the start-up reconcile failed or was refused (ACCEPTANCE-v3 /// 2.5): effect commands refuse until an operator reconcile succeeds. reconcile_failed: std::sync::Mutex<Option<String>>, + /// sovereign-core #297: when true, `ComposeAuthorize` needs the approval + /// desk's MAC. Default false (legacy OS-user-only authorize). + authorize_requires_desk: bool, } impl ComposeBridge { @@ -1741,6 +1757,7 @@ impl ComposeBridge { proposer_label: proposer_label.to_string(), home: std::sync::Mutex::new(None), reconcile_failed: std::sync::Mutex::new(None), + authorize_requires_desk: false, } } @@ -1750,6 +1767,17 @@ impl ComposeBridge { self } + /// Turn the desk-MAC requirement on `ComposeAuthorize` on or off (#297). + pub fn with_authorize_requires_desk(mut self, on: bool) -> Self { + self.authorize_requires_desk = on; + self + } + + /// True when `ComposeAuthorize` needs the approval desk's MAC (#297). + pub fn authorize_requires_desk(&self) -> bool { + self.authorize_requires_desk + } + pub fn dir(&self) -> &Path { &self.dir } diff --git a/crates/aien-runtime/tests/authorize_desk_mac_test.rs b/crates/aien-runtime/tests/authorize_desk_mac_test.rs new file mode 100644 index 00000000..2dcae9a6 --- /dev/null +++ b/crates/aien-runtime/tests/authorize_desk_mac_test.rs @@ -0,0 +1,426 @@ +//! sovereign-core #297: optional approval-desk MAC on `ComposeAuthorize`. +//! +//! Driven at the bridge like minted_grant_test.rs (the socket tests' mock +//! backend cannot commit a proposal). Each test builds its OWN compose home +//! (and so its own desk key) in a fresh temp dir; nothing is shared. Every +//! test needs the linked composition archive and is IGNORED in a stub build, +//! never passed. +use aien_omega_compose::hex; +use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; +use aien_runtime::control::{ComposeNoteReport, ComposeTaskReport, ControlResponse, DeskProof}; +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::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +const PROPOSALS: [&str; 2] = [ + "filename: NOTES.md\nkeep every change inside the workspace\n", + "filename: OTHER.md\nsecond note for a different proposal\n", +]; +const CONTENTS: [&str; 2] = [ + "keep every change inside the workspace\n", + "second note for a different proposal\n", +]; +const PATHS: [&str; 2] = ["NOTES.md", "OTHER.md"]; + +fn proposer() -> ComposeProposer { + let n = Arc::new(AtomicUsize::new(0)); + Arc::new(move |_prompt: &str, _limit: std::time::Duration| { + let i = n.fetch_add(1, Ordering::SeqCst).min(1); + Ok(Generation { + text: PROPOSALS[i].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:?}"), + } +} + +fn refusal(r: ControlResponse, attack: &str) -> String { + match r { + ControlResponse::Error(e) => e, + other => panic!("ATTACK SUCCEEDED ({attack}): {other:?}"), + } +} + +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, + /// Two committed proposals (A = NOTES.md, B = OTHER.md). + reports: [ComposeTaskReport; 2], + key: DeskKey, +} + +impl Fx { + /// `on`: the desk switch. `with_key`: create the desk key file. + fn new(on: bool, with_key: bool) -> Option<Fx> { + 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") + .with_authorize_requires_desk(on); + let mut reports = vec![]; + for _ in 0..2 { + 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(r) = run else { + panic!("run: {run:?}") + }; + assert!(r.committed, "{r:?}"); + reports.push(*r); + } + // The desk key lives in this fixture's own compose home. + let kp = desk_key_path(&home); + let key = if with_key { + DeskKey::create(&kp).unwrap() + } else { + // A key that exists only in memory: signs, but the daemon has none. + DeskKey::create(&tmp.path().join("elsewhere.key")).unwrap() + }; + let [a, bb] = <[ComposeTaskReport; 2]>::try_from(reports).unwrap(); + Some(Fx { + _turn: turn, + _tmp: tmp, + home, + ws, + b, + reports: [a, bb], + key, + }) + } + + fn target(&self, i: usize) -> String { + self.ws.join(PATHS[i]).display().to_string() + } + + fn req(&self, i: usize) -> MintRequest { + MintRequest { + cx_promotion: self.reports[i].cx_promotion, + proposal_sha256: sha(PROPOSALS[i].as_bytes()), + workspace: self.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + } + } + + fn binding(&self, i: usize, nonce: &str) -> AuthorizeBinding { + let r = self.req(i); + AuthorizeBinding { + cx_promotion: r.cx_promotion, + proposal_sha256: r.proposal_sha256, + path: PATHS[i].into(), + content_sha256: sha(CONTENTS[i].as_bytes()), + workspace: self.ws.display().to_string(), + approver: r.approver, + constraints: vec![], + nonce: nonce.into(), + desk_key_id: String::new(), + } + } + + fn proof(&self, key: &DeskKey, b: &AuthorizeBinding) -> DeskProof { + DeskProof { + nonce: b.nonce.clone(), + mac: key.sign_authorize(b), + } + } + + fn good(&self, i: usize, nonce: &str) -> DeskProof { + self.proof(&self.key, &self.binding(i, nonce)) + } + + fn auth(&self, i: usize, p: Option<&DeskProof>) -> ControlResponse { + effects::authorize(&self.b, &self.req(i), p) + } + + /// Id the next record gets: a refusal must not have consumed one. + fn next_id(&self) -> u64 { + noted(self.b.note("constraint", "probe", &[])).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 intent(&self, a: u64, i: usize) -> IntentRequest { + let (pid, start) = effects::self_executor(); + IntentRequest { + authorization: a, + proposal_sha256: sha(PROPOSALS[i].as_bytes()), + path: PATHS[i].into(), + target: self.target(i), + content_sha256: sha(CONTENTS[i].as_bytes()), + executor_pid: pid, + executor_start: start, + } + } +} + +macro_rules! linked_test { + ($name:ident, $on:expr, $key:expr, |$fx:ident| $body:block) => { + #[test] + #[cfg_attr(not(compose_linked), ignore = "needs the linked librx_compose.a")] + fn $name() { + let Some($fx) = Fx::new($on, $key) else { + return; + }; + $body + } + }; +} + +/// Asserts the refusal names `name` and that no record was written by it. +fn refused_clean(fx: &Fx, r: ControlResponse, name: &str, what: &str) { + let before = fx.next_id(); + let e = refusal(r, what); + assert!(e.contains(name), "{what}: {e}"); + assert_eq!(fx.next_id(), before + 1, "{what}: a refusal wrote a record"); +} + +linked_test!( + switch_on_no_mac_is_refused_and_writes_nothing, + true, + true, + |fx| { + refused_clean(&fx, fx.auth(0, None), "DeskMacRequired", "no MAC"); + // The legacy entry point is the same gate. + refused_clean( + &fx, + effects::mint_grant(&fx.b, &fx.req(0)), + "DeskMacRequired", + "mint_grant without MAC", + ); + } +); + +linked_test!(switch_on_wrong_key_is_refused, true, true, |fx| { + let other = DeskKey::create(&fx.home.parent().unwrap().join("other.key")).unwrap(); + let p = fx.proof(&other, &fx.binding(0, "n1")); + refused_clean(&fx, fx.auth(0, Some(&p)), "DeskMacInvalid", "wrong key"); + let junk = DeskProof { + nonce: "n1".into(), + mac: "zz".into(), + }; + refused_clean(&fx, fx.auth(0, Some(&junk)), "DeskMacInvalid", "junk MAC"); +}); + +linked_test!( + switch_on_mac_for_proposal_a_fails_on_proposal_b, + true, + true, + |fx| { + let for_a = fx.good(0, "n-a"); + refused_clean( + &fx, + fx.auth(1, Some(&for_a)), + "DeskMacInvalid", + "A's MAC on B", + ); + } +); + +linked_test!(switch_on_every_bound_field_is_checked, true, true, |fx| { + type Mutate = fn(&mut AuthorizeBinding); + let cases: [(&str, Mutate); 7] = [ + ("proposal", |b| b.proposal_sha256 = sha(b"other")), + ("path", |b| b.path = "ELSE.md".into()), + ("content", |b| b.content_sha256 = sha(b"evil\n")), + ("workspace", |b| b.workspace = "/tmp".into()), + ("approver", |b| b.approver = "mallory".into()), + ("constraints", |b| b.constraints = vec![1]), + ("promotion", |b| b.cx_promotion += 1), + ]; + for (what, mutate) in cases { + let mut b = fx.binding(0, "n-f"); + mutate(&mut b); + let p = fx.proof(&fx.key, &b); + refused_clean(&fx, fx.auth(0, Some(&p)), "DeskMacInvalid", what); + } + // A MAC made over one nonce does not carry another. + let mut p = fx.good(0, "n-1"); + p.nonce = "n-2".into(); + refused_clean(&fx, fx.auth(0, Some(&p)), "DeskMacInvalid", "swapped nonce"); +}); + +linked_test!( + switch_on_correct_mac_mints_and_the_effect_runs, + true, + true, + |fx| { + let p = fx.good(0, "n-ok"); + let g = noted(fx.auth(0, Some(&p))); + let t = fx.text(g.id); + assert_eq!(t["minted_grant"], 1); + assert_eq!(t["desk_nonce"], "n-ok"); + assert_eq!(t["desk_key_id"], fx.key.id()); + let i = noted(effects::open_intent(&fx.b, &fx.intent(g.id, 0))).id; + std::fs::write(fx.target(0), CONTENTS[0]).unwrap(); + let a = noted(effects::ack(&fx.b, i, &json!({"executor": "test"}))); + assert_eq!(fx.text(a.id)["state"], "DONE"); + assert_eq!(std::fs::read_to_string(fx.target(0)).unwrap(), CONTENTS[0]); + } +); + +linked_test!(switch_on_replay_mints_no_second_grant, true, true, |fx| { + let p = fx.good(0, "n-once"); + let g1 = noted(fx.auth(0, Some(&p))).id; + // Same request again while the grant is live. + refused_clean(&fx, fx.auth(0, Some(&p)), "Replayed", "replay while live"); + // After a revoke the proposal could be authorized again, but not by the + // same MAC: the nonce is spent. + effects::control(&fx.b, "revoke", "drake", Some(g1)); + refused_clean(&fx, fx.auth(0, Some(&p)), "Replayed", "replay after revoke"); + // A fresh authorize (new nonce, new MAC) does mint. + let g2 = noted(fx.auth(0, Some(&fx.good(0, "n-twice")))).id; + assert_ne!(g1, g2); +}); + +linked_test!( + switch_on_missing_key_file_refuses_no_silent_fallback, + true, + false, + |fx| { + assert!(!desk_key_path(&fx.home).exists()); + // Even a MAC made with some other key, and no MAC at all: both refused. + let p = fx.good(0, "n-nokey"); + refused_clean(&fx, fx.auth(0, Some(&p)), "NoDesk", "key file missing"); + refused_clean(&fx, fx.auth(0, None), "DeskMacRequired", "no MAC, no key"); + } +); + +linked_test!( + switch_on_rotated_key_refuses_the_old_mac, + true, + true, + |fx| { + let old = fx.good(0, "n-old"); + std::fs::remove_file(desk_key_path(&fx.home)).unwrap(); + let new = DeskKey::create(&desk_key_path(&fx.home)).unwrap(); + assert_ne!(new.id(), fx.key.id()); + refused_clean( + &fx, + fx.auth(0, Some(&old)), + "DeskMacInvalid", + "old MAC after rotation", + ); + let p = fx.proof(&new, &fx.binding(0, "n-new")); + noted(fx.auth(0, Some(&p))); + } +); + +linked_test!(switch_on_rejects_a_bad_nonce, true, true, |fx| { + for n in ["", "has space", &"x".repeat(129)] { + let p = fx.good(0, n); + refused_clean(&fx, fx.auth(0, Some(&p)), "DeskMacInvalid", "bad nonce"); + } +}); + +// Legacy behaviour, NOT a security pass: with the switch off the daemon +// authenticates the operator by OS user only, exactly as before #297. A proof, +// good or bad, is ignored and not recorded. +linked_test!(switch_off_legacy_authorize_still_works, false, true, |fx| { + let g = noted(fx.auth(0, None)); + assert!(fx.text(g.id).get("desk_nonce").is_none()); + let bad = DeskProof { + nonce: "n".into(), + mac: "00".into(), + }; + let g2 = noted(fx.auth(1, Some(&bad))); + assert!(fx.text(g2.id).get("desk_nonce").is_none()); + let i = noted(effects::open_intent(&fx.b, &fx.intent(g.id, 0))).id; + std::fs::write(fx.target(0), CONTENTS[0]).unwrap(); + let a = noted(effects::ack(&fx.b, i, &json!({"executor": "test"}))); + assert_eq!(fx.text(a.id)["state"], "DONE"); +}); + +#[test] +fn the_wire_field_is_optional_and_old_clients_parse() { + use aien_runtime::control::ControlCommand; + // An old client's line has no desk_proof: it parses, with None. + let old = r#"{"ComposeAuthorize":{"cx_promotion":3,"proposal_sha256":"p","workspace":"/w","approver":"a","constraints":[]}}"#; + match serde_json::from_str::<ControlCommand>(old).unwrap() { + ControlCommand::ComposeAuthorize { desk_proof, .. } => assert!(desk_proof.is_none()), + other => panic!("{other:?}"), + } + // None is not written, so an old daemon sees the old shape. + let none = ControlCommand::ComposeAuthorize { + cx_promotion: 3, + proposal_sha256: "p".into(), + workspace: "/w".into(), + approver: "a".into(), + constraints: vec![], + desk_proof: None, + }; + assert_eq!(serde_json::to_string(&none).unwrap(), old); + // A new line with the proof round-trips. + let with = ControlCommand::ComposeAuthorize { + cx_promotion: 3, + proposal_sha256: "p".into(), + workspace: "/w".into(), + approver: "a".into(), + constraints: vec![], + desk_proof: Some(DeskProof { + nonce: "n".into(), + mac: "m".into(), + }), + }; + let s = serde_json::to_string(&with).unwrap(); + assert!(s.contains("desk_proof")); + assert!(matches!( + serde_json::from_str::<ControlCommand>(&s).unwrap(), + ControlCommand::ComposeAuthorize { + desk_proof: Some(_), + .. + } + )); +} + +#[test] +fn the_env_switch_is_strict() { + // Pure parse check on the daemon's reader; run in one test so the + // process-wide env is not raced by another test. + use aien_runtime::spine::{authorize_requires_desk_from_env, AUTHORIZE_DESK_ENV}; + let _g = ONE_HOME.lock().unwrap_or_else(|e| e.into_inner()); + std::env::remove_var(AUTHORIZE_DESK_ENV); + assert_eq!(authorize_requires_desk_from_env(), Ok(false)); + std::env::set_var(AUTHORIZE_DESK_ENV, "0"); + assert_eq!(authorize_requires_desk_from_env(), Ok(false)); + std::env::set_var(AUTHORIZE_DESK_ENV, "1"); + assert_eq!(authorize_requires_desk_from_env(), Ok(true)); + std::env::set_var(AUTHORIZE_DESK_ENV, "yes"); + assert!(authorize_requires_desk_from_env().is_err()); + std::env::remove_var(AUTHORIZE_DESK_ENV); +} diff --git a/scripts/.crumb b/scripts/.crumb index e27f28b5..a32c9699 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -4,14 +4,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-07T04:01:59Z", + "compiled_at": "2026-10-08T02:27:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:5113f380d92d17b79f3676f303677c86b6980132671208b070eb84ec6ceee3ba", + "digest": "sha256:c34ee7424ed8e187cd76e8c971904972f2f839e592cbe52b8779158e00522713", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 23, - "generated_at_commit": "997158b861e3772973a46c960660f97b6923b43a", - "source_tree": "sha256:bebc9e8e1efcc1da4afb935f11cd06121ddb229196f05259e5a46e1cd46a6eb2" + "files": 24, + "generated_at_commit": "cffee10466c5621ed586faff5fff49f7bdf4a1ee", + "source_tree": "sha256:513f5b3043e53664bd22cd5e03d8221ae76889d45258a9670245c61c4d516253" } }, "parent": {