Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-runtime/src/approved.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-runtime / src / approved.rs` 655 lines ยท 27446 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Proposer hook: an approved proposal enters the production compose path. 17 //! 18 //! The approval desk upstream (INTERPLANE `ComposeLedgerAuthority`, 19 //! interplane#77) hands over one file change it approved. `ProposerHook` 20 //! checks it, then drives it through the same compose run `RunComposeTask` 21 //! uses: the model Skill returns the approved text instead of calling the 22 //! model, AEGIS checks it with the bridge's verify callback, the winner 23 //! commits through the World on a J-Space branch, Cortex records it. 24 //! 25 //! The hook grants nothing. It never writes the workspace and never mints an 26 //! authorization: the effect still needs an `authorization` note, a 27 //! `ComposeEffectIntent` and an ack (crate::effects). Anything it cannot 28 //! verify, any duplicate and any run that does not commit is refused with a 29 //! named error (`PROPOSAL_REFUSED : ...`), never dropped. 30 //! 31 //! Hash semantics (both are reported, never conflated): 32 //! - `approved_proposal_sha256`: sha256 of the compact JSON object 33 //! `{"content":..,"path":..}` with sorted keys, as interplane#77 computes it. 34 //! - `compose_proposal_sha256`: sha256 of the committed proposal text 35 //! (`filename: \n`), the value `aien compose authorize` puts 36 //! in the authorization grant and `ComposeEffectIntent` must repeat. 37 //! 38 //! Authentication (#249 A, crate::approved_auth): `approval_mac` must be the 39 //! approval desk key's HMAC over every approved field, else `Unauthenticated`. 40 //! Replay (#249 B, crate::approved_replay): the approval is claimed durably 41 //! in the Cortex journal before the run and settled after it (committed, 42 //! failed, uncertain); a claimed request id, approval id or approval key is 43 //! refused for ever, across restarts. 44 //! 45 //! Design note: docs/COMPOSE_PROPOSER_HOOK.md. 46 use crate::approved_auth::{ 47 approval_key, check_confinement, desk_key_path, ApprovalIdentity, DeskKey, 48 }; 49 use crate::approved_replay::{self, ClaimKeys, CommitEvidence}; 50 use crate::compose::{check_file_proposal, ComposeBridge}; 51 use crate::control::ComposeTaskReport; 52 use crate::effects::{write_approved_grant, ApprovedLink}; 53 use aien_omega_compose::hex; 54 use serde::{Deserialize, Serialize}; 55 use serde_json::{Map, Value}; 56 use sha2::{Digest, Sha256}; 57 use std::path::Path; 58 use std::sync::Arc; 59 60 /// Prefix of every hook refusal. 61 pub const REFUSED: &str = "PROPOSAL_REFUSED"; 62 63 /// One file change an upstream approval desk approved (the interplane#77 64 /// ledger fields plus the correlation ids). 65 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 66 pub struct ApprovedProposal { 67 /// INTERPLANE request id and trace id: carried into the report. 68 pub request_id: String, 69 pub trace_id: String, 70 /// The approval the desk consumed (single use). 71 pub approval_id: String, 72 pub approver: String, 73 /// Workspace-relative path and the complete new content. 74 pub path: String, 75 pub content: String, 76 /// `approved_proposal_sha256(path, content)` as the desk computed it. 77 pub approved_proposal_sha256: String, 78 /// sha256 of `content`. 79 pub content_sha256: String, 80 /// HMAC-SHA256 (hex) of the approval binding under the approval desk key 81 /// (crate::approved_auth). Never caller text: only the desk key holder 82 /// can make it. 83 pub approval_mac: String, 84 /// The goal text whose measurable requirements the approved bytes must 85 /// meet (crate::requirements), bound by `requirements_mac`. `Some("")` is 86 /// an explicit, signed "no requirements"; `None` (field missing) is 87 /// refused: an absent binding is never read as an empty requirement set. 88 #[serde(default)] 89 pub requirements: Option, 90 /// HMAC-SHA256 (hex) under the desk key over the approval binding and 91 /// `requirements` (crate::approved_auth::DeskKey::sign_requirements). 92 #[serde(default)] 93 pub requirements_mac: String, 94 /// Only when a requirement depends on the file the bytes replace (an added-line 95 /// count): the sha256 (hex) of that file as the desk saw it, or "absent". Bound by 96 /// `requirements_mac` (tag v2). The daemon refuses unless the file still has this 97 /// sha256 when the grant is written (same compose-home lock). 98 #[serde(default)] 99 pub requirements_base: Option, 100 } 101 102 /// What a committed approved proposal hands to the effect ledger. 103 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 104 pub struct ApprovedComposeReport { 105 /// "COMMITTED" (this submission ran and the World committed it) or 106 /// "ALREADY_COMMITTED" (a retry of the same authenticated approval whose 107 /// first response was lost: nothing ran again, `task` is None and the 108 /// evidence is the original run's, read from the replay ledger). 109 pub state: String, 110 pub request_id: String, 111 pub trace_id: String, 112 pub approval_id: String, 113 pub approver: String, 114 pub path: String, 115 pub content_sha256: String, 116 pub approved_proposal_sha256: String, 117 /// sha256 of the committed proposal text: the authorization grant and the 118 /// effect intent must name this value. 119 pub compose_proposal_sha256: String, 120 /// Links the authorization grant carries, as `aien compose authorize` 121 /// does: [cx_promotion, cx_evidence]. 122 pub grant_links: Vec, 123 /// The desk key that authenticated the approval (its id, never the key). 124 pub desk_key_id: String, 125 /// The durable replay key (crate::approved_auth::approval_key). 126 pub approval_key: String, 127 /// The replay claim (its `accepted` record id in the Cortex journal). 128 pub replay_claim: u64, 129 /// The compose run (J-Space branch, AEGIS verdict, World commit records); 130 /// None for ALREADY_COMMITTED. 131 pub task: Option, 132 /// The authorization grant the daemon wrote for this approval (reserved 133 /// `approved_grant` record, keyed on `compose_proposal_sha256`, linked to 134 /// promotion, evidence and the replay claim). The effect intent names it; 135 /// a caller never writes its own. None for ALREADY_COMMITTED. 136 #[serde(default)] 137 pub approved_grant: Option, 138 /// The grant's absolute target (`/`). 139 #[serde(default)] 140 pub target: Option, 141 } 142 143 /// A refusal of the approved-proposal command, with the correlation ids. 144 /// `refused_by` is "PROPOSAL_REFUSED" (checks before or around the run) or 145 /// "REPLAY_REFUSED" (crate::approved_replay); `name` is the refusal name. 146 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 147 pub struct ApprovedRefusal { 148 pub refused_by: String, 149 pub name: String, 150 pub detail: String, 151 pub request_id: String, 152 pub trace_id: String, 153 pub approval_id: String, 154 /// The replay claim the refusal concerns, when there is one. 155 pub replay_claim: Option, 156 } 157 158 impl std::fmt::Display for ApprovedRefusal { 159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 160 write!(f, "{} {}: {}", self.refused_by, self.name, self.detail) 161 } 162 } 163 164 impl ApprovedRefusal { 165 /// From a " : detail" text. 166 fn from_text(p: &ApprovedProposal, text: &str, claim: Option) -> Box { 167 let (head, detail) = text.split_once(": ").unwrap_or((text, "")); 168 let (by, name) = head.split_once(' ').unwrap_or((REFUSED, head)); 169 Box::new(Self { 170 refused_by: by.to_string(), 171 name: name.to_string(), 172 detail: detail.to_string(), 173 request_id: p.request_id.clone(), 174 trace_id: p.trace_id.clone(), 175 approval_id: p.approval_id.clone(), 176 replay_claim: claim, 177 }) 178 } 179 } 180 181 fn sha256_hex(b: &[u8]) -> String { 182 hex(&Sha256::digest(b)) 183 } 184 185 /// Start of the machine goal of an approved run. It carries the desk-supplied path, not 186 /// a requirement statement: the run does not read requirements out of it (the 187 /// goal bound into the approval was checked on the same bytes before the claim). 188 pub(crate) const APPROVED_GOAL_PREFIX: &str = "apply approved proposal for "; 189 190 fn refuse(name: &str, why: impl std::fmt::Display) -> String { 191 format!("{REFUSED} {name}: {why}") 192 } 193 194 /// sha256 of the compact JSON `{"content":..,"path":..}`, keys sorted 195 /// (inserted in sorted order, so serde_json's map ordering does not matter). 196 pub fn approved_proposal_sha256(path: &str, content: &str) -> String { 197 let mut m = Map::new(); 198 m.insert("content".into(), Value::String(content.to_string())); 199 m.insert("path".into(), Value::String(path.to_string())); 200 sha256_hex(Value::Object(m).to_string().as_bytes()) 201 } 202 203 /// The proposal text in the compose template. Refused unless the template 204 /// parser reads back exactly this path and content (a content the parser 205 /// would normalise is refused, not silently changed). 206 pub fn proposal_text(path: &str, content: &str) -> Result { 207 let text = format!("filename: {path}\n{content}"); 208 let p = check_file_proposal(&text).map_err(|e| refuse("Unverified", e))?; 209 if p.path != path || p.content != content { 210 return Err(refuse( 211 "Unverified", 212 "content does not read back unchanged through the compose template \ 213 (it must end with one newline, not start with a blank line or a code fence)", 214 )); 215 } 216 Ok(text) 217 } 218 219 /// Every check that needs no compose home. Ok = the proposal text. 220 pub fn verify(p: &ApprovedProposal) -> Result { 221 for (k, v) in [ 222 ("request_id", &p.request_id), 223 ("trace_id", &p.trace_id), 224 ("approval_id", &p.approval_id), 225 ("approver", &p.approver), 226 ] { 227 if v.trim().is_empty() { 228 return Err(refuse("Unverified", format!("empty {k}"))); 229 } 230 } 231 if sha256_hex(p.content.as_bytes()) != p.content_sha256 { 232 return Err(refuse( 233 "Unverified", 234 "content_sha256 does not match content", 235 )); 236 } 237 if approved_proposal_sha256(&p.path, &p.content) != p.approved_proposal_sha256 { 238 return Err(refuse( 239 "Unverified", 240 "approved_proposal_sha256 does not match {content, path}", 241 )); 242 } 243 if p.requirements.is_none() { 244 return Err(refuse( 245 "RequirementsUnbound", 246 "the approval carries no requirement binding (requirements); an absent binding is refused, sign an empty goal for none", 247 )); 248 } 249 proposal_text(&p.path, &p.content) 250 } 251 252 /// The requirements the desk bound to this approval, checked on the exact 253 /// approved content (the bytes that would be saved). Uncertain wording refuses. 254 fn check_bound_requirements(p: &ApprovedProposal, workspace: &Path) -> Result<(), String> { 255 let goal = p.requirements.as_deref().ok_or_else(|| { 256 refuse( 257 "RequirementsUnbound", 258 "the approval carries no requirement binding", 259 ) 260 })?; 261 let mut ex = crate::requirements::analyze(goal); 262 if let Some(why) = ex.refusal() { 263 return Err(refuse("RequirementsUncertain", why)); 264 } 265 if ex.needs_prior() { 266 // An added-line count is judged against the file these bytes replace. 267 let class = if p.path.contains(char::is_whitespace) { 268 crate::compose::TargetClass::Refused(String::new()) 269 } else { 270 crate::compose::classify_target(&p.path, workspace) 271 }; 272 let (prior, exists) = 273 match class { 274 crate::compose::TargetClass::Edit(_, c) => (c, true), 275 crate::compose::TargetClass::New => (String::new(), false), 276 _ => return Err(refuse( 277 "RequirementsUnmet", 278 "the existing file cannot be read, so the added-line count cannot be measured", 279 )), 280 }; 281 let base = p.requirements_base.as_deref().ok_or_else(|| { 282 refuse( 283 "RequirementsUnbound", 284 "a requirement depends on the file these bytes replace, so the approval must bind requirements_base (its sha256, or \"absent\")", 285 ) 286 })?; 287 let now = if exists { 288 sha256_hex(prior.as_bytes()) 289 } else { 290 "absent".to_string() 291 }; 292 if now != base { 293 return Err(refuse( 294 "BaseChanged", 295 format!("the file changed since the desk bound it (bound {base}, now {now})"), 296 )); 297 } 298 ex = ex.resolved(&prior); 299 } 300 match crate::requirements::refusal_reason(&ex.requirements, &p.content) { 301 Some(why) => Err(refuse("RequirementsUnmet", why)), 302 None => Ok(()), 303 } 304 } 305 306 /// The hook over one compose bridge (the daemon's, or a test's). Replay 307 /// state lives only in the bridge's Cortex journal (crate::approved_replay): 308 /// two hooks over one compose home, or a restarted daemon, see the same claims. 309 pub struct ProposerHook { 310 bridge: Arc, 311 } 312 313 impl ProposerHook { 314 pub fn new(bridge: Arc) -> Self { 315 Self { bridge } 316 } 317 318 /// Blocking (runs the composition). Order: verify (hashes, template) -> 319 /// start-up reconcile gate -> desk key (file rules) -> confinement -> 320 /// authenticate (MAC) -> durable claim -> in_flight -> one compose run -> 321 /// committed | failed | uncertain. Nothing runs unless every step before 322 /// it passed; nothing before the claim writes a record. 323 pub fn submit( 324 &self, 325 p: &ApprovedProposal, 326 workspace: &str, 327 ) -> Result> { 328 let refusal = |t: String, c: Option| ApprovedRefusal::from_text(p, &t, c); 329 let text = verify(p).map_err(|e| refusal(e, None))?; 330 if let Some(why) = self.bridge.reconcile_failed() { 331 return Err(refusal( 332 refuse( 333 "ReconcileFailed", 334 format!("the start-up reconcile did not complete ({why}); run aien compose reconcile"), 335 ), 336 None, 337 )); 338 } 339 let identity = (|| { 340 let desk = DeskKey::load(&desk_key_path(self.bridge.dir()))?; 341 check_confinement(self.bridge.dir(), Path::new(workspace))?; 342 desk.authenticate(p, Path::new(workspace)) 343 })() 344 .map_err(|e| refusal(e, None))?; 345 // The goal requirements bound by the desk, checked on the exact approved 346 // bytes BEFORE any claim, run or commit. 347 check_bound_requirements(p, Path::new(workspace)).map_err(|e| refusal(e, None))?; 348 let keys = ClaimKeys { 349 approval_key: approval_key(&identity), 350 request_id: p.request_id.clone(), 351 approval_id: p.approval_id.clone(), 352 trace_id: p.trace_id.clone(), 353 }; 354 let claim = match approved_replay::claim(&self.bridge, &keys) { 355 Ok(c) => c, 356 Err(r) => return self.replayed(p, &identity, &keys, r), 357 }; 358 crash_point("approved_after_claim"); 359 let rr = |r: approved_replay::Refusal| refusal(r.to_string(), Some(claim.id)); 360 approved_replay::mark_in_flight(&self.bridge, &claim).map_err(|e| { 361 // Nothing ran; end the claim as not_executed if the journal lets us. 362 let _ = approved_replay::not_executed(&self.bridge, &claim, &e.to_string()); 363 rr(e) 364 })?; 365 // Exactly one compose run per claim. 366 let goal = format!( 367 "{APPROVED_GOAL_PREFIX}{} (request {})", 368 p.path, p.request_id 369 ); 370 let r = match self 371 .bridge 372 .run_approved_task(&goal, &identity.workspace, &text) 373 { 374 Ok(r) => r, 375 Err(e) => { 376 // The run may have reached the World: never guess. 377 let why = refuse("ComposeError", &e); 378 approved_replay::uncertain(&self.bridge, &claim, &why).map_err(rr)?; 379 return Err(refusal(why, Some(claim.id))); 380 } 381 }; 382 if !r.committed { 383 let why = refuse( 384 "NotCommitted", 385 format!( 386 "outcome {} (AEGIS pass mask {:#x}); {}", 387 r.outcome, 388 r.aegis_pass_mask, 389 r.proposer_error.as_deref().unwrap_or("no proposer error") 390 ), 391 ); 392 approved_replay::fail(&self.bridge, &claim, &why).map_err(rr)?; 393 return Err(refusal(why, Some(claim.id))); 394 } 395 let compose_sha = sha256_hex(text.as_bytes()); 396 // The prior file the bound requirements were checked against (None when none depends on it). 397 let base = crate::requirements::analyze(p.requirements.as_deref().unwrap_or("")) 398 .needs_prior() 399 .then(|| p.requirements_base.clone()) 400 .flatten(); 401 if r.proposal.as_deref() != Some(text.as_str()) 402 || r.proposal_sha256.as_deref() != Some(compose_sha.as_str()) 403 || r.proposal_path.as_deref() != Some(p.path.as_str()) 404 || r.proposal_content_sha256.as_deref() != Some(p.content_sha256.as_str()) 405 { 406 let why = refuse( 407 "Mismatch", 408 format!( 409 "the World committed task {} (promotion #{}) but not the approved proposal", 410 r.task, r.cx_promotion 411 ), 412 ); 413 approved_replay::uncertain(&self.bridge, &claim, &why).map_err(rr)?; 414 return Err(refusal(why, Some(claim.id))); 415 } 416 let evidence = CommitEvidence { 417 compose_proposal_sha256: compose_sha.clone(), 418 cx_promotion: r.cx_promotion, 419 cx_evidence: r.cx_evidence, 420 task: r.task, 421 }; 422 crash_point("approved_after_compose"); 423 // If this append fails the claim stays in_flight: refused forever, 424 // UNCERTAIN after a restart (fail closed). 425 approved_replay::commit(&self.bridge, &claim, &evidence).map_err(rr)?; 426 crash_point("approved_after_commit"); 427 // The one grant for this approval, written by the daemon (never by the 428 // caller). If it cannot be written the approval stays spent and no 429 // effect is possible: a new approval is needed (fail closed). 430 // The grant's target comes from the bound (MAC-covered) workspace only. 431 let link = ApprovedLink { 432 approval_key: keys.approval_key.clone(), 433 replay_claim: claim.id, 434 cx_promotion: evidence.cx_promotion, 435 cx_evidence: evidence.cx_evidence, 436 }; 437 let ids = serde_json::json!({"request_id": p.request_id, "trace_id": p.trace_id, 438 "approval_id": p.approval_id, "desk_key_id": identity.desk_key_id, 439 "approved_proposal_sha256": p.approved_proposal_sha256}); 440 #[cfg(test)] 441 if let Some(f) = BEFORE_GRANT.lock().unwrap().as_ref() { 442 f(); 443 } 444 let (grant, target) = write_approved_grant( 445 &self.bridge, 446 &identity.workspace, 447 &p.path, 448 &p.content_sha256, 449 &p.approver, 450 &ids, 451 &link, 452 &compose_sha, 453 base.as_deref(), 454 ) 455 .map_err(|e| { 456 refusal( 457 refuse( 458 "GrantNotWritten", 459 format!("the approval is committed and spent; no effect is possible: {e}"), 460 ), 461 Some(claim.id), 462 ) 463 })?; 464 let mut out = self.report( 465 p, 466 &identity, 467 &keys, 468 claim.id, 469 "COMMITTED", 470 &evidence, 471 Some(r), 472 ); 473 out.approved_grant = Some(grant); 474 out.target = Some(target); 475 Ok(out) 476 } 477 478 /// A claim refusal. A retry of the very same authenticated approval (all 479 /// keys equal) whose claim committed gets the original result back as 480 /// ALREADY_COMMITTED; everything else is refused with the claim's state. 481 fn replayed( 482 &self, 483 p: &ApprovedProposal, 484 identity: &ApprovalIdentity, 485 keys: &ClaimKeys, 486 r: approved_replay::Refusal, 487 ) -> Result> { 488 if r.name == "AlreadyCommitted" { 489 if let (Some(id), Some(ev)) = (r.claim, r.evidence.as_ref()) { 490 if self.claim_keys(id).as_ref() == Ok(keys) { 491 return Ok(self.report(p, identity, keys, id, "ALREADY_COMMITTED", ev, None)); 492 } 493 } 494 } 495 Err(ApprovedRefusal::from_text(p, &r.to_string(), r.claim)) 496 } 497 498 /// The keys a claim recorded, read back from the journal. 499 fn claim_keys(&self, id: u64) -> Result { 500 self.bridge.with_home(|home| { 501 let (recs, _) = home 502 .compose 503 .recall(aien_omega_compose::SUBJECT_HOST, 4096) 504 .map_err(|e| format!("host records: {e}"))?; 505 let views: Vec<_> = recs 506 .iter() 507 .map(|r| crate::compose::record_view(&mut home.compose, r)) 508 .collect(); 509 let l = 510 approved_replay::ReplayLedger::from_records(&views).map_err(|e| e.to_string())?; 511 l.claims 512 .get(&id) 513 .map(|row| row.keys.clone()) 514 .ok_or_else(|| format!("#{id} is not a claim")) 515 }) 516 } 517 518 #[allow(clippy::too_many_arguments)] 519 fn report( 520 &self, 521 p: &ApprovedProposal, 522 identity: &ApprovalIdentity, 523 keys: &ClaimKeys, 524 claim: u64, 525 state: &str, 526 ev: &CommitEvidence, 527 task: Option, 528 ) -> ApprovedComposeReport { 529 ApprovedComposeReport { 530 state: state.into(), 531 request_id: p.request_id.clone(), 532 trace_id: p.trace_id.clone(), 533 approval_id: p.approval_id.clone(), 534 approver: p.approver.clone(), 535 path: p.path.clone(), 536 content_sha256: p.content_sha256.clone(), 537 approved_proposal_sha256: p.approved_proposal_sha256.clone(), 538 compose_proposal_sha256: ev.compose_proposal_sha256.clone(), 539 grant_links: vec![ev.cx_promotion, ev.cx_evidence], 540 desk_key_id: identity.desk_key_id.clone(), 541 approval_key: keys.approval_key.clone(), 542 replay_claim: claim, 543 task, 544 approved_grant: None, 545 target: None, 546 } 547 } 548 } 549 550 /// Test builds only (cargo feature `fault-hold`): abort the process at the 551 /// named point when `AIEN_FAULT_HOLD` names it, to prove the crash 552 /// boundaries of #249 B. The default build compiles this to nothing. 553 #[cfg(feature = "fault-hold")] 554 fn crash_point(name: &str) { 555 if std::env::var("AIEN_FAULT_HOLD").as_deref() == Ok(name) { 556 eprintln!("fault hold {name}: aborting (test build)"); 557 std::process::abort(); 558 } 559 } 560 561 #[cfg(not(feature = "fault-hold"))] 562 fn crash_point(_: &str) {} 563 564 /// Test seam: runs between the compose commit and the grant write, where a 565 /// concurrent edit of the target would land. 566 #[cfg(test)] 567 static BEFORE_GRANT: std::sync::Mutex>> = std::sync::Mutex::new(None); 568 569 #[cfg(test)] 570 mod toctou_tests { 571 use super::*; 572 use crate::approved_auth::{desk_key_path, DeskKey}; 573 574 fn proposal(b: &ComposeBridge, ws: &Path, id: &str, base: &str) -> ApprovedProposal { 575 let content = "one\ntwo\nthree\n".to_string(); 576 let mut p = ApprovedProposal { 577 request_id: id.into(), 578 trace_id: format!("trace-{id}"), 579 approval_id: format!("appr-{id}"), 580 approver: "interplane-host".into(), 581 path: "NOTES.md".into(), 582 approved_proposal_sha256: approved_proposal_sha256("NOTES.md", &content), 583 content_sha256: sha256_hex(content.as_bytes()), 584 content, 585 approval_mac: String::new(), 586 requirements: Some("Add one line to NOTES.md".into()), 587 requirements_mac: String::new(), 588 requirements_base: Some(base.into()), 589 }; 590 DeskKey::load(&desk_key_path(b.dir())) 591 .unwrap() 592 .seal(&mut p, ws); 593 p 594 } 595 596 /// The target changes after the requirements were checked and before the 597 /// grant is written: refused with BaseChanged, nothing authorizes a write. 598 /// Unchanged, the same approval shape passes. (Linked build: the stub 599 /// refuses at the claim, before the seam.) 600 #[test] 601 fn prior_changed_between_check_and_commit_is_refused() { 602 let _home = crate::home_guard::home_slot(); 603 if !aien_omega_compose::LINKED { 604 return; 605 } 606 let tmp = tempfile::tempdir().unwrap(); 607 let ws = tmp.path().join("ws"); 608 std::fs::create_dir_all(&ws).unwrap(); 609 let proposer: crate::compose::ComposeProposer = 610 Arc::new(|_: &str, _: std::time::Duration| panic!("model ran")); 611 let b = Arc::new(ComposeBridge::new( 612 tmp.path().join("compose"), 613 proposer, 614 "t", 615 )); 616 DeskKey::create(&desk_key_path(b.dir())).unwrap(); 617 let hook = ProposerHook::new(b.clone()); 618 let wss = ws.display().to_string(); 619 let target = ws.join("NOTES.md"); 620 std::fs::write(&target, "one\ntwo\n").unwrap(); 621 let base = sha256_hex(b"one\ntwo\n"); 622 623 let t2 = target.clone(); 624 let fired = Arc::new(std::sync::atomic::AtomicBool::new(false)); 625 let f2 = fired.clone(); 626 *BEFORE_GRANT.lock().unwrap() = Some(Box::new(move || { 627 f2.store(true, std::sync::atomic::Ordering::SeqCst); 628 std::fs::write(&t2, "one\ntwo\nEXTRA\n").unwrap() 629 })); 630 let e = hook 631 .submit(&proposal(&b, &ws, "toctou1", &base), &wss) 632 .expect_err("a changed prior must be refused"); 633 *BEFORE_GRANT.lock().unwrap() = None; 634 // The seam sits after the compose commit, so firing proves the run reached it. 635 assert!( 636 fired.load(std::sync::atomic::Ordering::SeqCst), 637 "seam did not fire; refusal was {}: {}", 638 e.name, 639 e.detail 640 ); 641 eprintln!( 642 "TOCTOU seam fired after compose commit; refusal = {}: {}", 643 e.name, e.detail 644 ); 645 assert_eq!(e.name, "GrantNotWritten", "{e}"); 646 assert!(e.detail.contains("BaseChanged"), "{e}"); 647 648 // Unchanged prior: the grant is written. 649 std::fs::write(&target, "one\ntwo\n").unwrap(); 650 let ok = hook 651 .submit(&proposal(&b, &ws, "toctou2", &base), &wss) 652 .unwrap_or_else(|e| panic!("unchanged prior must pass: {e}")); 653 assert_eq!(ok.state, "COMMITTED"); 654 } 655 }