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 / src / compose_ledger.rs

1124 lines · 47403 bytes Raw Blame History
1//! `write_file` through AIEN's production compose path and durable effect ledger (`aien-cli
2//! daemon`, sovereign-core #249).
3//!
4//! [`ComposeLedgerAuthority`] wraps [`AienShared`]: the approval desk, `decide` and every read are
5//! the tested in-process adapter, unchanged. Only an authorized `write_file` takes a different
6//! route, after the host approved it through the host-only continuation:
7//!
8//! 1. the authenticated handoff: an `ApprovedProposal` (trace id, request id, approval id,
9//! approver, path, content, approved proposal digest, content digest) with `approval_mac`, the
10//! HMAC-SHA256 under the approval desk key ([`DeskKey`]) over the canonical binding, sent as
11//! `ComposeApprovedProposal`. The daemon re-checks the MAC, claims the request id, approval id
12//! and approval key durably (replay refused across restarts), then runs the approved text
13//! through compose: J-Space branch, AEGIS verify callback, World commit, Cortex records;
14//! 2. the returned `ApprovedComposeReport` is checked field by field (ids, both hash identities);
15//! 3. the grant is the daemon's own reserved `approved_grant` record (returned as
16//! `approved_grant`): keyed on `compose_proposal_sha256` (never the pre-compose approved
17//! digest), confined to the workspace, linked to the Cortex promotion, evidence and replay claim
18//! records; it is read back and checked. This authority writes no grant itself, so an approved
19//! write has exactly one route;
20//! 4. `ComposeEffectIntent` (stop, revoke, spent, stale checked by the daemon), the write (tmp +
21//! rename inside the workspace), `ComposeEffectAck` (the daemon reads the disk).
22//!
23//! The desk key never reaches the model: it is read from a host-configured path outside the
24//! workspace ([`ComposeLedgerAuthority::new`] refuses a key inside it) and only its id is recorded.
25//! The socket client speaks the daemon's JSON line protocol directly (`aien-runtime` is not a
26//! dependency: its build scripts need the omega libraries). Boundary: [`LEDGER_BOUNDARY`].
27use std::cell::RefCell;
28use std::collections::HashMap;
29use std::fs;
30use std::io::{BufRead, BufReader, Read, Write};
31use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
32use std::os::unix::net::UnixStream;
33use std::path::{Component, Path, PathBuf};
34use std::rc::Rc;
35use std::sync::atomic::{AtomicU64, Ordering};
36use std::time::{Duration, SystemTime, UNIX_EPOCH};
37
38use aien_mcp::ApprovalGrant;
39use interplane_core::*;
40use interplane_crossveil::{CallContext, ObservedRecord, Pipeline, Refusal, RuntimeAuthority};
41use serde_json::{json, Map, Value};
42use sha2::{Digest, Sha256};
43
44use crate::{AienShared, RUNTIME_ID};
45
46/// The label every receipt of this authority carries.
47pub const LEDGER_BOUNDARY: &str = "boundary = authenticated daemon handoff (ComposeApprovedProposal: desk MAC, durable replay claim) -> compose verify + AEGIS -> J-Space branch -> World commit -> Cortex promotion/evidence -> daemon-written grant on compose_proposal_sha256 -> effect intent -> write -> ack; the production effect path, not WALDO provenance";
48/// Version tag inside every approval binding (sovereign-core `approved_auth`).
49pub const APPROVAL_BINDING_VERSION: &str = "aien.approval.v2";
50/// Domain tag of the requirements MAC (sovereign-core #295, `approved_auth::requirements_bytes`;
51/// tag v1 = no bound requirement depends on the file the bytes replace).
52pub const REQUIREMENTS_TAG_V1: &[u8] = b"aien.requirements.v1\0";
53/// The requirement goal this authority binds: empty, and signed. The host approves the exact
54/// bytes of a `write_file`, so there is no natural-language goal whose measurable requirements the
55/// daemon could check; an empty goal is the explicit "none" (a missing one is refused, #289).
56/// Tag v2 (a goal whose requirement depends on the replaced file, signed with a base) is
57/// deliberately not implemented: an empty goal never needs a base.
58pub const BOUND_REQUIREMENTS: &str = "";
59/// Approver recorded in the grant when the host names none.
60pub const DEFAULT_APPROVER: &str = "interplane-host";
61
62/// sha256 hex (the daemon's digest form: lowercase, no prefix).
63pub fn sha256_hex(b: &[u8]) -> String {
64 format!("{:x}", Sha256::digest(b))
65}
66
67/// HMAC-SHA256 (RFC 2104) over sha2.
68pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
69 let mut k = [0u8; 64];
70 if key.len() > 64 {
71 k[..32].copy_from_slice(&Sha256::digest(key));
72 } else {
73 k[..key.len()].copy_from_slice(key);
74 }
75 let (mut ipad, mut opad) = ([0x36u8; 64], [0x5cu8; 64]);
76 for i in 0..64 {
77 ipad[i] ^= k[i];
78 opad[i] ^= k[i];
79 }
80 let inner = Sha256::new()
81 .chain_update(ipad)
82 .chain_update(msg)
83 .finalize();
84 Sha256::new()
85 .chain_update(opad)
86 .chain_update(inner)
87 .finalize()
88 .into()
89}
90
91/// The fields one approval covers, in the canonical binding the daemon re-computes (compact
92/// JSON, keys sorted, plus `"v": APPROVAL_BINDING_VERSION`).
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct ApprovalBinding {
95 pub trace_id: String,
96 pub request_id: String,
97 pub approval_id: String,
98 pub approver: String,
99 pub path: String,
100 pub content_sha256: String,
101 pub approved_proposal_sha256: String,
102 pub desk_key_id: String,
103 /// The canonical absolute workspace the effect may land in (the daemon binds the
104 /// canonicalised workspace of the command, so another workspace fails the MAC).
105 pub workspace: String,
106}
107
108impl ApprovalBinding {
109 pub fn bytes(&self) -> Vec<u8> {
110 let mut m = Map::new();
111 for (k, v) in [
112 ("approval_id", &self.approval_id),
113 ("approved_proposal_sha256", &self.approved_proposal_sha256),
114 ("approver", &self.approver),
115 ("content_sha256", &self.content_sha256),
116 ("desk_key_id", &self.desk_key_id),
117 ("path", &self.path),
118 ("request_id", &self.request_id),
119 ("trace_id", &self.trace_id),
120 ("workspace", &self.workspace),
121 ] {
122 m.insert(k.into(), json!(v));
123 }
124 m.insert("v".into(), json!(APPROVAL_BINDING_VERSION));
125 Value::Object(m).to_string().into_bytes()
126 }
127}
128
129/// The approval desk key (`<compose dir>/approval-desk.key`, made by `aien compose desk-key
130/// --create 1`). Loaded with the daemon's rules: a regular file (no symlink, `O_NOFOLLOW`) owned
131/// by this user, no group or other bits, 64 lowercase hex digits. `Debug` shows only the id.
132pub struct DeskKey {
133 key: [u8; 32],
134 id: String,
135}
136
137impl std::fmt::Debug for DeskKey {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 write!(f, "DeskKey {{ id: {} }}", self.id)
140 }
141}
142
143impl DeskKey {
144 pub fn load(path: &Path) -> Result<Self, String> {
145 let bad = |w: String| format!("approval desk key {}: {w}", path.display());
146 let l = fs::symlink_metadata(path).map_err(|e| bad(e.to_string()))?;
147 if l.file_type().is_symlink() {
148 return Err(bad("is a symlink".into()));
149 }
150 let f = fs::OpenOptions::new()
151 .read(true)
152 .custom_flags(libc_o_nofollow())
153 .open(path)
154 .map_err(|e| bad(e.to_string()))?;
155 let m = f.metadata().map_err(|e| bad(e.to_string()))?;
156 let me = fs::metadata("/proc/self")
157 .map_err(|e| bad(e.to_string()))?
158 .uid();
159 if !m.file_type().is_file() || m.uid() != me || m.mode() & 0o077 != 0 {
160 return Err(bad(
161 "must be a regular file owned by this user with mode 0600".into(),
162 ));
163 }
164 let mut s = String::new();
165 f.take(256)
166 .read_to_string(&mut s)
167 .map_err(|e| bad(e.to_string()))?;
168 let h = s.trim_end_matches('\n');
169 if h.len() != 64
170 || !h
171 .bytes()
172 .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
173 {
174 return Err(bad("not 64 lowercase hex digits".into()));
175 }
176 let mut key = [0u8; 32];
177 for (i, o) in key.iter_mut().enumerate() {
178 *o = u8::from_str_radix(&h[2 * i..2 * i + 2], 16).map_err(|e| bad(e.to_string()))?;
179 }
180 let id = sha256_hex(&key)[..16].to_string();
181 Ok(Self { key, id })
182 }
183
184 /// First 16 hex digits of sha256 of the key.
185 pub fn id(&self) -> &str {
186 &self.id
187 }
188
189 /// `approval_mac` for `b` (whose `desk_key_id` must be [`Self::id`]).
190 pub fn mac(&self, b: &ApprovalBinding) -> String {
191 hmac_sha256(&self.key, &b.bytes())
192 .iter()
193 .map(|x| format!("{x:02x}"))
194 .collect()
195 }
196
197 /// `requirements_mac` for `b` and the bound goal `goal` (tag v1, no base): HMAC-SHA256 over
198 /// the tag, the binding bytes, a zero byte, a one byte (goal present), the goal bytes.
199 pub fn requirements_mac(&self, b: &ApprovalBinding, goal: &str) -> String {
200 let mut m = REQUIREMENTS_TAG_V1.to_vec();
201 m.extend(b.bytes());
202 m.push(0);
203 m.push(1);
204 m.extend(goal.as_bytes());
205 hmac_sha256(&self.key, &m)
206 .iter()
207 .map(|x| format!("{x:02x}"))
208 .collect()
209 }
210}
211
212impl Drop for DeskKey {
213 fn drop(&mut self) {
214 for b in self.key.iter_mut() {
215 // SAFETY: a valid, aligned, exclusively borrowed byte.
216 unsafe { std::ptr::write_volatile(b, 0) };
217 }
218 }
219}
220
221/// `O_NOFOLLOW` on Linux (aarch64 and x86_64 differ; the adapter is Linux-only like the daemon).
222fn libc_o_nofollow() -> i32 {
223 if cfg!(target_arch = "aarch64") {
224 0o100000
225 } else {
226 0o400000
227 }
228}
229
230/// sha256 of a file, `None` when absent; an error for anything that is not a regular file
231/// (the daemon's `effects::file_sha256` rule).
232pub fn file_sha256(path: &Path) -> Result<Option<String>, String> {
233 match fs::symlink_metadata(path) {
234 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
235 Err(e) => Err(format!("stat {}: {e}", path.display())),
236 Ok(m) if !m.file_type().is_file() => {
237 Err(format!("{} is not a regular file", path.display()))
238 }
239 Ok(_) => fs::read(path)
240 .map(|b| Some(sha256_hex(&b)))
241 .map_err(|e| format!("read {}: {e}", path.display())),
242 }
243}
244
245/// This process as the effect executor: pid and start ticks (/proc/self/stat field 22).
246pub fn self_executor() -> (u32, u64) {
247 let stat = fs::read_to_string("/proc/self/stat").unwrap_or_default();
248 let start = stat
249 .rfind(')')
250 .and_then(|i| stat[i + 1..].split_whitespace().nth(19))
251 .and_then(|s| s.parse().ok())
252 .unwrap_or(0);
253 (std::process::id(), start)
254}
255
256static OPERATION: AtomicU64 = AtomicU64::new(0);
257
258/// What the daemon returned for one `StreamTurn`: its own text and the id of its own generation
259/// record (sovereign-core `DAEMON_GENERATION_RECORD.md`).
260#[derive(Clone, Debug)]
261pub struct ModelTurn {
262 pub text: String,
263 pub generation_record: u64,
264 pub total_tokens: u64,
265}
266
267/// Newline-JSON client for the daemon's control socket (`aien-runtime` client.rs framing).
268#[derive(Clone, Debug)]
269pub struct LedgerClient {
270 socket: PathBuf,
271}
272
273impl LedgerClient {
274 pub fn new(socket: impl Into<PathBuf>) -> Self {
275 Self {
276 socket: socket.into(),
277 }
278 }
279
280 /// One command in, one response out. `Ok` is the response's single variant body keyed by
281 /// name (e.g. `{"ComposeNoted": {...}}`); a daemon `Error` is `Err` with its text.
282 pub fn send(&self, command: Value) -> Result<Value, String> {
283 // Same-user check: the socket file must be owned by this process's user.
284 let me = fs::metadata("/proc/self").map_err(|e| e.to_string())?.uid();
285 let owner = fs::metadata(&self.socket)
286 .map_err(|e| format!("socket {}: {e}", self.socket.display()))?
287 .uid();
288 if owner != me {
289 return Err(format!(
290 "refusing socket {}: owned by uid {owner}",
291 self.socket.display()
292 ));
293 }
294 let mut s = UnixStream::connect(&self.socket)
295 .map_err(|e| format!("connect {}: {e}", self.socket.display()))?;
296 s.set_read_timeout(Some(Duration::from_secs(120)))
297 .map_err(|e| e.to_string())?;
298 let now = SystemTime::now()
299 .duration_since(UNIX_EPOCH)
300 .unwrap_or_default();
301 let op = now.as_nanos() as u64 + OPERATION.fetch_add(1, Ordering::SeqCst);
302 let env = json!({"protocol_version": 1, "request_id": now.as_millis() as u64,
303 "operation_id": op, "operator_session": 1, "command": command});
304 s.write_all(format!("{env}\n").as_bytes())
305 .map_err(|e| format!("send: {e}"))?;
306 let mut line = String::new();
307 BufReader::new(&s)
308 .read_line(&mut line)
309 .map_err(|e| format!("receive: {e}"))?;
310 let v: Value =
311 serde_json::from_str(line.trim()).map_err(|e| format!("response: {e}: {line}"))?;
312 match v.get("Error") {
313 Some(e) => Err(e.as_str().map_or_else(|| e.to_string(), str::to_string)),
314 None => Ok(v),
315 }
316 }
317
318 /// One `StreamTurn` (the generation path `aien-cli chat` uses) on the daemon's loaded model.
319 /// The daemon answers with a stream of lines and ends with `TurnFinished`; the request is sent
320 /// as `messages` exactly as given and the returned [`ModelTurn`] carries the daemon's own text
321 /// and the id of its generation record (`TurnFinished.generation_record`). `Err` when the
322 /// stream ends without `TurnFinished`, carries an `Error`, or names no generation record: no
323 /// record means no claim, so this never invents one.
324 pub fn stream_turn(
325 &self,
326 messages: &Value,
327 max_tokens: u64,
328 temperature: f64,
329 ) -> Result<ModelTurn, String> {
330 let me = fs::metadata("/proc/self").map_err(|e| e.to_string())?.uid();
331 let owner = fs::metadata(&self.socket)
332 .map_err(|e| format!("socket {}: {e}", self.socket.display()))?
333 .uid();
334 if owner != me {
335 return Err(format!(
336 "refusing socket {}: owned by uid {owner}",
337 self.socket.display()
338 ));
339 }
340 let mut s = UnixStream::connect(&self.socket)
341 .map_err(|e| format!("connect {}: {e}", self.socket.display()))?;
342 s.set_read_timeout(Some(Duration::from_secs(1800)))
343 .map_err(|e| e.to_string())?;
344 let now = SystemTime::now()
345 .duration_since(UNIX_EPOCH)
346 .unwrap_or_default();
347 let op = now.as_nanos() as u64 + OPERATION.fetch_add(1, Ordering::SeqCst);
348 let env = json!({"protocol_version": 1, "request_id": now.as_millis() as u64,
349 "operation_id": op, "operator_session": 1,
350 "command": {"StreamTurn": {"messages": messages, "max_tokens": max_tokens,
351 "temperature": temperature}}});
352 s.write_all(format!("{env}\n").as_bytes())
353 .map_err(|e| format!("send: {e}"))?;
354 for line in BufReader::new(&s).lines() {
355 let line = line.map_err(|e| format!("receive: {e}"))?;
356 let v: Value =
357 serde_json::from_str(line.trim()).map_err(|e| format!("response: {e}: {line}"))?;
358 if let Some(e) = v.get("Error") {
359 return Err(e.as_str().map_or_else(|| e.to_string(), str::to_string));
360 }
361 if let Some(f) = v.get("TurnFinished") {
362 let text = f["text"].as_str().ok_or("TurnFinished without text")?;
363 let generation_record = f["generation_record"]
364 .as_u64()
365 .ok_or("the daemon returned no generation_record: no record means no claim")?;
366 return Ok(ModelTurn {
367 text: text.to_string(),
368 generation_record,
369 total_tokens: f["total_tokens"].as_u64().unwrap_or(0),
370 });
371 }
372 }
373 Err("StreamTurn ended without TurnFinished".into())
374 }
375
376 fn body(&self, command: Value, variant: &str) -> Result<Value, String> {
377 let v = self.send(command)?;
378 v.get(variant)
379 .cloned()
380 .ok_or_else(|| format!("expected {variant}, got {v}"))
381 }
382
383 /// `ComposeNote`; returns the `ComposeNoted` report (`id`, `digest`, ...).
384 pub fn note(&self, kind: &str, text: &str, links: &[u64]) -> Result<Value, String> {
385 self.body(
386 json!({"ComposeNote": {"kind": kind, "text": text, "links": links}}),
387 "ComposeNoted",
388 )
389 }
390
391 /// `ComposeEffectIntent`; returns the `ComposeNoted` report of the intent record.
392 #[allow(clippy::too_many_arguments)]
393 pub fn intent(
394 &self,
395 authorization: u64,
396 proposal_sha256: &str,
397 path: &str,
398 target: &str,
399 content_sha256: &str,
400 executor: (u32, u64),
401 ) -> Result<Value, String> {
402 self.body(
403 json!({"ComposeEffectIntent": {"authorization": authorization,
404 "proposal_sha256": proposal_sha256, "path": path, "target": target,
405 "content_sha256": content_sha256, "executor_pid": executor.0,
406 "executor_start": executor.1}}),
407 "ComposeNoted",
408 )
409 }
410
411 /// `ComposeEffectAck`; returns the `ComposeNoted` report of the ack record.
412 pub fn ack(&self, intent: u64, reported: &Value) -> Result<Value, String> {
413 self.body(
414 json!({"ComposeEffectAck": {"intent": intent, "reported": reported}}),
415 "ComposeNoted",
416 )
417 }
418
419 /// `ComposeApprovedProposal` (sovereign-core #249). `Ok` = the `ComposeApprovedResult` report;
420 /// a `ComposeApprovedRefused` is `Err` with `"<refused_by> <name>: <detail>"`.
421 pub fn approved(&self, proposal: &Value, workspace: &str) -> Result<Value, String> {
422 let v = self.send(
423 json!({"ComposeApprovedProposal": {"proposal": proposal, "workspace": workspace}}),
424 )?;
425 if let Some(r) = v.get("ComposeApprovedRefused") {
426 return Err(format!(
427 "{} {}: {}",
428 r["refused_by"].as_str().unwrap_or("REFUSED"),
429 r["name"].as_str().unwrap_or("?"),
430 r["detail"].as_str().unwrap_or("")
431 ));
432 }
433 v.get("ComposeApprovedResult")
434 .cloned()
435 .ok_or_else(|| format!("expected ComposeApprovedResult, got {v}"))
436 }
437
438 /// `ComposeRecall`; returns the `ComposeRecalled` report.
439 pub fn recall(&self, ids: &[u64], prefix: Option<u64>) -> Result<Value, String> {
440 self.body(
441 json!({"ComposeRecall": {"ids": ids, "prefix": prefix}}),
442 "ComposeRecalled",
443 )
444 }
445
446 /// `ComposeControl` (`stop`, `resume`, `revoke`); returns the `ComposeControlled` report.
447 pub fn control(
448 &self,
449 action: &str,
450 approver: &str,
451 authorization: Option<u64>,
452 ) -> Result<Value, String> {
453 self.body(
454 json!({"ComposeControl": {"action": action, "approver": approver, "authorization": authorization}}),
455 "ComposeControlled",
456 )
457 }
458
459 /// Number of records in the compose home's Cortex journal (`ComposeRecall.records_total`).
460 pub fn records_total(&self) -> Result<u64, String> {
461 self.recall(&[], None)?["records_total"]
462 .as_u64()
463 .ok_or_else(|| "ComposeRecalled without records_total".into())
464 }
465}
466
467type Hook = Box<dyn FnMut(&Path)>;
468
469struct LedgerState {
470 client: LedgerClient,
471 workspace: PathBuf,
472 desk_key: PathBuf,
473 approvers: HashMap<String, String>,
474 before_intent: Option<Hook>,
475 before_ack: Option<Hook>,
476 grants_minted: u32,
477 receipts: Vec<Value>,
478}
479
480/// The adapter with `write_file` routed through the daemon's durable effect ledger. Clone it to
481/// hand one copy to the `Pipeline` and keep one for the host (same pattern as [`AienShared`]).
482#[derive(Clone)]
483pub struct ComposeLedgerAuthority {
484 shared: AienShared,
485 state: Rc<RefCell<LedgerState>>,
486}
487
488impl ComposeLedgerAuthority {
489 /// `shared` must be enrolled over the same `workspace`; `socket` is `$AIEN_RUNTIME_SOCK`;
490 /// `desk_key` is the daemon's approval desk key (`aien compose desk-key`). Refused when the key
491 /// fails the file rules or sits inside the workspace (the model-facing tools read there).
492 pub fn new(
493 shared: AienShared,
494 workspace: impl AsRef<Path>,
495 socket: impl Into<PathBuf>,
496 desk_key: impl AsRef<Path>,
497 ) -> Result<Self, String> {
498 let workspace =
499 fs::canonicalize(workspace.as_ref()).map_err(|e| format!("workspace: {e}"))?;
500 let desk_key = fs::canonicalize(desk_key.as_ref().parent().unwrap_or(Path::new("/")))
501 .map_err(|e| format!("approval desk key: {e}"))?
502 .join(
503 desk_key
504 .as_ref()
505 .file_name()
506 .ok_or("approval desk key: no file name")?,
507 );
508 if desk_key.starts_with(&workspace)
509 || workspace.starts_with(desk_key.parent().unwrap_or(Path::new("/")))
510 {
511 return Err(format!(
512 "approval desk key {} and workspace {} overlap; refusing",
513 desk_key.display(),
514 workspace.display()
515 ));
516 }
517 DeskKey::load(&desk_key)?;
518 Ok(Self {
519 shared,
520 state: Rc::new(RefCell::new(LedgerState {
521 client: LedgerClient::new(socket),
522 workspace,
523 desk_key,
524 approvers: HashMap::new(),
525 before_intent: None,
526 before_ack: None,
527 grants_minted: 0,
528 receipts: vec![],
529 })),
530 })
531 }
532
533 /// The wrapped in-process adapter (approval desk, counters).
534 pub fn shared(&self) -> &AienShared {
535 &self.shared
536 }
537
538 /// A client on the same daemon socket.
539 pub fn client(&self) -> LedgerClient {
540 self.state.borrow().client.clone()
541 }
542
543 /// Daemon-written grants (reserved `approved_grant` records) this authority received for
544 /// approvals it handed off and checked; it never writes a grant itself.
545 pub fn grants_minted(&self) -> u32 {
546 self.state.borrow().grants_minted
547 }
548
549 /// Every ledger receipt this authority produced, oldest first.
550 pub fn receipts(&self) -> Vec<Value> {
551 self.state.borrow().receipts.clone()
552 }
553
554 /// Fault-injection seam for the window between the written bytes and the acknowledgement: runs
555 /// after the intent record exists and the bytes are on disk, just before `ComposeEffectAck`.
556 /// A daemon that dies here leaves an intent without an ack: the receipt must say `UNRESOLVED`.
557 pub fn set_before_ack(&self, hook: impl FnMut(&Path) + 'static) {
558 self.state.borrow_mut().before_ack = Some(Box::new(hook));
559 }
560
561 /// Fault-injection seam (the analogue of aien-cli's `fault_hold("before_intent")`): runs after
562 /// the grant is recorded and before the intent is asked for, with the absolute target.
563 pub fn set_before_intent(&self, hook: impl FnMut(&Path) + 'static) {
564 self.state.borrow_mut().before_intent = Some(Box::new(hook));
565 }
566
567 /// Host-only: [`AienShared::continue_approval`] with the host approver recorded in the grant
568 /// (`None` = [`DEFAULT_APPROVER`]).
569 #[allow(clippy::too_many_arguments)]
570 pub fn continue_approval(
571 &self,
572 pipeline: &mut Pipeline<'_>,
573 trace: &str,
574 request_id: &str,
575 grant: &ApprovalGrant,
576 now_epoch: u64,
577 now: &str,
578 approver: Option<&str>,
579 ) -> Result<(ToolResult, ObservedRecord), Refusal> {
580 let who = approver.unwrap_or(DEFAULT_APPROVER).to_string();
581 self.state
582 .borrow_mut()
583 .approvers
584 .insert(request_id.to_string(), who);
585 let out = self
586 .shared
587 .continue_approval(pipeline, trace, request_id, grant, now_epoch, now);
588 self.state.borrow_mut().approvers.remove(request_id);
589 out
590 }
591
592 /// Absolute target for a workspace-relative `path`: no `..`, parent inside the workspace.
593 fn target(&self, path: &str) -> Result<PathBuf, String> {
594 let root = self.state.borrow().workspace.clone();
595 let p = Path::new(path);
596 let outside = || format!("path is outside the workspace: {path}");
597 if p.is_absolute() || p.components().any(|c| !matches!(c, Component::Normal(_))) {
598 return Err(outside());
599 }
600 let full = root.join(p);
601 let name = full.file_name().ok_or_else(outside)?.to_owned();
602 let parent = full
603 .parent()
604 .and_then(|d| fs::canonicalize(d).ok())
605 .filter(|d| d.starts_with(&root))
606 .ok_or_else(outside)?;
607 Ok(parent.join(name))
608 }
609
610 /// handoff -> grant -> intent -> atomic write -> ack. `Err` before the intent means nothing
611 /// was written.
612 fn write_through_ledger(
613 &self,
614 req: &CapabilityRequest,
615 trace_id: &str,
616 approver: &str,
617 approval_id: &str,
618 ) -> Result<Value, String> {
619 let arg = |k: &str| {
620 req.arguments
621 .get(k)
622 .and_then(Value::as_str)
623 .ok_or(format!("missing required argument: {k}"))
624 };
625 let (path, content) = (arg("path")?, arg("content")?);
626 let target = self.target(path)?;
627 let tgt = target.to_str().ok_or("target is not UTF-8")?.to_string();
628 let ws = self
629 .state
630 .borrow()
631 .workspace
632 .to_str()
633 .ok_or("workspace is not UTF-8")?
634 .to_string();
635 // approved_proposal_sha256: the approved {content, path} object, keys sorted.
636 let mut prop = Map::new();
637 prop.insert("content".into(), json!(content));
638 prop.insert("path".into(), json!(path));
639 let approved_sha = sha256_hex(Value::Object(prop).to_string().as_bytes());
640 let content_sha256 = sha256_hex(content.as_bytes());
641 let rid = req.request_id.as_str();
642 if approval_id.is_empty() {
643 return Err("no approval id for this request".into());
644 }
645 // 1. The authenticated handoff.
646 let desk = DeskKey::load(&self.state.borrow().desk_key)?;
647 let binding = ApprovalBinding {
648 trace_id: trace_id.into(),
649 request_id: rid.into(),
650 approval_id: approval_id.into(),
651 approver: approver.into(),
652 path: path.into(),
653 content_sha256: content_sha256.clone(),
654 approved_proposal_sha256: approved_sha.clone(),
655 desk_key_id: desk.id().into(),
656 workspace: ws.clone(),
657 };
658 let proposal = json!({"request_id": rid, "trace_id": trace_id, "approval_id": approval_id,
659 "approver": approver, "path": path, "content": content,
660 "approved_proposal_sha256": approved_sha, "content_sha256": content_sha256,
661 "approval_mac": desk.mac(&binding), "requirements": BOUND_REQUIREMENTS,
662 "requirements_mac": desk.requirements_mac(&binding, BOUND_REQUIREMENTS)});
663 drop(desk);
664 let client = self.client();
665 let mut rc = json!({"boundary": LEDGER_BOUNDARY, "trace_id": trace_id, "request_id": rid,
666 "approval_id": approval_id, "approver": approver, "path": path, "target": tgt,
667 "approved_proposal_sha256": approved_sha, "content_sha256": content_sha256});
668 let report = match client.approved(&proposal, &ws) {
669 Ok(r) => r,
670 Err(e) => {
671 rc["state"] = json!("REFUSED");
672 rc["handoff_error"] = json!(e);
673 self.state.borrow_mut().receipts.push(rc);
674 return Err(e);
675 }
676 };
677 // 2. Check what came back: ids unchanged, both hash identities, a fresh commit.
678 let compose_sha = sha256_hex(format!("filename: {path}\n{content}").as_bytes());
679 let field = |k: &str| report[k].as_str().unwrap_or_default().to_string();
680 let checks = [
681 ("state", field("state"), "COMMITTED".to_string()),
682 ("trace_id", field("trace_id"), trace_id.to_string()),
683 ("request_id", field("request_id"), rid.to_string()),
684 ("approval_id", field("approval_id"), approval_id.to_string()),
685 (
686 "approved_proposal_sha256",
687 field("approved_proposal_sha256"),
688 approved_sha.clone(),
689 ),
690 (
691 "content_sha256",
692 field("content_sha256"),
693 content_sha256.clone(),
694 ),
695 (
696 "compose_proposal_sha256",
697 field("compose_proposal_sha256"),
698 compose_sha.clone(),
699 ),
700 ];
701 let task = &report["task"];
702 let links: Vec<u64> = report["grant_links"]
703 .as_array()
704 .map(|a| a.iter().filter_map(Value::as_u64).collect())
705 .unwrap_or_default();
706 let claim = report["replay_claim"].as_u64().unwrap_or(0);
707 rc["compose_proposal_sha256"] = json!(compose_sha);
708 rc["handoff"] = json!({"state": report["state"], "desk_key_id": report["desk_key_id"],
709 "approved_grant": report["approved_grant"], "target": report["target"],
710 "approval_key": report["approval_key"], "replay_claim": claim,
711 "task": task["task"], "outcome": task["outcome"], "committed": task["committed"],
712 "branch_count": task["branch_count"], "winner": task["winner"],
713 "aegis_pass_mask": task["aegis_pass_mask"], "proposer": task["proposer"],
714 "cx_goal": task["cx_goal"], "cx_evidence": task["cx_evidence"],
715 "cx_promotion": task["cx_promotion"], "winner_digest": task["winner_digest"],
716 "record_digest": task["record_digest"], "grant_links": links});
717 let bad: Vec<String> = checks
718 .iter()
719 .filter(|(_, got, want)| got != want)
720 .map(|(k, got, want)| format!("{k}: daemon {got:?}, expected {want:?}"))
721 .collect();
722 let committed = task["committed"] == json!(true)
723 && task["proposal_sha256"].as_str() == Some(compose_sha.as_str())
724 && links.len() == 2
725 && links.iter().all(|&x| x != 0)
726 && claim != 0;
727 if !bad.is_empty() || !committed {
728 let e = format!(
729 "handoff report does not match the approval ({}{})",
730 bad.join("; "),
731 if committed {
732 ""
733 } else {
734 "; no fresh committed compose run"
735 }
736 );
737 rc["state"] = json!("REFUSED");
738 rc["handoff_error"] = json!(e);
739 self.state.borrow_mut().receipts.push(rc);
740 return Err(e);
741 }
742 // 3. The grant: written by the daemon itself after the committed compose (a reserved
743 // `approved_grant` record keyed on compose_proposal_sha256, linked to promotion, evidence
744 // and the replay claim). This authority never writes its own grant: there is no second
745 // route to an effect.
746 let grant_id = report["approved_grant"].as_u64().unwrap_or(0);
747 let g = client
748 .recall(&[grant_id], None)
749 .ok()
750 .and_then(|r| r["cited"].as_array().and_then(|a| a.first().cloned()))
751 .unwrap_or(Value::Null);
752 let gt: Value = g["text"]
753 .as_str()
754 .and_then(|t| serde_json::from_str(t).ok())
755 .unwrap_or(Value::Null);
756 let glinks: Vec<u64> = g["links"]
757 .as_array()
758 .map(|a| a.iter().filter_map(Value::as_u64).collect())
759 .unwrap_or_default();
760 let grant_ok = grant_id != 0
761 && g["verified"] == json!(true)
762 && g["note"] == json!("authorization")
763 && gt["approved_grant"] == json!(1)
764 && gt["proposal_sha256"].as_str() == Some(compose_sha.as_str())
765 && gt["path"].as_str() == Some(path)
766 && gt["content_sha256"].as_str() == Some(content_sha256.as_str())
767 && gt["target"].as_str() == Some(tgt.as_str())
768 && report["target"].as_str() == Some(tgt.as_str())
769 && gt["replay_claim"].as_u64() == Some(claim)
770 && [links[0], links[1], claim]
771 .iter()
772 .all(|x| glinks.contains(x));
773 if !grant_ok {
774 let e = format!("daemon grant #{grant_id} does not match the committed approval: {g}");
775 rc["state"] = json!("REFUSED");
776 rc["handoff_error"] = json!(e);
777 self.state.borrow_mut().receipts.push(rc);
778 return Err(e);
779 }
780 self.state.borrow_mut().grants_minted += 1;
781 let prior = gt["prior_sha256"].clone();
782 let hook = self.state.borrow_mut().before_intent.take();
783 if let Some(mut h) = hook {
784 h(&target);
785 self.state.borrow_mut().before_intent = Some(h);
786 }
787 rc["prior_sha256"] = prior;
788 rc["grant_id"] = json!(grant_id);
789 rc["grant_digest"] = g["digest"].clone();
790 rc["proposal_sha256"] = json!(compose_sha);
791 // 4. Intent (on compose_proposal_sha256), write, ack.
792 let intent = match client.intent(
793 grant_id,
794 &compose_sha,
795 path,
796 &tgt,
797 &content_sha256,
798 self_executor(),
799 ) {
800 Ok(i) => i,
801 Err(e) => {
802 rc["state"] = json!("REFUSED");
803 rc["daemon_error"] = json!(e);
804 self.state.borrow_mut().receipts.push(rc);
805 return Err(e);
806 }
807 };
808 let intent_id = intent["id"].as_u64().ok_or("intent without id")?;
809 let written = atomic_write(Path::new(&ws), &target, content.as_bytes());
810 let disk = file_sha256(&target);
811 let reported = json!({"written_sha256": disk.as_ref().ok().cloned().flatten(),
812 "bytes": content.len(), "error": written.as_ref().err()});
813 rc["intent_id"] = json!(intent_id);
814 rc["intent_digest"] = intent["digest"].clone();
815 rc["disk_sha256"] = reported["written_sha256"].clone();
816 let hook = self.state.borrow_mut().before_ack.take();
817 if let Some(mut h) = hook {
818 h(&target);
819 self.state.borrow_mut().before_ack = Some(h);
820 }
821 let ack = client.ack(intent_id, &reported);
822 let state = match &ack {
823 Ok(a) => {
824 rc["ack_record_id"] = a["id"].clone();
825 rc["ack_digest"] = a["digest"].clone();
826 let id = a["id"].as_u64().unwrap_or(0);
827 client
828 .recall(&[id], None)
829 .ok()
830 .and_then(|r| r["cited"][0]["text"].as_str().map(str::to_string))
831 .and_then(|t| serde_json::from_str::<Value>(&t).ok())
832 .and_then(|v| v["state"].as_str().map(str::to_string))
833 .unwrap_or_else(|| "UNRESOLVED".into())
834 }
835 Err(e) => {
836 rc["ack_error"] = json!(e);
837 "UNRESOLVED".into()
838 }
839 };
840 rc["state"] = json!(state);
841 self.state.borrow_mut().receipts.push(rc.clone());
842 if state == "DONE" {
843 Ok(rc)
844 } else {
845 Err(format!("effect not done: {rc}"))
846 }
847 }
848}
849
850/// The parent of `target` must still resolve (symlinks followed) to itself, inside `workspace`
851/// (canonical). Checked before the temp file is created and again just before the rename.
852fn parent_confined(workspace: &Path, target: &Path) -> Result<PathBuf, String> {
853 let parent = target
854 .parent()
855 .ok_or_else(|| format!("write {}: no parent directory", target.display()))?;
856 let real =
857 fs::canonicalize(parent).map_err(|e| format!("write {}: parent: {e}", target.display()))?;
858 if real != parent || !real.starts_with(workspace) {
859 return Err(format!(
860 "write {}: refused, parent {} resolves to {} (outside the workspace or through a symlink)",
861 target.display(),
862 parent.display(),
863 real.display()
864 ));
865 }
866 Ok(real)
867}
868
869/// A random hex suffix for the temp file name (no new dependency: /dev/urandom).
870fn random_suffix() -> Result<String, String> {
871 let mut b = [0u8; 16];
872 fs::File::open("/dev/urandom")
873 .and_then(|mut f| f.read_exact(&mut b))
874 .map_err(|e| format!("random temp name: {e}"))?;
875 Ok(b.iter().map(|x| format!("{x:02x}")).collect())
876}
877
878/// The process umask, read from `/proc/self/status` (no new dependency, no unsafe). When the
879/// field cannot be read, the conventional 022 is assumed (the file then gets 0644).
880fn process_umask() -> u32 {
881 fs::read_to_string("/proc/self/status")
882 .ok()
883 .and_then(|s| {
884 s.lines()
885 .find_map(|l| l.strip_prefix("Umask:"))
886 .and_then(|v| u32::from_str_radix(v.trim(), 8).ok())
887 })
888 .unwrap_or(0o022)
889}
890
891/// The mode the written file ends with: an existing regular target keeps its permission bits;
892/// a new file gets what `File::create` gave before the x4 change, 0666 less the umask.
893fn final_mode(target: &Path) -> u32 {
894 match fs::symlink_metadata(target) {
895 Ok(m) if m.file_type().is_file() => m.permissions().mode() & 0o777,
896 _ => 0o666 & !process_umask(),
897 }
898}
899
900/// Write `bytes` to `target` through a temp file in the same, confined directory: the temp file
901/// gets an unpredictable name and is opened `create_new` + `O_NOFOLLOW`, mode 0600, so a symlink
902/// planted at a guessed name is never followed (476ca4 x4); the parent is re-checked inside the
903/// workspace just before the rename, which is refused otherwise. Before the rename the temp file
904/// is set (through its open handle) to [`final_mode`], so the rename does not leave the written
905/// file at 0600.
906fn atomic_write(workspace: &Path, target: &Path, bytes: &[u8]) -> Result<(), String> {
907 let parent = parent_confined(workspace, target)?;
908 let name = target
909 .file_name()
910 .map(|n| n.to_string_lossy().into_owned())
911 .unwrap_or_default();
912 let tmp = parent.join(format!(".{name}.interplane-{}.tmp", random_suffix()?));
913 let mode = final_mode(target);
914 let r = fs::OpenOptions::new()
915 .write(true)
916 .create_new(true)
917 .mode(0o600)
918 .custom_flags(libc_o_nofollow())
919 .open(&tmp)
920 .and_then(|mut f| {
921 f.write_all(bytes)?;
922 f.set_permissions(fs::Permissions::from_mode(mode))?;
923 f.sync_all()
924 })
925 .map_err(|e| format!("write {}: temp file: {e}", target.display()))
926 .and_then(|_| parent_confined(workspace, target).map(|_| ()))
927 .and_then(|_| {
928 fs::rename(&tmp, target).map_err(|e| format!("write {}: {e}", target.display()))
929 });
930 if r.is_err() {
931 let _ = fs::remove_file(&tmp);
932 }
933 r
934}
935
936impl RuntimeAuthority for ComposeLedgerAuthority {
937 fn runtime_id(&self) -> &str {
938 RUNTIME_ID
939 }
940
941 fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision {
942 self.shared.decide(req, ctx)
943 }
944
945 fn execute(
946 &mut self,
947 req: &CapabilityRequest,
948 decision: &Decision,
949 ctx: &CallContext,
950 ) -> ToolResult {
951 if req.capability != "write_file" || !decision.is_authorized() {
952 return self.shared.execute(req, decision, ctx);
953 }
954 let rid = req.request_id.as_str();
955 // Only an effect AIEN's EffectLane minted for this request opens the ledger path. The
956 // in-process provider never runs it: the effect runs through the daemon instead. The
957 // route holds the effect (and its grant reservation, sovereign-core #260) until the daemon
958 // answers; the grant's expiry is checked with the adapter's clock just before the handoff
959 // (the commit point of this route). The daemon's durable replay ledger is what spends the
960 // approval; afterwards AIEN's reservation is released with that reason.
961 let effect = self.shared.with(|a| {
962 a.discard_replayed(rid);
963 a.take_minted(rid)
964 });
965 let expiry = match &effect {
966 Some(e) => self.shared.with(|a| a.check_expiry(e)),
967 None => Ok(()),
968 };
969 let minted = effect.is_some();
970 let approver = self
971 .state
972 .borrow()
973 .approvers
974 .get(rid)
975 .cloned()
976 .unwrap_or_else(|| DEFAULT_APPROVER.into());
977 let approval_id = decision
978 .approval
979 .as_ref()
980 .map(|a| a.approval_id.clone())
981 .unwrap_or_default();
982 let out = if let Err(e) = expiry {
983 Err(e)
984 } else if minted {
985 self.write_through_ledger(req, &ctx.trace_id, &approver, &approval_id)
986 } else {
987 Err(format!(
988 "{}: no AIEN-minted effect for this request",
989 crate::NOT_EXECUTED
990 ))
991 };
992 if let Some(e) = effect {
993 e.cancel(match &out {
994 Ok(_) => "interplane ledger route: the daemon's durable replay ledger spent this approval",
995 Err(_) => "interplane ledger route: refused, nothing written by this route",
996 });
997 }
998 let mut r = match out {
999 Ok(rc) => ToolResult::ok(rid, json!({"receipt": rc})),
1000 Err(e) => ToolResult::failed(
1001 Some(rid),
1002 ResultStatus::Error,
1003 ErrorCode::ExecutionError,
1004 &e,
1005 ),
1006 };
1007 let ok = r.status == ResultStatus::Ok;
1008 r.provenance = Some(ResultProvenance {
1009 runtime: Some(RUNTIME_ID.into()),
1010 capability: Some(req.capability.clone()),
1011 duration_ms: Some(0),
1012 content_kind: ok.then_some(ContentKind::ToolResult),
1013 trust: ok.then_some(TrustLevel::TrustedRuntime),
1014 trusted: None,
1015 extensions: Map::new(),
1016 });
1017 r
1018 }
1019
1020 fn catalog(&self) -> Catalog {
1021 self.shared.catalog()
1022 }
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027 use super::*;
1028
1029 /// 476ca4 x4 hardening: the write stays in a confined parent and never follows a symlink.
1030 #[test]
1031 fn atomic_write_stays_inside_the_workspace() {
1032 let tmp = tempfile::tempdir().unwrap();
1033 let root = fs::canonicalize(tmp.path()).unwrap();
1034 let ws = root.join("ws");
1035 let outdir = root.join("outdir");
1036 fs::create_dir_all(&ws).unwrap();
1037 fs::create_dir_all(&outdir).unwrap();
1038 // Honest write: lands, no temp left behind.
1039 atomic_write(&ws, &ws.join("a.txt"), b"one\n").unwrap();
1040 assert_eq!(fs::read(ws.join("a.txt")).unwrap(), b"one\n");
1041 assert_eq!(
1042 fs::read_dir(&ws).unwrap().count(),
1043 1,
1044 "temp file left behind"
1045 );
1046 // Parent directory is a symlink to outside: refused, nothing written outside.
1047 std::os::unix::fs::symlink(&outdir, ws.join("sub")).unwrap();
1048 let e = atomic_write(&ws, &ws.join("sub/b.txt"), b"two\n").unwrap_err();
1049 assert!(e.contains("refused"), "{e}");
1050 assert_eq!(fs::read_dir(&outdir).unwrap().count(), 0);
1051 // A parent outside the workspace altogether: refused.
1052 let e = atomic_write(&ws, &outdir.join("c.txt"), b"three\n").unwrap_err();
1053 assert!(e.contains("refused"), "{e}");
1054 assert_eq!(fs::read_dir(&outdir).unwrap().count(), 0);
1055 // Two temp names never repeat.
1056 assert_ne!(random_suffix().unwrap(), random_suffix().unwrap());
1057 }
1058
1059 /// The temp file is created 0600, but the written file keeps the existing target's mode, and
1060 /// a new file gets 0666 less the umask, as `File::create` gave before the x4 change.
1061 #[test]
1062 fn atomic_write_keeps_the_target_mode_or_the_umask_default() {
1063 let tmp = tempfile::tempdir().unwrap();
1064 let ws = fs::canonicalize(tmp.path()).unwrap();
1065 let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
1066 // New file: the old default, observed the same way File::create sets it.
1067 let probe = ws.join("probe.txt");
1068 fs::File::create(&probe).unwrap();
1069 let old_default = mode(&probe);
1070 fs::remove_file(&probe).unwrap();
1071 assert_eq!(old_default, 0o666 & !process_umask());
1072 atomic_write(&ws, &ws.join("new.txt"), b"new\n").unwrap();
1073 assert_eq!(mode(&ws.join("new.txt")), old_default);
1074 assert_ne!(mode(&ws.join("new.txt")), 0o600, "temp mode leaked");
1075 // Existing target: its mode survives the replace, both tighter and looser than default.
1076 for m in [0o640, 0o600, 0o755] {
1077 let t = ws.join(format!("existing-{m:o}.txt"));
1078 fs::write(&t, b"old\n").unwrap();
1079 fs::set_permissions(&t, fs::Permissions::from_mode(m)).unwrap();
1080 atomic_write(&ws, &t, b"replaced\n").unwrap();
1081 assert_eq!(fs::read(&t).unwrap(), b"replaced\n");
1082 assert_eq!(mode(&t), m, "mode of an existing {m:o} target");
1083 }
1084 }
1085
1086 /// Golden vectors, computed outside this crate (`openssl dgst -sha256 -mac HMAC`) over the
1087 /// bytes sovereign-core `approved_auth` signs, so a change to a tag, a separator or the
1088 /// binding's field order fails here and not only in the `--ignored` real-daemon run.
1089 #[test]
1090 fn desk_macs_match_fixed_vectors() {
1091 let key: [u8; 32] = std::array::from_fn(|i| i as u8);
1092 let desk = DeskKey {
1093 key,
1094 id: "0123456789abcdef".into(),
1095 };
1096 let b = ApprovalBinding {
1097 trace_id: "t-1".into(),
1098 request_id: "r-1".into(),
1099 approval_id: "A-1".into(),
1100 approver: "host".into(),
1101 path: "/ws/a.txt".into(),
1102 content_sha256: "cc".into(),
1103 approved_proposal_sha256: "bb".into(),
1104 desk_key_id: "0123456789abcdef".into(),
1105 workspace: "/ws".into(),
1106 };
1107 assert_eq!(
1108 String::from_utf8(b.bytes()).unwrap(),
1109 r#"{"approval_id":"A-1","approved_proposal_sha256":"bb","approver":"host","content_sha256":"cc","desk_key_id":"0123456789abcdef","path":"/ws/a.txt","request_id":"r-1","trace_id":"t-1","v":"aien.approval.v2","workspace":"/ws"}"#
1110 );
1111 assert_eq!(
1112 desk.mac(&b),
1113 "314669cd8b3848f7c92f8354cda5265b14051902e944e5ef464ed5bb216604d9"
1114 );
1115 assert_eq!(
1116 desk.requirements_mac(&b, BOUND_REQUIREMENTS),
1117 "467f2dfe43034b856ec7e9ecb80643410eac39d4520f6c62bda55a17a12d248a"
1118 );
1119 assert_eq!(
1120 desk.requirements_mac(&b, "two lines"),
1121 "d29340b1c0661149dcc337aebad1866fe71cdb33bd1718e9cfcdda55d1347bf1"
1122 );
1123 }
1124}