interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / adapters / aien / tests / compose_ledger_attacks.rs

558 lines · 20517 bytes Raw Blame History
1//! Attacks on the single write route of the compose-ledger cut (sovereign-core #249 item 1,
2//! interplane #77): the old client-minted authorization route can produce no write, there is no
3//! fallback write when the daemon refuses or is gone, the effect names the daemon's grant, and
4//! the write itself cannot be redirected outside the workspace.
5//!
6//! Same harness as `compose_ledger.rs` (helpers copied verbatim): needs `AIEN_BIN`, rows are
7//! `#[ignore]` (NOT_RUN) unless run with `--ignored`.
8#![allow(dead_code)]
9use interplane_adapter_aien::*;
10use interplane_core::*;
11use interplane_crossveil::Pipeline;
12use interplane_lenshift::DialectRegistry;
13use serde_json::{json, Value};
14use sha2::{Digest, Sha256};
15use std::path::{Path, PathBuf};
16use std::process::{Child, Command, Stdio};
17use std::sync::Mutex;
18use std::time::{Duration, Instant};
19
20const NOW: &str = "2026-10-06T00:00:00Z";
21const TRACE: &str = "ledger";
22const EXPECTED: &str = "Decisions: ship v0.3 on Friday.\nOwners: Ada (release), Lin (docs).\n";
23const MODEL_SNAPSHOT: &str = ".cache/huggingface/hub/models--unsloth--Llama-3.2-1B-Instruct/snapshots/5a8abab4a5d6f164389b1079fb721cfab8d7126c";
24
25/// One daemon at a time (each loads the model).
26static SERIAL: Mutex<()> = Mutex::new(());
27
28fn hex(b: &[u8]) -> String {
29 format!("{:x}", Sha256::digest(b))
30}
31
32struct Daemon {
33 child: Child,
34 root: PathBuf,
35 sock: PathBuf,
36 desk_key_id: String,
37 log: PathBuf,
38 started_ms: u128,
39 _keep: Option<tempfile::TempDir>,
40}
41
42impl Drop for Daemon {
43 fn drop(&mut self) {
44 let _ = self.child.kill();
45 let _ = self.child.wait();
46 }
47}
48
49impl Daemon {
50 fn client(&self) -> LedgerClient {
51 LedgerClient::new(&self.sock)
52 }
53 fn ws(&self) -> PathBuf {
54 self.root.join("ws")
55 }
56 fn desk(&self) -> PathBuf {
57 self.root.join("compose").join("approval-desk.key")
58 }
59}
60
61/// Start `AIEN_BIN daemon` on CPU in a fresh home. `None` (NOT_RUN, printed) when `AIEN_BIN` is
62/// unset. Panics with the log path when the daemon does not come up within 600 s.
63fn daemon(row: &str) -> Option<Daemon> {
64 let Ok(bin) = std::env::var("AIEN_BIN") else {
65 panic!("NOT_RUN {row}: AIEN_BIN is unset (needs an aien-cli daemon binary)");
66 };
67 let model = std::env::var("AIEN_LEDGER_MODEL_DIR")
68 .map(PathBuf::from)
69 .unwrap_or_else(|_| {
70 Path::new(&std::env::var("HOME").unwrap_or_default()).join(MODEL_SNAPSHOT)
71 });
72 let (keep, root) = match std::env::var("LEDGER_OUT") {
73 Ok(d) => {
74 let p = Path::new(&d).join(row);
75 let _ = std::fs::remove_dir_all(&p);
76 (None, p)
77 }
78 Err(_) => {
79 let t = tempfile::tempdir().unwrap();
80 let p = t.path().to_path_buf();
81 (Some(t), p)
82 }
83 };
84 for d in ["ws", "compose", "state", "prov"] {
85 std::fs::create_dir_all(root.join(d)).unwrap();
86 }
87 let root = std::fs::canonicalize(root).unwrap();
88 let (sock, log) = (root.join("aien.sock"), root.join("daemon.log"));
89 // The approval desk key, made by the CLI step in the compose home (outside the workspace).
90 let made = Command::new(&bin)
91 .args(["compose", "desk-key", "--create", "1"])
92 .env("AIEN_COMPOSE_DIR", root.join("compose"))
93 .output()
94 .expect("aien compose desk-key");
95 assert!(made.status.success(), "desk-key: {made:?}");
96 let out = String::from_utf8_lossy(&made.stdout);
97 let desk: Value = out
98 .lines()
99 .rev()
100 .find_map(|l| serde_json::from_str(l).ok())
101 .unwrap_or_else(|| panic!("desk-key printed no JSON: {out}"));
102 let key_text = std::fs::read_to_string(root.join("compose/approval-desk.key")).unwrap();
103 assert!(!out.contains(key_text.trim()), "desk-key printed the key");
104 let desk_key_id = desk["desk_key_id"]
105 .as_str()
106 .expect("desk_key_id")
107 .to_string();
108 let t0 = Instant::now();
109 let child = Command::new(&bin)
110 .arg("daemon")
111 .env_remove("AIEN_GPU_BACKEND")
112 .env_remove("AIEN_REQUIRE_BLACKWELL")
113 .env("AIEN_MODEL_PATH", model.join("model.safetensors"))
114 .env("AIEN_TOKENIZER_PATH", model.join("tokenizer.json"))
115 .env("AIEN_REQUIRE_CHECKPOINT", "1")
116 .env("AIEN_COMPOSE_DIR", root.join("compose"))
117 .env("AIEN_RUNTIME_STATE_DIR", root.join("state"))
118 .env("AIEN_PROVENANCE_DIR", root.join("prov"))
119 .env("AIEN_RUNTIME_SOCK", &sock)
120 .stdin(Stdio::null())
121 .stdout(std::fs::File::create(&log).unwrap())
122 .stderr(std::fs::File::create(root.join("daemon.err")).unwrap())
123 .spawn()
124 .expect("spawn aien-cli daemon");
125 let mut d = Daemon {
126 child,
127 root: root.clone(),
128 sock: sock.clone(),
129 desk_key_id,
130 log: log.clone(),
131 started_ms: 0,
132 _keep: keep,
133 };
134 // Started = socket present and the declared warm-up line printed (run-campaign.sh rule).
135 loop {
136 let text = std::fs::read_to_string(&log).unwrap_or_default();
137 if sock.exists() && text.contains("Warm-up:") {
138 break;
139 }
140 if let Ok(Some(st)) = d.child.try_wait() {
141 panic!(
142 "DAEMON_NOT_STARTED {row}: exited {st}; log {}",
143 log.display()
144 );
145 }
146 if t0.elapsed() > Duration::from_secs(600) {
147 panic!(
148 "DAEMON_NOT_STARTED {row}: no warm-up within 600 s; log {}",
149 log.display()
150 );
151 }
152 std::thread::sleep(Duration::from_millis(500));
153 }
154 std::thread::sleep(Duration::from_millis(500));
155 d.started_ms = t0.elapsed().as_millis();
156 std::fs::create_dir_all(d.ws().join("notes")).unwrap();
157 Some(d)
158}
159
160/// `records_total`, read twice: the read appends nothing.
161fn count(c: &LedgerClient) -> u64 {
162 let a = c.records_total().expect("ComposeRecall");
163 let b = c.records_total().expect("ComposeRecall");
164 assert_eq!(a, b, "ComposeRecall must not append");
165 a
166}
167
168/// Every `effect` record in the journal, whatever grant it names.
169fn all_effects(c: &LedgerClient) -> usize {
170 // Effect phase records (intent, ack) on any grant. The daemon also writes
171 // effect-class bookkeeping (replay claims, compose-commit records), which
172 // carry no `phase` and are not effects.
173 let r = c.recall(&[], None).unwrap();
174 r["host"]
175 .as_array()
176 .unwrap()
177 .iter()
178 .filter(|h| h["note"] == "effect")
179 .filter_map(|h| serde_json::from_str::<Value>(h["text"].as_str()?).ok())
180 .filter(|t| t.get("phase").is_some())
181 .count()
182}
183
184/// Host records of kind `effect` that name authorization `grant`.
185fn effects_for(c: &LedgerClient, grant: u64) -> Vec<Value> {
186 let r = c.recall(&[], None).unwrap();
187 r["host"]
188 .as_array()
189 .unwrap()
190 .iter()
191 .filter(|h| h["note"] == "effect")
192 .filter_map(|h| serde_json::from_str::<Value>(h["text"].as_str()?).ok().map(|t| (h, t)))
193 .filter(|(_, t)| t["authorization"].as_u64() == Some(grant))
194 .map(|(h, t)| json!({"id": h["id"], "digest": h["digest"], "verified": h["verified"], "text": t}))
195 .collect()
196}
197
198/// id, digest, verified and text of the named records.
199fn records(c: &LedgerClient, ids: &[u64]) -> Vec<Value> {
200 let r = c.recall(ids, None).unwrap();
201 assert!(r["missing"].as_array().unwrap().is_empty(), "{r}");
202 r["cited"]
203 .as_array()
204 .unwrap()
205 .iter()
206 .map(|v| json!({"id": v["id"], "digest": v["digest"], "verified": v["verified"], "note": v["note"],
207 "text": v["text"].as_str().and_then(|t| serde_json::from_str::<Value>(t).ok())}))
208 .collect()
209}
210
211fn save(d: &Daemon, row: &str, mut v: Value) {
212 v["row"] = json!(row);
213 v["boundary"] = json!(LEDGER_BOUNDARY);
214 v["daemon"] = interplane_adapter_aien::fix_the_test::receipt_daemon(
215 &d.root,
216 &d.log,
217 &d.root.join("compose"),
218 d.started_ms,
219 std::env::var("AIEN_BIN").ok().as_deref(),
220 );
221 std::fs::write(
222 d.root.join("receipt.json"),
223 serde_json::to_vec_pretty(&v).unwrap(),
224 )
225 .unwrap();
226 println!("{row}: {v}");
227}
228
229fn input(id: &str, kind: &str, trust: &str, body: &str) -> InputRecord {
230 serde_json::from_value(json!({
231 "input_id": id, "content_kind": kind, "trust": trust,
232 "source": {"kind": "operator", "id": "drake"}, "origin": "operator:turn-0",
233 "content_digest": format!("sha256:{}", hex(body.as_bytes())), "trace_id": TRACE,
234 "parent_id": null, "derived_from": []
235 }))
236 .unwrap()
237}
238
239fn call(id: &str, name: &str, args: Value) -> Value {
240 json!({"id": id, "type": "function", "function": {"name": name, "arguments": args.to_string()}})
241}
242
243fn turn(calls: Vec<Value>) -> Value {
244 json!({"role": "assistant", "content": null, "tool_calls": calls})
245}
246
247/// Adapter + ledger authority over the daemon's workspace.
248/// The adapter's clock is pinned to the synthetic epoch these rows use (`now` 10, `expires_at`
249/// 1000), as in `compose_ledger.rs` (sovereign-core #260 checks expiry before the handoff).
250fn ledger(d: &Daemon) -> ComposeLedgerAuthority {
251 let mut a = AienAuthority::new(d.ws()).unwrap();
252 a.set_clock(std::sync::Arc::new(|| 10));
253 let shared = AienShared::new(a);
254 ComposeLedgerAuthority::new(shared, d.ws(), &d.sock, d.desk()).unwrap()
255}
256
257/// `(replay_claim, grant_id)` of a receipt that reached the grant.
258fn claim_grant(rc: &Value) -> (u64, u64) {
259 (
260 rc["handoff"]["replay_claim"]
261 .as_u64()
262 .expect("replay_claim"),
263 rc["grant_id"].as_u64().expect("grant_id"),
264 )
265}
266
267/// The approved `{content, path}` digest (INTERPLANE form) and the compose form.
268fn approved_sha(path: &str, content: &str) -> String {
269 hex(json!({"content": content, "path": path})
270 .to_string()
271 .as_bytes())
272}
273fn compose_sha(path: &str, content: &str) -> String {
274 hex(format!("filename: {path}\n{content}").as_bytes())
275}
276
277/// A handoff for `ComposeApprovedProposal`, MAC'd with `key` (`None`: no MAC).
278fn handoff(key: Option<&DeskKey>, b: &ApprovalBinding, content: &str) -> Value {
279 json!({"request_id": b.request_id, "trace_id": b.trace_id, "approval_id": b.approval_id,
280 "approver": b.approver, "path": b.path, "content": content,
281 "approved_proposal_sha256": b.approved_proposal_sha256, "content_sha256": b.content_sha256,
282 "approval_mac": key.map(|k| k.mac(b)).unwrap_or_default(), "requirements": BOUND_REQUIREMENTS,
283 "requirements_mac": key.map(|k| k.requirements_mac(b, BOUND_REQUIREMENTS)).unwrap_or_default()})
284}
285
286fn binding(
287 d: &Daemon,
288 rid: &str,
289 aid: &str,
290 approver: &str,
291 path: &str,
292 content: &str,
293) -> ApprovalBinding {
294 ApprovalBinding {
295 trace_id: TRACE.into(),
296 request_id: rid.into(),
297 approval_id: aid.into(),
298 approver: approver.into(),
299 path: path.into(),
300 content_sha256: hex(content.as_bytes()),
301 approved_proposal_sha256: approved_sha(path, content),
302 desk_key_id: d.desk_key_id.clone(),
303 workspace: d.ws().to_str().unwrap().into(),
304 }
305}
306
307fn pipe<'a>(rt: &'a mut ComposeLedgerAuthority, l: &ComposeLedgerAuthority) -> Pipeline<'a> {
308 let table = l.shared().with(|a| a.mapping_table(true));
309 let mut p = Pipeline::new(
310 DialectRegistry::with_defaults(),
311 table,
312 rt,
313 Limits::default(),
314 RequestLedger::new(),
315 );
316 p.register_input(input(
317 "in-user",
318 "user_request",
319 "user_supplied",
320 "write the summary",
321 ))
322 .unwrap();
323 p
324}
325
326/// Propose `write_file path content` as request `id`; it must stop at requires_approval.
327fn propose(p: &mut Pipeline<'_>, n: u64, id: &str, path: &str, content: &str) {
328 let out = p.run_turn(
329 "openai",
330 "scripted",
331 &turn(vec![call(
332 id,
333 "write_file",
334 json!({"path": path, "content": content}),
335 )]),
336 TRACE,
337 n,
338 );
339 assert_eq!(
340 out.results[0].status,
341 ResultStatus::RequiresApproval,
342 "{:?}",
343 out.results[0]
344 );
345}
346
347/// Host approves request `id` (one AIEN grant) as `drake` and continues it.
348fn approve(
349 p: &mut Pipeline<'_>,
350 l: &ComposeLedgerAuthority,
351 id: &str,
352) -> (ToolResult, aien_mcp::ApprovalGrant) {
353 let pa = p.pending_approval(TRACE, id).expect("pending");
354 let g = l
355 .shared()
356 .with(|a| a.issue_approval(&pa.capability_request, 1_000))
357 .unwrap();
358 let (r, _) = l
359 .continue_approval(p, TRACE, id, &g, 10, NOW, Some("drake"))
360 .expect("continued");
361 (r, g)
362}
363
364fn lock() -> std::sync::MutexGuard<'static, ()> {
365 SERIAL.lock().unwrap_or_else(|e| e.into_inner())
366}
367
368/// The old route: a caller notes its own `authorization` grant (workspace, path, confined
369/// target, compose-form digest) for exactly the write the host will approve. Since
370/// sovereign-core #261 (#296) the daemon refuses every caller-written `authorization` note;
371/// returns the refusal text.
372fn client_minted(c: &LedgerClient, ws: &str, path: &str, content: &str) -> String {
373 let target = Path::new(ws).join(path).to_str().unwrap().to_string();
374 let text = json!({"proposal_sha256": compose_sha(path, content), "path": path,
375 "content_sha256": hex(content.as_bytes()), "approver": "attacker", "workspace": ws,
376 "target": target, "prior_sha256": null});
377 match c.note("authorization", &text.to_string(), &[]) {
378 Ok(n) => panic!("ATTACK SUCCEEDED: the daemon accepted a client-minted grant note: {n}"),
379 Err(e) => e,
380 }
381}
382
383/// Host approves `id`; the outcome as (Ok?, error text). A pipeline refusal counts as not Ok.
384fn approve_outcome(p: &mut Pipeline<'_>, l: &ComposeLedgerAuthority, id: &str) -> (bool, String) {
385 let pa = p.pending_approval(TRACE, id).expect("pending");
386 let g = l
387 .shared()
388 .with(|a| a.issue_approval(&pa.capability_request, 1_000))
389 .unwrap();
390 match l.continue_approval(p, TRACE, id, &g, 10, NOW, Some("drake")) {
391 Ok((r, _)) => (
392 r.status == ResultStatus::Ok,
393 r.error.map(|e| e.message).unwrap_or_default(),
394 ),
395 Err(e) => (false, format!("pipeline refused: {e:?}")),
396 }
397}
398
399/// Item (1): a client-minted grant note for exactly the approved write is refused by the daemon
400/// (sovereign-core #261), and the daemon refuses the handoff (the request id was already
401/// claimed). Nothing is written, no intent opens on the client grant, the adapter does not
402/// fall back to it.
403#[test]
404#[ignore = "NOT_RUN unless AIEN_BIN names an aien-cli binary: run with --ignored"]
405fn x1_client_minted_grant_unused_when_the_handoff_refuses() {
406 let _g = lock();
407 let Some(d) = daemon("x1") else { return };
408 let c = d.client();
409 let ws = d.ws().to_str().unwrap().to_string();
410 let path = "minted.txt";
411 let before_note = count(&c);
412 let minted = client_minted(&c, &ws, path, EXPECTED);
413 assert!(
414 minted.contains("sovereign-core #261"),
415 "client-minted note refused for another reason: {minted}"
416 );
417 assert_eq!(
418 count(&c),
419 before_note,
420 "a refused client-minted note appended records"
421 );
422 // Request id m1 is claimed first by a real, desk-signed handoff for other content.
423 let k = DeskKey::load(&d.desk()).unwrap();
424 let b = binding(
425 &d,
426 "m1",
427 "aien-approval:other",
428 "drake",
429 "other.txt",
430 "other\n",
431 );
432 c.approved(&handoff(Some(&k), &b, "other\n"), &ws)
433 .expect("first handoff commits");
434 drop(k);
435 let before = count(&c);
436 let l = ledger(&d);
437 let mut rt = l.clone();
438 let mut p = pipe(&mut rt, &l);
439 propose(&mut p, 0, "m1", path, EXPECTED);
440 let (ok, err) = approve_outcome(&mut p, &l, "m1");
441 assert!(
442 !ok,
443 "ATTACK SUCCEEDED: write reported Ok after a refused handoff"
444 );
445 assert!(
446 !d.ws().join(path).exists(),
447 "ATTACK SUCCEEDED: file written"
448 );
449 assert_eq!(
450 all_effects(&c),
451 0,
452 "ATTACK SUCCEEDED: an effect record exists"
453 );
454 assert_eq!(l.grants_minted(), 0);
455 assert_eq!(count(&c), before, "a refused handoff appended records");
456 let rc = l.receipts().last().cloned().unwrap();
457 assert_eq!(rc["state"], "REFUSED");
458 println!("x1: PASS refused: {err}");
459}
460
461/// No fallback: the daemon is gone when the host approves. Nothing is written anywhere in the
462/// workspace (the in-process provider never runs the write).
463#[test]
464#[ignore = "NOT_RUN unless AIEN_BIN names an aien-cli binary: run with --ignored"]
465fn x2_no_fallback_write_when_the_daemon_is_gone() {
466 let _g = lock();
467 let Some(mut d) = daemon("x2") else { return };
468 let l = ledger(&d);
469 let mut rt = l.clone();
470 let mut p = pipe(&mut rt, &l);
471 propose(&mut p, 0, "g1", "gone.txt", EXPECTED);
472 d.child.kill().unwrap();
473 d.child.wait().unwrap();
474 let (ok, err) = approve_outcome(&mut p, &l, "g1");
475 assert!(!ok, "ATTACK SUCCEEDED: write reported Ok with no daemon");
476 assert!(
477 !d.ws().join("gone.txt").exists(),
478 "ATTACK SUCCEEDED: fallback write"
479 );
480 let left: Vec<_> = std::fs::read_dir(d.ws())
481 .unwrap()
482 .filter_map(|e| e.ok())
483 .map(|e| e.file_name().to_string_lossy().into_owned())
484 .filter(|n| n != "notes")
485 .collect();
486 assert!(left.is_empty(), "workspace changed: {left:?}");
487 println!("x2: PASS refused: {err}");
488}
489
490/// The effect names the daemon's own grant and the compose-form digest; a client-minted grant
491/// note for the same write is refused first (sovereign-core #261), so no other grant exists.
492#[test]
493#[ignore = "NOT_RUN unless AIEN_BIN names an aien-cli binary: run with --ignored"]
494fn x3_effect_uses_the_daemon_grant_not_a_client_one() {
495 let _g = lock();
496 let Some(d) = daemon("x3") else { return };
497 let c = d.client();
498 let ws = d.ws().to_str().unwrap().to_string();
499 let minted = client_minted(&c, &ws, "summary.txt", EXPECTED);
500 assert!(minted.contains("sovereign-core #261"), "{minted}");
501 let l = ledger(&d);
502 let mut rt = l.clone();
503 let mut p = pipe(&mut rt, &l);
504 propose(&mut p, 0, "u1", "summary.txt", EXPECTED);
505 let (ok, err) = approve_outcome(&mut p, &l, "u1");
506 assert!(ok, "honest write failed: {err}");
507 let rc = l.receipts().last().cloned().unwrap();
508 let grant = rc["grant_id"].as_u64().unwrap();
509 assert_eq!(rc["handoff"]["approved_grant"], json!(grant));
510 let g = &records(&c, &[grant])[0];
511 assert_eq!(g["text"]["approved_grant"], 1, "the daemon wrote the grant");
512 let csha = compose_sha("summary.txt", EXPECTED);
513 assert_eq!(rc["proposal_sha256"], json!(csha));
514 assert_eq!(rc["handoff"]["state"], "COMMITTED");
515 assert_eq!(
516 effects_for(&c, grant).len(),
517 2,
518 "intent + ack on the daemon grant"
519 );
520 assert_eq!(
521 all_effects(&c),
522 2,
523 "an effect names a grant other than the daemon's"
524 );
525 assert_eq!(rc["state"], "DONE");
526 println!("x3: PASS grant #{grant} (client-minted note refused: {minted})");
527}
528
529/// The write's temporary file has a predictable name in the target directory. Planted there as a
530/// symlink to a file outside the workspace, the write must not land outside.
531#[test]
532#[ignore = "NOT_RUN unless AIEN_BIN names an aien-cli binary: run with --ignored"]
533fn x4_planted_temp_symlink_does_not_redirect_the_write() {
534 let _g = lock();
535 let Some(d) = daemon("x4") else { return };
536 let outside = d.root.join("outside.txt");
537 std::fs::write(&outside, "ORIGINAL\n").unwrap();
538 let tmp = d.ws().join(format!(
539 ".summary.txt.interplane-{}.tmp",
540 std::process::id()
541 ));
542 std::os::unix::fs::symlink(&outside, &tmp).unwrap();
543 let l = ledger(&d);
544 let mut rt = l.clone();
545 let mut p = pipe(&mut rt, &l);
546 propose(&mut p, 0, "s1", "summary.txt", EXPECTED);
547 let (ok, err) = approve_outcome(&mut p, &l, "s1");
548 let rc = l.receipts().last().cloned().unwrap();
549 let now = std::fs::read_to_string(&outside).unwrap();
550 println!(
551 "x4: ok={ok} state={} outside={now:?} err={err}",
552 rc["state"]
553 );
554 assert_eq!(
555 now, "ORIGINAL\n",
556 "ATTACK SUCCEEDED: the approved bytes landed outside the workspace"
557 );
558}