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
aien-sovereign-core-mv / crates / aien-runtime / src / effects.rs
| 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 | //! NEXT-PHASE-2: durable effect intents on the compose home's Cortex journal |
| 17 | //! (ACCEPTANCE-v2 section 2). |
| 18 | //! |
| 19 | //! An external effect (today: the S5 `write_file`) is bracketed by host |
| 20 | //! records of kind `effect`, text JSON with a `phase` field: |
| 21 | //! |
| 22 | //! intent appended by the daemon, durable (Cortex `CX_OPEN_SYNC`) |
| 23 | //! BEFORE the executor touches the world; one per authorization |
| 24 | //! ack appended after the write; its state is read from the world |
| 25 | //! reconcile appended later (daemon start, operator request, operator |
| 26 | //! declaration) for an intent that never got a terminal state |
| 27 | //! |
| 28 | //! States: OPEN (intent, nothing after it), DONE, NOT_DONE, UNRESOLVED. |
| 29 | //! The world decides: target digest = content digest -> DONE, = the digest |
| 30 | //! the operator authorized against (`prior_sha256`) -> NOT_DONE, else |
| 31 | //! UNRESOLVED. An effect is never re-run by this module; a retry after |
| 32 | //! NOT_DONE needs a new authorization. |
| 33 | //! |
| 34 | //! Operator control records (kind `authorization`, text with `control`): |
| 35 | //! `stop`, `resume`, `revoke`. A stop is durable; a grant older than the |
| 36 | //! newest stop is stale forever. |
| 37 | //! |
| 38 | //! Grants (sovereign-core #261). The ledger honours only grants the daemon wrote |
| 39 | //! itself: `approved_grant` (ComposeApprovedProposal, backed by a COMMITTED |
| 40 | //! replay claim) and `minted_grant` (ComposeAuthorize, backed by a |
| 41 | //! `compose_commit` record the daemon wrote when its own compose run |
| 42 | //! committed the proposal). A caller-written `authorization` note (any record |
| 43 | //! with neither marker, including ones already in a journal from before this |
| 44 | //! rule) is read but never honoured: it opens no intent, and an intent it |
| 45 | //! opened earlier is settled UNRESOLVED by the world check (never DONE, never |
| 46 | //! NOT_DONE by the daemon itself) and an operator may not declare it DONE; an |
| 47 | //! operator `--declare not_done` is still accepted. |
| 48 | //! |
| 49 | //! The ledger is rebuilt from the journal on every call, under the |
| 50 | //! compose-home lock, so the check and the intent append are one step. |
| 51 | use crate::compose::{record_view, ComposeBridge, ComposeHome}; |
| 52 | use crate::control::{ |
| 53 | ComposeControlReport, ComposeNoteReport, ComposeReconcileReport, ComposeRecordView, |
| 54 | ControlResponse, ObjectiveBinding, ReconcileDeclare, ReconcileOutcome, |
| 55 | }; |
| 56 | use aien_omega_compose::{hex, NoteKind}; |
| 57 | use serde_json::{json, Value}; |
| 58 | use sha2::{Digest, Sha256}; |
| 59 | use std::collections::BTreeMap; |
| 60 | use std::fmt; |
| 61 | use std::os::fd::AsRawFd; |
| 62 | use std::path::Path; |
| 63 | |
| 64 | pub const PHASE_INTENT: &str = "intent"; |
| 65 | pub const PHASE_ACK: &str = "ack"; |
| 66 | pub const PHASE_RECONCILE: &str = "reconcile"; |
| 67 | /// Host records the ledger reads in one recall; more is refused, not truncated. |
| 68 | const HOST_RECALL_MAX: u32 = 4096; |
| 69 | |
| 70 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 71 | pub enum EffectState { |
| 72 | Open, |
| 73 | Done, |
| 74 | NotDone, |
| 75 | Unresolved, |
| 76 | } |
| 77 | |
| 78 | impl EffectState { |
| 79 | pub fn name(self) -> &'static str { |
| 80 | match self { |
| 81 | Self::Open => "OPEN", |
| 82 | Self::Done => "DONE", |
| 83 | Self::NotDone => "NOT_DONE", |
| 84 | Self::Unresolved => "UNRESOLVED", |
| 85 | } |
| 86 | } |
| 87 | fn parse(s: &str) -> Option<Self> { |
| 88 | match s { |
| 89 | "DONE" => Some(Self::Done), |
| 90 | "NOT_DONE" => Some(Self::NotDone), |
| 91 | "UNRESOLVED" => Some(Self::Unresolved), |
| 92 | _ => None, |
| 93 | } |
| 94 | } |
| 95 | pub fn terminal(self) -> bool { |
| 96 | matches!(self, Self::Done | Self::NotDone) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// A named refusal at the effect boundary (`EFFECT_REFUSED <name>: detail`). |
| 101 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 102 | pub struct Refusal { |
| 103 | pub name: &'static str, |
| 104 | pub detail: String, |
| 105 | } |
| 106 | |
| 107 | impl Refusal { |
| 108 | fn new(name: &'static str, detail: impl Into<String>) -> Self { |
| 109 | Self { |
| 110 | name, |
| 111 | detail: detail.into(), |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | impl fmt::Display for Refusal { |
| 117 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 118 | write!(f, "EFFECT_REFUSED {}: {}", self.name, self.detail) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// One authorization record, as the ledger reads it. |
| 123 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 124 | pub struct Grant { |
| 125 | pub id: u64, |
| 126 | pub proposal_sha256: String, |
| 127 | pub path: String, |
| 128 | pub content_sha256: String, |
| 129 | /// Absolute target (absent in grants written before NEXT-PHASE-2). |
| 130 | pub target: Option<String>, |
| 131 | /// `Some(None)`: authorized against an absent target. `None`: the grant |
| 132 | /// predates NEXT-PHASE-2 and names no prior state (always stale). |
| 133 | pub prior_sha256: Option<Option<String>>, |
| 134 | /// The workspace the target must stay inside (sovereign-core #249). A |
| 135 | /// grant without one opens no intent. |
| 136 | pub workspace: Option<String>, |
| 137 | /// Set on the grant the daemon writes after an approved compose (#249). |
| 138 | pub approved: Option<ApprovedGrant>, |
| 139 | /// Set on the grant `ComposeAuthorize` minted (#261). |
| 140 | pub minted: Option<MintedGrant>, |
| 141 | /// sovereign-core #408: the objective record the grant was approved for. |
| 142 | pub objective: Option<GrantObjective>, |
| 143 | /// The record's links. |
| 144 | pub links: Vec<u64>, |
| 145 | } |
| 146 | |
| 147 | impl Grant { |
| 148 | /// True for a grant the daemon wrote itself (approved or minted). A |
| 149 | /// caller-written note, or an old one already in a journal, is not. |
| 150 | pub fn honoured(&self) -> bool { |
| 151 | self.approved.is_some() || self.minted.is_some() |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// Marker field of the grant the daemon itself writes after a COMMITTED |
| 156 | /// approved compose (sovereign-core #249). Reserved: `ComposeNote` refuses it. |
| 157 | pub const APPROVED_GRANT: &str = "approved_grant"; |
| 158 | |
| 159 | /// Marker field of the grant `ComposeAuthorize` mints (sovereign-core #261). |
| 160 | /// Reserved: `ComposeNote` refuses every `authorization` note. |
| 161 | /// Prefix of the `disk_error` of an intent whose grant the daemon did not mint. |
| 162 | pub const NOT_DAEMON_MINTED: &str = "NotDaemonMinted"; |
| 163 | |
| 164 | pub const MINTED_GRANT: &str = "minted_grant"; |
| 165 | |
| 166 | /// Marker field of the record the daemon writes when its own compose run |
| 167 | /// COMMITTED a one-file proposal (sovereign-core #261). Reserved. |
| 168 | pub const COMPOSE_COMMIT: &str = "compose_commit"; |
| 169 | |
| 170 | /// sovereign-core #408: the objective a grant is bound to, as minted. |
| 171 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 172 | pub struct GrantObjective { |
| 173 | pub id: String, |
| 174 | /// sha256 of the objective text the record held when the grant was minted. |
| 175 | pub text_sha256: String, |
| 176 | /// sha256 of the record file's bytes then. |
| 177 | pub record_sha256: String, |
| 178 | } |
| 179 | |
| 180 | /// What a minted grant is backed by: the daemon's own compose-commit record. |
| 181 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 182 | pub struct MintedGrant { |
| 183 | pub commit: u64, |
| 184 | } |
| 185 | |
| 186 | /// A compose-commit record as the ledger reads it. |
| 187 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 188 | pub struct CommitRow { |
| 189 | pub id: u64, |
| 190 | pub cx_promotion: u64, |
| 191 | pub cx_evidence: u64, |
| 192 | pub proposal_sha256: String, |
| 193 | pub path: String, |
| 194 | pub content_sha256: String, |
| 195 | pub workspace: String, |
| 196 | /// sovereign-core #408: sha256 of the goal the compose ran for (absent in |
| 197 | /// commit records written before #408). |
| 198 | pub goal_sha256: Option<String>, |
| 199 | } |
| 200 | |
| 201 | /// What an approved grant must be backed by: a COMMITTED replay claim whose |
| 202 | /// commit evidence names the grant's proposal, promotion and evidence. |
| 203 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 204 | pub struct ApprovedLink { |
| 205 | pub approval_key: String, |
| 206 | pub replay_claim: u64, |
| 207 | pub cx_promotion: u64, |
| 208 | pub cx_evidence: u64, |
| 209 | } |
| 210 | |
| 211 | /// What the ledger reads back from an approved grant: its link and the bound |
| 212 | /// approval identity its text names (so the approval key can be recomputed). |
| 213 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 214 | pub struct ApprovedGrant { |
| 215 | pub link: ApprovedLink, |
| 216 | pub identity: crate::approved_auth::ApprovalIdentity, |
| 217 | } |
| 218 | |
| 219 | /// What an executor asks for before it touches the world. |
| 220 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 221 | pub struct IntentRequest { |
| 222 | pub authorization: u64, |
| 223 | pub proposal_sha256: String, |
| 224 | pub path: String, |
| 225 | pub target: String, |
| 226 | pub content_sha256: String, |
| 227 | pub executor_pid: u32, |
| 228 | pub executor_start: u64, |
| 229 | } |
| 230 | |
| 231 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 232 | pub struct IntentRow { |
| 233 | pub id: u64, |
| 234 | pub authorization: u64, |
| 235 | pub path: String, |
| 236 | pub target: String, |
| 237 | pub content_sha256: String, |
| 238 | pub prior_sha256: Option<String>, |
| 239 | pub executor_pid: u32, |
| 240 | pub executor_start: u64, |
| 241 | pub state: EffectState, |
| 242 | /// Record that set `state` (0 while OPEN). |
| 243 | pub state_record: u64, |
| 244 | /// Target digest of the newest UNRESOLVED record (so one is written per |
| 245 | /// distinct digest, not one per daemon start). |
| 246 | pub unresolved_digest: Option<Option<String>>, |
| 247 | /// sovereign-core #408: the objective of the grant, carried on the intent. |
| 248 | pub objective_id: Option<String>, |
| 249 | } |
| 250 | |
| 251 | /// The effect ledger of one compose home, rebuilt from its host records. |
| 252 | #[derive(Debug, Default, Clone)] |
| 253 | pub struct Ledger { |
| 254 | pub grants: BTreeMap<u64, Grant>, |
| 255 | /// Approved grants by replay claim: more than one for a claim opens none. |
| 256 | pub approved_by_claim: BTreeMap<u64, Vec<u64>>, |
| 257 | /// Compose-commit records the daemon wrote (#261), by record id. |
| 258 | pub commits: BTreeMap<u64, CommitRow>, |
| 259 | /// Minted grants by compose-commit record, oldest first. |
| 260 | pub minted_by_commit: BTreeMap<u64, Vec<u64>>, |
| 261 | /// Desk-MAC nonces already used by a minted grant (#297): one grant per nonce. |
| 262 | pub desk_nonces: std::collections::BTreeSet<String>, |
| 263 | pub intents: BTreeMap<u64, IntentRow>, |
| 264 | /// authorization id -> intent id (one intent per authorization). |
| 265 | pub spent: BTreeMap<u64, u64>, |
| 266 | /// authorization id -> legacy (pre-NEXT-PHASE-2) write_file effect record. |
| 267 | pub legacy_spent: BTreeMap<u64, u64>, |
| 268 | /// authorization id -> revoke record. |
| 269 | pub revoked: BTreeMap<u64, u64>, |
| 270 | pub stops: Vec<u64>, |
| 271 | pub resumes: Vec<u64>, |
| 272 | } |
| 273 | |
| 274 | fn corrupt(id: u64, why: impl fmt::Display) -> Refusal { |
| 275 | Refusal::new("CorruptLedger", format!("host record #{id}: {why}")) |
| 276 | } |
| 277 | |
| 278 | fn s(v: &Value, k: &str, id: u64) -> Result<String, Refusal> { |
| 279 | v.get(k) |
| 280 | .and_then(Value::as_str) |
| 281 | .map(str::to_string) |
| 282 | .ok_or_else(|| corrupt(id, format!("field {k:?} missing or not a string"))) |
| 283 | } |
| 284 | |
| 285 | fn u(v: &Value, k: &str, id: u64) -> Result<u64, Refusal> { |
| 286 | v.get(k) |
| 287 | .and_then(Value::as_u64) |
| 288 | .ok_or_else(|| corrupt(id, format!("field {k:?} missing or not a number"))) |
| 289 | } |
| 290 | |
| 291 | /// `null` -> Some(None), "hex" -> Some(Some), missing -> None. |
| 292 | fn opt_digest(v: &Value, k: &str, id: u64) -> Result<Option<Option<String>>, Refusal> { |
| 293 | match v.get(k) { |
| 294 | None => Ok(None), |
| 295 | Some(Value::Null) => Ok(Some(None)), |
| 296 | Some(Value::String(x)) => Ok(Some(Some(x.clone()))), |
| 297 | Some(_) => Err(corrupt(id, format!("field {k:?} is not a digest or null"))), |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Missing -> None, a string -> Some, anything else is damaged state. |
| 302 | fn opt_str(v: &Value, k: &str, id: u64) -> Result<Option<String>, Refusal> { |
| 303 | match v.get(k) { |
| 304 | None => Ok(None), |
| 305 | Some(Value::String(x)) => Ok(Some(x.clone())), |
| 306 | Some(_) => Err(corrupt(id, format!("field {k:?} is not a string"))), |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | impl Ledger { |
| 311 | /// Rebuild from host records, oldest first. Any unverified record, or a |
| 312 | /// gated record that does not parse, refuses the whole ledger: effects |
| 313 | /// are never decided on damaged state. |
| 314 | pub fn from_records(host: &[ComposeRecordView]) -> Result<Self, Refusal> { |
| 315 | let mut l = Ledger::default(); |
| 316 | for r in host { |
| 317 | if !r.verified { |
| 318 | return Err(corrupt(r.id, "digest does not verify")); |
| 319 | } |
| 320 | let Some(text) = r.text.as_deref() else { |
| 321 | continue; |
| 322 | }; |
| 323 | match r.note.as_deref() { |
| 324 | Some("authorization") => l.read_authorization(r.id, text, &r.links)?, |
| 325 | Some("effect") => l.read_effect(r.id, text)?, |
| 326 | _ => {} |
| 327 | } |
| 328 | } |
| 329 | Ok(l) |
| 330 | } |
| 331 | |
| 332 | fn read_authorization(&mut self, id: u64, text: &str, links: &[u64]) -> Result<(), Refusal> { |
| 333 | let v: Value = match serde_json::from_str(text) { |
| 334 | Ok(v) => v, |
| 335 | // An authorization that is not JSON authorizes nothing. |
| 336 | Err(_) => return Ok(()), |
| 337 | }; |
| 338 | if let Some(c) = v.get("control") { |
| 339 | match c.as_str() { |
| 340 | Some("stop") => self.stops.push(id), |
| 341 | Some("resume") => self.resumes.push(id), |
| 342 | Some("revoke") => { |
| 343 | let a = u(&v, "authorization", id)?; |
| 344 | self.revoked.entry(a).or_insert(id); |
| 345 | } |
| 346 | _ => return Err(corrupt(id, "unknown control record")), |
| 347 | } |
| 348 | return Ok(()); |
| 349 | } |
| 350 | let (Some(p), Some(path), Some(c)) = ( |
| 351 | v.get("proposal_sha256").and_then(Value::as_str), |
| 352 | v.get("path").and_then(Value::as_str), |
| 353 | v.get("content_sha256").and_then(Value::as_str), |
| 354 | ) else { |
| 355 | return Ok(()); |
| 356 | }; |
| 357 | let objective = match opt_str(&v, "objective_id", id)? { |
| 358 | None => None, |
| 359 | Some(oid) => Some(GrantObjective { |
| 360 | id: oid, |
| 361 | text_sha256: s(&v, "objective_text_sha256", id)?, |
| 362 | record_sha256: s(&v, "objective_record_sha256", id)?, |
| 363 | }), |
| 364 | }; |
| 365 | self.grants.insert( |
| 366 | id, |
| 367 | Grant { |
| 368 | id, |
| 369 | proposal_sha256: p.to_string(), |
| 370 | path: path.to_string(), |
| 371 | content_sha256: c.to_string(), |
| 372 | target: v.get("target").and_then(Value::as_str).map(str::to_string), |
| 373 | prior_sha256: opt_digest(&v, "prior_sha256", id)?, |
| 374 | workspace: v |
| 375 | .get("workspace") |
| 376 | .and_then(Value::as_str) |
| 377 | .map(str::to_string), |
| 378 | minted: match v.get(MINTED_GRANT) { |
| 379 | None => None, |
| 380 | Some(_) => { |
| 381 | let commit = u(&v, "compose_commit", id)?; |
| 382 | self.minted_by_commit.entry(commit).or_default().push(id); |
| 383 | if let Some(n) = v.get("desk_nonce").and_then(Value::as_str) { |
| 384 | self.desk_nonces.insert(n.to_string()); |
| 385 | } |
| 386 | Some(MintedGrant { commit }) |
| 387 | } |
| 388 | }, |
| 389 | approved: match v.get(APPROVED_GRANT) { |
| 390 | None => None, |
| 391 | Some(_) => { |
| 392 | let link = ApprovedLink { |
| 393 | approval_key: s(&v, "approval_key", id)?, |
| 394 | replay_claim: u(&v, "replay_claim", id)?, |
| 395 | cx_promotion: u(&v, "cx_promotion", id)?, |
| 396 | cx_evidence: u(&v, "cx_evidence", id)?, |
| 397 | }; |
| 398 | self.approved_by_claim |
| 399 | .entry(link.replay_claim) |
| 400 | .or_default() |
| 401 | .push(id); |
| 402 | Some(ApprovedGrant { |
| 403 | identity: crate::approved_auth::ApprovalIdentity { |
| 404 | trace_id: s(&v, "trace_id", id)?, |
| 405 | request_id: s(&v, "request_id", id)?, |
| 406 | approval_id: s(&v, "approval_id", id)?, |
| 407 | approver: s(&v, "approver", id)?, |
| 408 | path: path.to_string(), |
| 409 | content_sha256: c.to_string(), |
| 410 | approved_proposal_sha256: s(&v, "approved_proposal_sha256", id)?, |
| 411 | desk_key_id: s(&v, "desk_key_id", id)?, |
| 412 | workspace: s(&v, "workspace", id)?, |
| 413 | }, |
| 414 | link, |
| 415 | }) |
| 416 | } |
| 417 | }, |
| 418 | objective, |
| 419 | links: links.to_vec(), |
| 420 | }, |
| 421 | ); |
| 422 | Ok(()) |
| 423 | } |
| 424 | |
| 425 | fn read_effect(&mut self, id: u64, text: &str) -> Result<(), Refusal> { |
| 426 | let Ok(v) = serde_json::from_str::<Value>(text) else { |
| 427 | return Ok(()); |
| 428 | }; |
| 429 | if v.get(COMPOSE_COMMIT).is_some() { |
| 430 | self.commits.insert( |
| 431 | id, |
| 432 | CommitRow { |
| 433 | id, |
| 434 | cx_promotion: u(&v, "cx_promotion", id)?, |
| 435 | cx_evidence: u(&v, "cx_evidence", id)?, |
| 436 | proposal_sha256: s(&v, "proposal_sha256", id)?, |
| 437 | path: s(&v, "path", id)?, |
| 438 | content_sha256: s(&v, "content_sha256", id)?, |
| 439 | workspace: s(&v, "workspace", id)?, |
| 440 | goal_sha256: opt_str(&v, "goal_sha256", id)?, |
| 441 | }, |
| 442 | ); |
| 443 | return Ok(()); |
| 444 | } |
| 445 | let Some(phase) = v.get("phase") else { |
| 446 | // NEXT-PHASE-1 effect notes: a write_file spends its authorization. |
| 447 | if v.get("tool").and_then(Value::as_str) == Some("write_file") { |
| 448 | if let Some(a) = v.get("authorization").and_then(Value::as_u64) { |
| 449 | self.legacy_spent.entry(a).or_insert(id); |
| 450 | } |
| 451 | } |
| 452 | return Ok(()); |
| 453 | }; |
| 454 | match phase.as_str() { |
| 455 | Some(PHASE_INTENT) => { |
| 456 | let a = u(&v, "authorization", id)?; |
| 457 | if let Some(prev) = self.spent.get(&a) { |
| 458 | return Err(corrupt( |
| 459 | id, |
| 460 | format!("second intent for authorization #{a} (first #{prev})"), |
| 461 | )); |
| 462 | } |
| 463 | let ex = v.get("executor").cloned().unwrap_or(Value::Null); |
| 464 | let row = IntentRow { |
| 465 | id, |
| 466 | authorization: a, |
| 467 | path: s(&v, "path", id)?, |
| 468 | target: s(&v, "target", id)?, |
| 469 | content_sha256: s(&v, "content_sha256", id)?, |
| 470 | prior_sha256: opt_digest(&v, "prior_sha256", id)? |
| 471 | .ok_or_else(|| corrupt(id, "intent without prior_sha256"))?, |
| 472 | executor_pid: u(&ex, "pid", id)? as u32, |
| 473 | executor_start: u(&ex, "start", id)?, |
| 474 | state: EffectState::Open, |
| 475 | state_record: 0, |
| 476 | unresolved_digest: None, |
| 477 | objective_id: opt_str(&v, "objective_id", id)?, |
| 478 | }; |
| 479 | self.spent.insert(a, id); |
| 480 | self.intents.insert(id, row); |
| 481 | } |
| 482 | Some(PHASE_ACK) | Some(PHASE_RECONCILE) => { |
| 483 | let i = u(&v, "intent", id)?; |
| 484 | let st = EffectState::parse(&s(&v, "state", id)?) |
| 485 | .ok_or_else(|| corrupt(id, "unknown effect state"))?; |
| 486 | let disk = opt_digest(&v, "disk_sha256", id)?.unwrap_or(None); |
| 487 | let row = self |
| 488 | .intents |
| 489 | .get_mut(&i) |
| 490 | .ok_or_else(|| corrupt(id, format!("names intent #{i}, which is not one")))?; |
| 491 | if row.state.terminal() { |
| 492 | return Err(corrupt( |
| 493 | id, |
| 494 | format!( |
| 495 | "intent #{i} already {} by #{}", |
| 496 | row.state.name(), |
| 497 | row.state_record |
| 498 | ), |
| 499 | )); |
| 500 | } |
| 501 | row.state = st; |
| 502 | row.state_record = id; |
| 503 | if st == EffectState::Unresolved { |
| 504 | row.unresolved_digest = Some(disk); |
| 505 | } |
| 506 | } |
| 507 | _ => return Err(corrupt(id, "unknown effect phase")), |
| 508 | } |
| 509 | Ok(()) |
| 510 | } |
| 511 | |
| 512 | /// True while the newest stop/resume record is a stop. |
| 513 | pub fn stopped(&self) -> Option<u64> { |
| 514 | let stop = self.stops.last().copied()?; |
| 515 | match self.resumes.last() { |
| 516 | Some(&r) if r > stop => None, |
| 517 | _ => Some(stop), |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | /// The effect-boundary check (ACCEPTANCE-v2 2.3). `current` is the |
| 522 | /// target's digest now (None = absent). |
| 523 | pub fn check_intent( |
| 524 | &self, |
| 525 | req: &IntentRequest, |
| 526 | current: &Option<String>, |
| 527 | ) -> Result<&Grant, Refusal> { |
| 528 | let a = req.authorization; |
| 529 | if let Some(stop) = self.stopped() { |
| 530 | return Err(Refusal::new( |
| 531 | "Stopped", |
| 532 | format!("operator stop #{stop} is in force; resume needs an authorized operator"), |
| 533 | )); |
| 534 | } |
| 535 | let g = self.grants.get(&a).ok_or_else(|| { |
| 536 | Refusal::new( |
| 537 | "NotAuthorized", |
| 538 | format!("cortex.cx#{a} is not a verified authorization"), |
| 539 | ) |
| 540 | })?; |
| 541 | if !g.honoured() { |
| 542 | return Err(Refusal::new( |
| 543 | "NotAuthorized", |
| 544 | format!( |
| 545 | "authorization #{a} is a caller-written note; the daemon honours only grants it minted itself (sovereign-core #261): run aien compose authorize" |
| 546 | ), |
| 547 | )); |
| 548 | } |
| 549 | if g.proposal_sha256 != req.proposal_sha256 |
| 550 | || g.path != req.path |
| 551 | || g.content_sha256 != req.content_sha256 |
| 552 | { |
| 553 | return Err(Refusal::new( |
| 554 | "NotAuthorized", |
| 555 | format!("authorization #{a} names a different proposal"), |
| 556 | )); |
| 557 | } |
| 558 | if let Some(&i) = self.spent.get(&a) { |
| 559 | let row = &self.intents[&i]; |
| 560 | return Err(if row.state.terminal() { |
| 561 | Refusal::new( |
| 562 | "AlreadySpent", |
| 563 | format!( |
| 564 | "authorization #{a} was spent by intent #{i} ({}); a new effect needs a new authorization", |
| 565 | row.state.name() |
| 566 | ), |
| 567 | ) |
| 568 | } else { |
| 569 | Refusal::new( |
| 570 | "ReconciliationRequired", |
| 571 | format!( |
| 572 | "intent #{i} for authorization #{a} is {}; run aien compose reconcile", |
| 573 | row.state.name() |
| 574 | ), |
| 575 | ) |
| 576 | }); |
| 577 | } |
| 578 | if let Some(&e) = self.legacy_spent.get(&a) { |
| 579 | return Err(Refusal::new( |
| 580 | "AlreadySpent", |
| 581 | format!("authorization #{a} was spent by effect #{e} (NEXT-PHASE-1 record)"), |
| 582 | )); |
| 583 | } |
| 584 | if let Some(&r) = self.revoked.get(&a) { |
| 585 | return Err(Refusal::new( |
| 586 | "Revoked", |
| 587 | format!("authorization #{a} revoked by #{r}"), |
| 588 | )); |
| 589 | } |
| 590 | if let Some(&stop) = self.stops.iter().rev().find(|&&x| x > a) { |
| 591 | return Err(Refusal::new( |
| 592 | "Stale", |
| 593 | format!("authorization #{a} predates operator stop #{stop}"), |
| 594 | )); |
| 595 | } |
| 596 | let (Some(target), Some(prior)) = (&g.target, &g.prior_sha256) else { |
| 597 | return Err(Refusal::new( |
| 598 | "Stale", |
| 599 | format!("authorization #{a} names no target state (written before effect intents)"), |
| 600 | )); |
| 601 | }; |
| 602 | if target != &req.target { |
| 603 | return Err(Refusal::new( |
| 604 | "NotAuthorized", |
| 605 | format!( |
| 606 | "authorization #{a} names target {target}, not {}", |
| 607 | req.target |
| 608 | ), |
| 609 | )); |
| 610 | } |
| 611 | if prior != current { |
| 612 | return Err(Refusal::new( |
| 613 | "Stale", |
| 614 | format!( |
| 615 | "target changed since authorization #{a} (authorized against {}, now {})", |
| 616 | prior.as_deref().unwrap_or("absent"), |
| 617 | current.as_deref().unwrap_or("absent") |
| 618 | ), |
| 619 | )); |
| 620 | } |
| 621 | Ok(g) |
| 622 | } |
| 623 | |
| 624 | /// Intents without a terminal state, oldest first. |
| 625 | pub fn unsettled(&self) -> impl Iterator<Item = &IntentRow> { |
| 626 | self.intents.values().filter(|r| !r.state.terminal()) |
| 627 | } |
| 628 | |
| 629 | /// One JSON row per intent, for `aien compose effects`. |
| 630 | pub fn view(&self) -> Value { |
| 631 | json!({ |
| 632 | "stopped": self.stopped(), |
| 633 | "stops": self.stops, "resumes": self.resumes, |
| 634 | "revoked": self.revoked.iter().map(|(a, r)| json!({"authorization": a, "record": r})).collect::<Vec<_>>(), |
| 635 | "legacy_spent": self.legacy_spent.iter().map(|(a, e)| json!({"authorization": a, "effect": e})).collect::<Vec<_>>(), |
| 636 | "intents": self.intents.values().map(|r| { |
| 637 | let mut row = json!({ |
| 638 | "intent": r.id, "authorization": r.authorization, "path": r.path, |
| 639 | "target": r.target, "content_sha256": r.content_sha256, |
| 640 | "prior_sha256": r.prior_sha256, "state": r.state.name(), |
| 641 | "state_record": r.state_record, |
| 642 | "executor": {"pid": r.executor_pid, "start": r.executor_start}, |
| 643 | }); |
| 644 | // #408: only when the intent names one, so older rows read as before. |
| 645 | if let Some(o) = &r.objective_id { |
| 646 | row["objective_id"] = json!(o); |
| 647 | } |
| 648 | row |
| 649 | }).collect::<Vec<_>>(), |
| 650 | }) |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /// sha256 of a file's bytes, None when it does not exist. Anything else |
| 655 | /// that is not a readable regular file is an error. |
| 656 | pub fn file_sha256(path: &Path) -> Result<Option<String>, String> { |
| 657 | match std::fs::symlink_metadata(path) { |
| 658 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 659 | Err(e) => return Err(format!("stat {}: {e}", path.display())), |
| 660 | Ok(m) if !m.file_type().is_file() => { |
| 661 | return Err(format!("{} is not a regular file", path.display())) |
| 662 | } |
| 663 | Ok(_) => {} |
| 664 | } |
| 665 | let b = std::fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?; |
| 666 | Ok(Some(hex(&Sha256::digest(&b)))) |
| 667 | } |
| 668 | |
| 669 | /// The world check of ACCEPTANCE-v2 2.2. Returns the state and the digest seen. |
| 670 | pub fn world_state(row: &IntentRow) -> (EffectState, Result<Option<String>, String>) { |
| 671 | state_from(row, file_sha256(Path::new(&row.target))) |
| 672 | } |
| 673 | |
| 674 | fn state_from( |
| 675 | row: &IntentRow, |
| 676 | now: Result<Option<String>, String>, |
| 677 | ) -> (EffectState, Result<Option<String>, String>) { |
| 678 | let st = match &now { |
| 679 | Ok(Some(d)) if *d == row.content_sha256 => EffectState::Done, |
| 680 | Ok(d) if *d == row.prior_sha256 => EffectState::NotDone, |
| 681 | _ => EffectState::Unresolved, |
| 682 | }; |
| 683 | (st, now) |
| 684 | } |
| 685 | |
| 686 | /// The text of one reconcile record, exactly as it is journalled (`append` writes |
| 687 | /// `to_string()` of it). `st` is the decided state, `world` what the world check saw, |
| 688 | /// `disk` the digest it read or its error, `who` who decided. The seeded .om world |
| 689 | /// check (om/effects/world.om) is compared byte for byte against this function. |
| 690 | pub fn reconcile_text( |
| 691 | row: &IntentRow, |
| 692 | st: EffectState, |
| 693 | world: EffectState, |
| 694 | disk: &Result<Option<String>, String>, |
| 695 | who: &str, |
| 696 | objective: Option<&ObjectiveBinding>, |
| 697 | ) -> Value { |
| 698 | let mut text = json!({ |
| 699 | "phase": PHASE_RECONCILE, "intent": row.id, "authorization": row.authorization, |
| 700 | "state": st.name(), "world": world.name(), |
| 701 | "disk_sha256": disk.as_ref().ok().cloned().flatten(), |
| 702 | "disk_error": disk.as_ref().err(), "by": who, |
| 703 | }); |
| 704 | if let Some(o) = objective { |
| 705 | text["objective_id"] = json!(o.objective_id); |
| 706 | text["objective_record"] = json!(o.record); |
| 707 | } |
| 708 | text |
| 709 | } |
| 710 | |
| 711 | /// The world check, confined (476ca4 c28): the target is read only while it |
| 712 | /// still resolves inside its grant's workspace (`confine_target` again, at |
| 713 | /// ack and reconcile time, so a directory swapped for a symlink after the |
| 714 | /// intent opened is seen). When confinement refuses, or the grant names no |
| 715 | /// workspace, or its grant is not daemon-minted, the state is UNRESOLVED, never |
| 716 | /// DONE or NOT_DONE. |
| 717 | pub fn confined_world_state( |
| 718 | l: &Ledger, |
| 719 | row: &IntentRow, |
| 720 | ) -> (EffectState, Result<Option<String>, String>) { |
| 721 | // sovereign-core #261: an intent whose grant the daemon did not write |
| 722 | // (a caller-written note, opened before this rule) is never settled |
| 723 | // DONE or NOT_DONE by the world check; it stays UNRESOLVED and the operator |
| 724 | // is told why. (An operator declaration of NOT_DONE is still accepted; |
| 725 | // DONE is refused.) |
| 726 | if !l |
| 727 | .grants |
| 728 | .get(&row.authorization) |
| 729 | .is_some_and(Grant::honoured) |
| 730 | { |
| 731 | return ( |
| 732 | EffectState::Unresolved, |
| 733 | Err(format!( |
| 734 | "{NOT_DAEMON_MINTED}: authorization #{} was not minted by the daemon (sovereign-core #261)", |
| 735 | row.authorization |
| 736 | )), |
| 737 | ); |
| 738 | } |
| 739 | let ws = l |
| 740 | .grants |
| 741 | .get(&row.authorization) |
| 742 | .and_then(|g| g.workspace.clone()); |
| 743 | let Some(ws) = ws else { |
| 744 | return ( |
| 745 | EffectState::Unresolved, |
| 746 | Err(format!( |
| 747 | "OutsideWorkspace: authorization #{} names no workspace", |
| 748 | row.authorization |
| 749 | )), |
| 750 | ); |
| 751 | }; |
| 752 | // sovereign-core #267: confine and read through the same held directory |
| 753 | // descriptors, so a swap after the check cannot redirect the read. |
| 754 | match open_confined(&ws, &row.path, &row.target) { |
| 755 | // The file exists but cannot be read: the plain read error, as before. |
| 756 | Err(r) if r.name == "Unreadable" => (EffectState::Unresolved, Err(r.detail)), |
| 757 | Err(r) => { |
| 758 | let r = outside_of(r); |
| 759 | ( |
| 760 | EffectState::Unresolved, |
| 761 | Err(format!("{}: {}", r.name, r.detail)), |
| 762 | ) |
| 763 | } |
| 764 | Ok(t) => state_from(row, t.sha256()), |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | /// Start time of a process (clock ticks since boot, /proc/<pid>/stat field 22). |
| 769 | pub fn process_start_ticks(pid: u32) -> Option<u64> { |
| 770 | let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; |
| 771 | // Field 2 (comm) may hold spaces and parentheses: fields after the last ')'. |
| 772 | let rest = &stat[stat.rfind(')')? + 1..]; |
| 773 | rest.split_whitespace().nth(19)?.parse().ok() |
| 774 | } |
| 775 | |
| 776 | /// This process as an executor: (pid, start ticks). |
| 777 | pub fn self_executor() -> (u32, u64) { |
| 778 | let pid = std::process::id(); |
| 779 | (pid, process_start_ticks(pid).unwrap_or(0)) |
| 780 | } |
| 781 | |
| 782 | /// Is the executor that opened an intent still running? |
| 783 | pub fn executor_alive(pid: u32, start: u64) -> bool { |
| 784 | pid != 0 && start != 0 && process_start_ticks(pid) == Some(start) |
| 785 | } |
| 786 | |
| 787 | /// Effect commands refuse while the start-up reconcile has not succeeded |
| 788 | /// (ACCEPTANCE-v3 2.5): `EFFECT_REFUSED ReconcileFailed`. |
| 789 | fn reconcile_gate(b: &ComposeBridge) -> Result<(), String> { |
| 790 | match b.reconcile_failed() { |
| 791 | None => Ok(()), |
| 792 | Some(why) => Err(Refusal::new( |
| 793 | "ReconcileFailed", |
| 794 | format!("the start-up reconcile did not complete ({why}); run aien compose reconcile"), |
| 795 | ) |
| 796 | .to_string()), |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | /// ComposeNote may not forge gated records (ACCEPTANCE-v2 2.7). |
| 801 | pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { |
| 802 | // sovereign-core #261: no caller writes an authorization, whatever it |
| 803 | // says. Grants come from ComposeAuthorize and ComposeApprovedProposal, |
| 804 | // control records from ComposeControl; all are written by the daemon. |
| 805 | if kind == crate::generation::GENERATION { |
| 806 | return Err( |
| 807 | "ComposeNote: generation records are written only by the daemon when a turn finishes" |
| 808 | .into(), |
| 809 | ); |
| 810 | } |
| 811 | if kind == "authorization" { |
| 812 | return Err( |
| 813 | "ComposeNote: authorization records are written only by the daemon (ComposeAuthorize, ComposeApprovedProposal, ComposeControl); a caller-written grant is never honoured (sovereign-core #261)" |
| 814 | .into(), |
| 815 | ); |
| 816 | } |
| 817 | let Ok(v) = serde_json::from_str::<Value>(text) else { |
| 818 | return Ok(()); |
| 819 | }; |
| 820 | // Provenance evidence is copied by the daemon along its own chain; no caller sets it. |
| 821 | if v.get(crate::generation::PROVENANCE).is_some() { |
| 822 | return Err( |
| 823 | "ComposeNote: the provenance field is written only by the daemon (generation link and ALLEN agent id)" |
| 824 | .into(), |
| 825 | ); |
| 826 | } |
| 827 | match kind { |
| 828 | // The daemon's generation record (evidence only, never an input to any |
| 829 | // decision): effect-class note with the marker field. |
| 830 | "effect" if v.get(crate::generation::GENERATION).is_some() => Err( |
| 831 | "ComposeNote: generation records are written only by the daemon when a turn finishes" |
| 832 | .into(), |
| 833 | ), |
| 834 | "effect" if v.get("phase").is_some() => Err( |
| 835 | "ComposeNote: effect records with a \"phase\" are written only by the effect commands" |
| 836 | .into(), |
| 837 | ), |
| 838 | // sovereign-core #323: a phase-less `write_file` note spends its |
| 839 | // authorization (NEXT-PHASE-1 journals, still read). No caller writes |
| 840 | // a new one: it would block a live grant and void its revoke. |
| 841 | "effect" if v.get("tool").and_then(Value::as_str) == Some("write_file") => Err( |
| 842 | "ComposeNote: write_file effect records are written only by the effect commands (a NEXT-PHASE-1 spend note is never accepted from a caller)" |
| 843 | .into(), |
| 844 | ), |
| 845 | // sovereign-core #249: approved-submission replay records come only from |
| 846 | // crate::approved_replay. |
| 847 | "effect" if v.get(crate::approved_replay::FIELD).is_some() => Err( |
| 848 | "ComposeNote: approved_submission records are written only by the replay ledger".into(), |
| 849 | ), |
| 850 | // sovereign-core #261: the daemon's own compose-commit record. |
| 851 | "effect" if v.get(COMPOSE_COMMIT).is_some() => Err( |
| 852 | "ComposeNote: compose_commit records are written only by the compose run".into(), |
| 853 | ), |
| 854 | // ACCEPTANCE-v3 2.4: repair records come only from RecoverComposeHome. |
| 855 | "constraint" if v.get("repair").is_some() => Err( |
| 856 | "ComposeNote: constraint records with a \"repair\" field are written only by RecoverComposeHome" |
| 857 | .into(), |
| 858 | ), |
| 859 | _ => Ok(()), |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | /// Shape checks of `confine_target` (no filesystem walk below the workspace): |
| 864 | /// returns the plain components of `path`. |
| 865 | fn confine_shape<'a>( |
| 866 | workspace: &str, |
| 867 | path: &'a str, |
| 868 | target: &str, |
| 869 | ) -> Result<Vec<&'a std::ffi::OsStr>, Refusal> { |
| 870 | use std::path::Component; |
| 871 | let out = |w: String| Refusal::new("OutsideWorkspace", w); |
| 872 | let ws = Path::new(workspace); |
| 873 | let canon = |
| 874 | std::fs::canonicalize(ws).map_err(|e| out(format!("workspace {workspace}: {e}")))?; |
| 875 | if !ws.is_absolute() || canon != ws || !canon.is_dir() || canon == Path::new("/") { |
| 876 | return Err(out(format!( |
| 877 | "workspace {workspace} is not an absolute canonical directory other than /" |
| 878 | ))); |
| 879 | } |
| 880 | let rel = Path::new(path); |
| 881 | if path.is_empty() || !rel.components().all(|c| matches!(c, Component::Normal(_))) { |
| 882 | return Err(out(format!("path {path:?} is not a plain relative path"))); |
| 883 | } |
| 884 | let want = ws.join(rel); |
| 885 | if Path::new(target) != want { |
| 886 | return Err(out(format!( |
| 887 | "target {target} is not {} (workspace {workspace} + path {path})", |
| 888 | want.display() |
| 889 | ))); |
| 890 | } |
| 891 | Ok(rel |
| 892 | .components() |
| 893 | .filter_map(|c| match c { |
| 894 | Component::Normal(n) => Some(n), |
| 895 | _ => None, |
| 896 | }) |
| 897 | .collect()) |
| 898 | } |
| 899 | |
| 900 | /// An open handle on a confined target (sovereign-core #267): the file was |
| 901 | /// opened by one `openat2(RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)` call below a |
| 902 | /// held descriptor of the workspace root, and is read through that descriptor |
| 903 | /// only, never re-opened by path, so the check and the read name the same |
| 904 | /// object even if a path component is swapped afterwards. `file` is the |
| 905 | /// regular file, or None when it does not exist. |
| 906 | pub struct ConfinedTarget { |
| 907 | #[allow(dead_code)] // held so the chain stays open for the handle's life |
| 908 | dir: std::os::fd::OwnedFd, |
| 909 | pub file: Option<std::fs::File>, |
| 910 | target: String, |
| 911 | } |
| 912 | |
| 913 | impl ConfinedTarget { |
| 914 | /// sha256 of the bytes behind the held descriptor, None when absent. |
| 915 | pub fn sha256(&self) -> Result<Option<String>, String> { |
| 916 | use std::io::Read; |
| 917 | let Some(f) = &self.file else { |
| 918 | return Ok(None); |
| 919 | }; |
| 920 | let mut r = f; |
| 921 | let mut h = Sha256::new(); |
| 922 | let mut buf = [0u8; 64 * 1024]; |
| 923 | loop { |
| 924 | let n = r |
| 925 | .read(&mut buf) |
| 926 | .map_err(|e| format!("read {}: {e}", self.target))?; |
| 927 | if n == 0 { |
| 928 | break; |
| 929 | } |
| 930 | h.update(&buf[..n]); |
| 931 | } |
| 932 | Ok(Some(hex(&h.finalize()))) |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | /// Test seams (unit tests and, through the `test-support` feature, the |
| 937 | /// integration tests): a swap hook that fires inside the real call between |
| 938 | /// confinement and the read, one at the start of `open_confined`, and a switch |
| 939 | /// that forces the ENOSYS fallback walk. Never compiled into the daemon. |
| 940 | #[cfg(any(test, feature = "test-support"))] |
| 941 | pub mod test_hooks { |
| 942 | use std::cell::{Cell, RefCell}; |
| 943 | type Hook = RefCell<Option<Box<dyn FnOnce()>>>; |
| 944 | thread_local! { |
| 945 | static PAUSE: Hook = const { RefCell::new(None) }; |
| 946 | static BEFORE: Hook = const { RefCell::new(None) }; |
| 947 | static FALLBACK: Cell<bool> = const { Cell::new(false) }; |
| 948 | } |
| 949 | /// Run `f` once, right after confinement succeeded and before any read. |
| 950 | pub fn set_pause(f: impl FnOnce() + 'static) { |
| 951 | PAUSE.with(|p| *p.borrow_mut() = Some(Box::new(f))); |
| 952 | } |
| 953 | /// Run `f` once, at the start of `open_confined`, before any descriptor opens. |
| 954 | pub fn set_before(f: impl FnOnce() + 'static) { |
| 955 | BEFORE.with(|p| *p.borrow_mut() = Some(Box::new(f))); |
| 956 | } |
| 957 | /// Force the per-component fallback walk (as on a kernel without openat2). |
| 958 | pub fn set_force_fallback(on: bool) { |
| 959 | FALLBACK.with(|f| f.set(on)); |
| 960 | } |
| 961 | pub(super) fn run_pause() { |
| 962 | if let Some(f) = PAUSE.with(|p| p.borrow_mut().take()) { |
| 963 | f(); |
| 964 | } |
| 965 | } |
| 966 | pub(super) fn run_before() { |
| 967 | if let Some(f) = BEFORE.with(|p| p.borrow_mut().take()) { |
| 968 | f(); |
| 969 | } |
| 970 | } |
| 971 | pub(super) fn force_fallback() -> bool { |
| 972 | FALLBACK.with(|f| f.get()) |
| 973 | } |
| 974 | } |
| 975 | |
| 976 | /// `openat2(2)` syscall number: 437 on every architecture that has it. |
| 977 | const SYS_OPENAT2: libc::c_long = 437; |
| 978 | |
| 979 | /// `struct open_how` of openat2(2) (libc marks its own copy non-exhaustive). |
| 980 | #[repr(C)] |
| 981 | struct OpenHow { |
| 982 | flags: u64, |
| 983 | mode: u64, |
| 984 | resolve: u64, |
| 985 | } |
| 986 | |
| 987 | /// Open `rel` below the directory `dirfd`, resolved by the kernel in ONE |
| 988 | /// step with RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS: |
| 989 | /// no symlink anywhere in `rel` is followed and nothing can resolve above |
| 990 | /// `dirfd`. Falls back to a per-component `openat(O_NOFOLLOW)` walk only when |
| 991 | /// the kernel lacks openat2 (ENOSYS); that walk is weaker (a directory |
| 992 | /// renamed out of the workspace mid-walk is not caught). |
| 993 | fn open_beneath( |
| 994 | dirfd: libc::c_int, |
| 995 | rel: &Path, |
| 996 | flags: libc::c_int, |
| 997 | ) -> std::io::Result<std::os::fd::OwnedFd> { |
| 998 | use std::os::fd::FromRawFd; |
| 999 | use std::os::unix::ffi::OsStrExt; |
| 1000 | let c = std::ffi::CString::new(rel.as_os_str().as_bytes()) |
| 1001 | .map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))?; |
| 1002 | let how = OpenHow { |
| 1003 | flags: (flags | libc::O_CLOEXEC) as u64, |
| 1004 | mode: 0, |
| 1005 | resolve: libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS, |
| 1006 | }; |
| 1007 | #[cfg(any(test, feature = "test-support"))] |
| 1008 | let force_fallback = test_hooks::force_fallback(); |
| 1009 | #[cfg(not(any(test, feature = "test-support")))] |
| 1010 | let force_fallback = false; |
| 1011 | let fd = if force_fallback { |
| 1012 | -1 |
| 1013 | } else { |
| 1014 | // SAFETY: valid C string and a correctly sized open_how; a descriptor |
| 1015 | // returned (>= 0) is owned by nobody else and wrapped immediately. |
| 1016 | unsafe { |
| 1017 | libc::syscall( |
| 1018 | SYS_OPENAT2, |
| 1019 | dirfd, |
| 1020 | c.as_ptr(), |
| 1021 | &how as *const OpenHow, |
| 1022 | std::mem::size_of::<OpenHow>(), |
| 1023 | ) |
| 1024 | } |
| 1025 | }; |
| 1026 | if fd >= 0 { |
| 1027 | return Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as libc::c_int) }); |
| 1028 | } |
| 1029 | let err = if force_fallback { |
| 1030 | std::io::Error::from_raw_os_error(libc::ENOSYS) |
| 1031 | } else { |
| 1032 | std::io::Error::last_os_error() |
| 1033 | }; |
| 1034 | if err.raw_os_error() != Some(libc::ENOSYS) { |
| 1035 | return Err(err); |
| 1036 | } |
| 1037 | // Fallback: per-component openat with O_NOFOLLOW. |
| 1038 | let comps: Vec<_> = rel.components().collect(); |
| 1039 | let mut cur: Option<std::os::fd::OwnedFd> = None; |
| 1040 | for (i, comp) in comps.iter().enumerate() { |
| 1041 | let name = std::ffi::CString::new(comp.as_os_str().as_bytes()) |
| 1042 | .map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))?; |
| 1043 | let fl = if i + 1 == comps.len() { |
| 1044 | flags |
| 1045 | } else { |
| 1046 | libc::O_RDONLY | libc::O_DIRECTORY |
| 1047 | }; |
| 1048 | let base = cur.as_ref().map_or(dirfd, |f| f.as_raw_fd()); |
| 1049 | // SAFETY: as above. |
| 1050 | let fd = |
| 1051 | unsafe { libc::openat(base, name.as_ptr(), fl | libc::O_CLOEXEC | libc::O_NOFOLLOW) }; |
| 1052 | if fd < 0 { |
| 1053 | return Err(std::io::Error::last_os_error()); |
| 1054 | } |
| 1055 | cur = Some(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }); |
| 1056 | } |
| 1057 | cur.ok_or_else(|| std::io::Error::from_raw_os_error(libc::EINVAL)) |
| 1058 | } |
| 1059 | |
| 1060 | /// Open a confined target (see `ConfinedTarget`). Ancestors of the workspace |
| 1061 | /// root itself are trusted (checked canonical, opened `O_NOFOLLOW`); |
| 1062 | /// everything below it is resolved beneath that held descriptor. |
| 1063 | /// |
| 1064 | /// Refusal names. `OutsideWorkspace`: the shape checks, an escape, an |
| 1065 | /// intermediate symlink or non-directory. Three INTERNAL names let each caller |
| 1066 | /// keep the refusal it always gave (they never leave this module): |
| 1067 | /// `NotRegular` (the final component exists and is a symlink, directory or |
| 1068 | /// other non-file), `Unreadable` (the file exists but cannot be opened) and |
| 1069 | /// `MissingParent` (a directory above the target is absent). |
| 1070 | pub fn open_confined(workspace: &str, path: &str, target: &str) -> Result<ConfinedTarget, Refusal> { |
| 1071 | use std::os::fd::FromRawFd; |
| 1072 | let out = |w: String| Refusal::new("OutsideWorkspace", w); |
| 1073 | confine_shape(workspace, path, target)?; |
| 1074 | let root = std::ffi::CString::new(workspace) |
| 1075 | .map_err(|_| out(format!("workspace {workspace} holds a NUL")))?; |
| 1076 | // SAFETY: valid C string; result checked and wrapped immediately. |
| 1077 | let rfd = unsafe { |
| 1078 | libc::open( |
| 1079 | root.as_ptr(), |
| 1080 | libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW, |
| 1081 | ) |
| 1082 | }; |
| 1083 | if rfd < 0 { |
| 1084 | return Err(out(format!( |
| 1085 | "workspace {workspace}: {}", |
| 1086 | std::io::Error::last_os_error() |
| 1087 | ))); |
| 1088 | } |
| 1089 | // SAFETY: `rfd` is a fresh descriptor owned by nobody else. |
| 1090 | let dir = unsafe { std::os::fd::OwnedFd::from_raw_fd(rfd) }; |
| 1091 | #[cfg(any(test, feature = "test-support"))] |
| 1092 | test_hooks::run_before(); |
| 1093 | let rel = Path::new(path); |
| 1094 | let not_regular = || { |
| 1095 | Refusal::new( |
| 1096 | "NotRegular", |
| 1097 | format!("target {target} exists and is not a regular file (symlink or other)"), |
| 1098 | ) |
| 1099 | }; |
| 1100 | let dir_flags = libc::O_RDONLY | libc::O_DIRECTORY; |
| 1101 | let parent = rel.parent().filter(|p| !p.as_os_str().is_empty()); |
| 1102 | // O_NONBLOCK so opening a FIFO cannot hang; the type is checked on the fd. |
| 1103 | let file = match open_beneath(dir.as_raw_fd(), rel, libc::O_RDONLY | libc::O_NONBLOCK) { |
| 1104 | Ok(fd) => { |
| 1105 | let f = std::fs::File::from(fd); |
| 1106 | let m = f |
| 1107 | .metadata() |
| 1108 | .map_err(|e| Refusal::new("Unreadable", format!("read {target}: {e}")))?; |
| 1109 | if !m.file_type().is_file() { |
| 1110 | return Err(not_regular()); |
| 1111 | } |
| 1112 | Some(f) |
| 1113 | } |
| 1114 | // ELOOP: a symlink. In the last component it is a non-regular target; |
| 1115 | // in a directory component it is an escape route. |
| 1116 | Err(e) if e.raw_os_error() == Some(libc::ELOOP) => { |
| 1117 | let leaf = parent.is_none_or(|p| open_beneath(dir.as_raw_fd(), p, dir_flags).is_ok()); |
| 1118 | return Err(if leaf { |
| 1119 | not_regular() |
| 1120 | } else { |
| 1121 | out(format!( |
| 1122 | "target directory of {target} passes through a symlink" |
| 1123 | )) |
| 1124 | }); |
| 1125 | } |
| 1126 | // EXDEV: RESOLVE_BENEATH refused an escape. ENOTDIR: a component is not a directory. |
| 1127 | Err(e) if matches!(e.raw_os_error(), Some(libc::EXDEV | libc::ENOTDIR)) => { |
| 1128 | return Err(out(format!( |
| 1129 | "target directory of {target}: {e} (outside or not a directory)" |
| 1130 | ))) |
| 1131 | } |
| 1132 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 1133 | // Absent file is fine; an absent parent directory is not. |
| 1134 | if let Some(p) = parent { |
| 1135 | if let Err(pe) = open_beneath(dir.as_raw_fd(), p, dir_flags) { |
| 1136 | return Err(match pe.raw_os_error() { |
| 1137 | Some(libc::ENOENT) => Refusal::new( |
| 1138 | "MissingParent", |
| 1139 | format!("target directory of {target}: {pe} (missing)"), |
| 1140 | ), |
| 1141 | _ => out(format!( |
| 1142 | "target directory of {target}: {pe} (outside or a symlink)" |
| 1143 | )), |
| 1144 | }); |
| 1145 | } |
| 1146 | } |
| 1147 | None |
| 1148 | } |
| 1149 | Err(e) => return Err(Refusal::new("Unreadable", format!("read {target}: {e}"))), |
| 1150 | }; |
| 1151 | #[cfg(any(test, feature = "test-support"))] |
| 1152 | test_hooks::run_pause(); |
| 1153 | Ok(ConfinedTarget { |
| 1154 | dir, |
| 1155 | file, |
| 1156 | target: target.to_string(), |
| 1157 | }) |
| 1158 | } |
| 1159 | |
| 1160 | /// The refusal an outside caller sees: the internal names collapse to |
| 1161 | /// `OutsideWorkspace`, exactly what `confine_target` always returned for them. |
| 1162 | fn outside_of(r: Refusal) -> Refusal { |
| 1163 | match r.name { |
| 1164 | "NotRegular" | "MissingParent" | "Unreadable" => Refusal::new("OutsideWorkspace", r.detail), |
| 1165 | _ => r, |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | /// Workspace confinement of an effect target (sovereign-core #249): the |
| 1170 | /// workspace is an absolute, canonical directory that is not `/`; `path` is |
| 1171 | /// relative with plain components only; `target` is exactly |
| 1172 | /// `workspace/path`; every directory below the workspace is a real directory, |
| 1173 | /// not a symlink; and the target itself, when present, is a regular file, |
| 1174 | /// never a symlink. A file that exists but cannot be opened is still |
| 1175 | /// confined (its read fails later, as before). Where the bytes are then read, |
| 1176 | /// use `open_confined` and read through it (sovereign-core #267), so the |
| 1177 | /// check and the read cannot be split by a swap. |
| 1178 | pub fn confine_target(workspace: &str, path: &str, target: &str) -> Result<(), Refusal> { |
| 1179 | match open_confined(workspace, path, target) { |
| 1180 | Ok(_) => Ok(()), |
| 1181 | Err(r) => Err(outside_of(r)), |
| 1182 | } |
| 1183 | } |
| 1184 | |
| 1185 | /// `confine_target` and the sha256 of the target in one held walk. |
| 1186 | pub fn confined_sha256( |
| 1187 | workspace: &str, |
| 1188 | path: &str, |
| 1189 | target: &str, |
| 1190 | ) -> Result<Option<String>, String> { |
| 1191 | open_confined(workspace, path, target) |
| 1192 | .map_err(|r| outside_of(r).to_string())? |
| 1193 | .sha256() |
| 1194 | } |
| 1195 | |
| 1196 | /// An approved grant must be backed by its COMMITTED replay claim: same |
| 1197 | /// approval key, commit evidence naming the grant's proposal, promotion and |
| 1198 | /// evidence, and the record linking all three. |
| 1199 | fn check_approved_backing( |
| 1200 | l: &Ledger, |
| 1201 | g: &Grant, |
| 1202 | host: &[ComposeRecordView], |
| 1203 | ) -> Result<(), Refusal> { |
| 1204 | let Some(ag) = &g.approved else { |
| 1205 | return Ok(()); |
| 1206 | }; |
| 1207 | let a = &ag.link; |
| 1208 | let no = |w: &str| { |
| 1209 | Refusal::new( |
| 1210 | "NotAuthorized", |
| 1211 | format!( |
| 1212 | "approved grant #{} is not backed by a committed approved compose: {w}", |
| 1213 | g.id |
| 1214 | ), |
| 1215 | ) |
| 1216 | }; |
| 1217 | // One approval, one grant: a copy of the grant (same claim) opens nothing. |
| 1218 | if l.approved_by_claim.get(&a.replay_claim).map(Vec::len) != Some(1) { |
| 1219 | return Err(no("more than one approved grant names this replay claim")); |
| 1220 | } |
| 1221 | // The grant's fields are the bound approval: its identity hashes to the |
| 1222 | // claim's approval key (path, content, workspace and ids all covered), and |
| 1223 | // the target is the bound workspace plus path. |
| 1224 | let id = &ag.identity; |
| 1225 | let bound_target = Path::new(&id.workspace).join(&id.path); |
| 1226 | if crate::approved_auth::approval_key(id) != a.approval_key |
| 1227 | || g.target.as_deref().map(Path::new) != Some(bound_target.as_path()) |
| 1228 | || g.workspace.as_deref() != Some(id.workspace.as_str()) |
| 1229 | { |
| 1230 | return Err(no("grant fields are not the bound approval")); |
| 1231 | } |
| 1232 | let rl = |
| 1233 | crate::approved_replay::ReplayLedger::from_records(host).map_err(|r| no(&r.to_string()))?; |
| 1234 | let row = rl |
| 1235 | .claims |
| 1236 | .get(&a.replay_claim) |
| 1237 | .ok_or_else(|| no("no such replay claim"))?; |
| 1238 | let ev = row.evidence.as_ref(); |
| 1239 | if row.state != crate::approved_replay::ClaimState::Committed |
| 1240 | || row.keys.approval_key != a.approval_key |
| 1241 | || ( |
| 1242 | &row.keys.request_id, |
| 1243 | &row.keys.approval_id, |
| 1244 | &row.keys.trace_id, |
| 1245 | ) != (&id.request_id, &id.approval_id, &id.trace_id) |
| 1246 | || ev.map(|e| { |
| 1247 | ( |
| 1248 | e.compose_proposal_sha256.as_str(), |
| 1249 | e.cx_promotion, |
| 1250 | e.cx_evidence, |
| 1251 | ) |
| 1252 | }) != Some((g.proposal_sha256.as_str(), a.cx_promotion, a.cx_evidence)) |
| 1253 | || ![a.cx_promotion, a.cx_evidence, a.replay_claim] |
| 1254 | .iter() |
| 1255 | .all(|x| g.links.contains(x)) |
| 1256 | { |
| 1257 | return Err(no("claim state, key, evidence or links differ")); |
| 1258 | } |
| 1259 | Ok(()) |
| 1260 | } |
| 1261 | |
| 1262 | /// The grant the daemon writes after a COMMITTED approved compose (#249): |
| 1263 | /// reserved (`approved_grant`), confined to `workspace`, linked to the |
| 1264 | /// promotion, evidence and replay claim. Returns (record id, target). |
| 1265 | #[allow(clippy::too_many_arguments)] |
| 1266 | pub(crate) fn write_approved_grant( |
| 1267 | b: &ComposeBridge, |
| 1268 | workspace: &str, |
| 1269 | path: &str, |
| 1270 | content_sha256: &str, |
| 1271 | approver: &str, |
| 1272 | ids: &Value, |
| 1273 | link: &ApprovedLink, |
| 1274 | proposal_sha256: &str, |
| 1275 | base: Option<&str>, |
| 1276 | ) -> Result<(u64, String), String> { |
| 1277 | b.with_home(|home| { |
| 1278 | let target = Path::new(workspace).join(path).display().to_string(); |
| 1279 | // #267 follow-up: confine and hash through one held handle. |
| 1280 | let prior = confined_sha256(workspace, path, &target)?; |
| 1281 | // The file must still be the one the bound requirements were checked against. |
| 1282 | if let Some(base) = base { |
| 1283 | let now = prior.as_deref().unwrap_or("absent"); |
| 1284 | if now != base { |
| 1285 | return Err(format!( |
| 1286 | "BaseChanged: {path} changed after the requirements were checked (bound {base}, now {now}); no grant was written" |
| 1287 | )); |
| 1288 | } |
| 1289 | } |
| 1290 | let mut text = json!({ |
| 1291 | APPROVED_GRANT: 1, "proposal_sha256": proposal_sha256, "path": path, |
| 1292 | "content_sha256": content_sha256, "approver": approver, "target": target, |
| 1293 | "workspace": workspace, "prior_sha256": prior, |
| 1294 | "approval_key": link.approval_key, "replay_claim": link.replay_claim, |
| 1295 | "cx_promotion": link.cx_promotion, "cx_evidence": link.cx_evidence, |
| 1296 | // An approved proposal runs no model: no generation record, the ALLEN only. |
| 1297 | crate::generation::PROVENANCE: |
| 1298 | crate::generation::Provenance::new(None, home.allen.as_ref()).to_json(), |
| 1299 | }); |
| 1300 | if let (Some(t), Some(i)) = (text.as_object_mut(), ids.as_object()) { |
| 1301 | for (k, v) in i { |
| 1302 | t.entry(k.clone()).or_insert(v.clone()); |
| 1303 | } |
| 1304 | } |
| 1305 | let n = append( |
| 1306 | home, |
| 1307 | NoteKind::Authorization, |
| 1308 | &[link.cx_promotion, link.cx_evidence, link.replay_claim], |
| 1309 | &text, |
| 1310 | )?; |
| 1311 | Ok((n.id, target)) |
| 1312 | }) |
| 1313 | } |
| 1314 | |
| 1315 | /// A minted grant must be backed by the compose-commit record the daemon |
| 1316 | /// wrote when its own compose run committed this proposal (#261): same |
| 1317 | /// proposal, path, content and workspace, target = workspace + path, and the |
| 1318 | /// grant links the record. |
| 1319 | fn check_minted_backing(l: &Ledger, g: &Grant) -> Result<(), Refusal> { |
| 1320 | let Some(m) = &g.minted else { |
| 1321 | return Ok(()); |
| 1322 | }; |
| 1323 | let no = |w: &str| { |
| 1324 | Refusal::new( |
| 1325 | "NotAuthorized", |
| 1326 | format!( |
| 1327 | "minted grant #{} is not backed by a committed compose: {w}", |
| 1328 | g.id |
| 1329 | ), |
| 1330 | ) |
| 1331 | }; |
| 1332 | let c = l |
| 1333 | .commits |
| 1334 | .get(&m.commit) |
| 1335 | .ok_or_else(|| no("no such compose-commit record"))?; |
| 1336 | let bound_target = Path::new(&c.workspace).join(&c.path); |
| 1337 | if c.proposal_sha256 != g.proposal_sha256 |
| 1338 | || c.path != g.path |
| 1339 | || c.content_sha256 != g.content_sha256 |
| 1340 | || g.workspace.as_deref() != Some(c.workspace.as_str()) |
| 1341 | || g.target.as_deref().map(Path::new) != Some(bound_target.as_path()) |
| 1342 | || !g.links.contains(&m.commit) |
| 1343 | { |
| 1344 | return Err(no("grant fields differ from the committed proposal")); |
| 1345 | } |
| 1346 | Ok(()) |
| 1347 | } |
| 1348 | |
| 1349 | /// Copy the provenance evidence of record `source` onto `text`, a record the |
| 1350 | /// daemon is about to append. EVIDENCE ONLY: this is the single place the |
| 1351 | /// ledger-side code reads provenance, it never fails and is called after every |
| 1352 | /// decision of its caller (`provenance_changes_no_decision` scans for that). |
| 1353 | fn stamp(text: &mut Value, views: &[ComposeRecordView], source: u64) { |
| 1354 | text[crate::generation::PROVENANCE] = crate::generation::inherit(views, source).to_json(); |
| 1355 | } |
| 1356 | |
| 1357 | /// The record the daemon writes when its own compose run COMMITTED a |
| 1358 | /// one-file proposal (#261): the only thing `ComposeAuthorize` mints from. |
| 1359 | /// Linked to the promotion and evidence. Returns the record id. |
| 1360 | #[allow(clippy::too_many_arguments)] |
| 1361 | pub(crate) fn write_compose_commit( |
| 1362 | home: &mut ComposeHome, |
| 1363 | workspace: &str, |
| 1364 | task: u64, |
| 1365 | cx_promotion: u64, |
| 1366 | cx_evidence: u64, |
| 1367 | proposal_sha256: &str, |
| 1368 | path: &str, |
| 1369 | content_sha256: &str, |
| 1370 | goal_sha256: Option<&str>, |
| 1371 | prov: &crate::generation::Provenance, |
| 1372 | ) -> Result<u64, String> { |
| 1373 | // Refused at write time: a record never names a generation id that is not |
| 1374 | // a verified generation record of this ledger. |
| 1375 | if let Some(g) = prov.generation_record { |
| 1376 | if !crate::generation::generation_exists(&host_views(home)?, g) { |
| 1377 | return Err(format!( |
| 1378 | "compose-commit not written: provenance names generation record #{g}, which is not a verified generation record" |
| 1379 | )); |
| 1380 | } |
| 1381 | } |
| 1382 | let mut text = json!({ |
| 1383 | COMPOSE_COMMIT: 1, "task": task, "cx_promotion": cx_promotion, |
| 1384 | "cx_evidence": cx_evidence, "proposal_sha256": proposal_sha256, |
| 1385 | "path": path, "content_sha256": content_sha256, "workspace": workspace, |
| 1386 | crate::generation::PROVENANCE: prov.to_json(), |
| 1387 | }); |
| 1388 | // #408: the goal digest, so a grant can be bound to the objective record |
| 1389 | // whose text this compose ran for. |
| 1390 | if let Some(g) = goal_sha256 { |
| 1391 | text["goal_sha256"] = json!(g); |
| 1392 | } |
| 1393 | append(home, NoteKind::Effect, &[cx_promotion, cx_evidence], &text).map(|n| n.id) |
| 1394 | } |
| 1395 | |
| 1396 | /// What `ComposeAuthorize` asks for: the operator's approval of one committed |
| 1397 | /// proposal. Only ids and digests; path, content and target come from the |
| 1398 | /// daemon's own commit record, never from the caller. |
| 1399 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1400 | pub struct MintRequest { |
| 1401 | pub cx_promotion: u64, |
| 1402 | pub proposal_sha256: String, |
| 1403 | pub workspace: String, |
| 1404 | pub approver: String, |
| 1405 | /// Constraint records the grant links (at most 3). |
| 1406 | pub constraints: Vec<u64>, |
| 1407 | } |
| 1408 | |
| 1409 | /// ComposeAuthorize (#261): mint the one grant for a proposal this daemon |
| 1410 | /// committed. Refused when no commit record names (promotion, proposal), the |
| 1411 | /// workspace differs from the one the compose ran for, the target escapes it |
| 1412 | /// (`confine_target`), or an earlier grant for the same commit is still live |
| 1413 | /// or has an unsettled intent. A revoked, stale or NOT_DONE grant does not block a new one (each grant |
| 1414 | /// is spent exactly once); a grant that settled DONE does: one committed |
| 1415 | /// proposal gives at most one DONE effect. |
| 1416 | pub fn mint_grant(b: &ComposeBridge, req: &MintRequest) -> ControlResponse { |
| 1417 | authorize(b, req, None) |
| 1418 | } |
| 1419 | |
| 1420 | /// `ComposeAuthorize` with the optional approval-desk proof (#297). When the |
| 1421 | /// bridge runs with the desk switch ON, a missing or wrong proof, a missing |
| 1422 | /// desk key, a MAC over other fields, or a reused nonce is refused and |
| 1423 | /// NOTHING is written. With the switch OFF the proof is ignored (legacy |
| 1424 | /// behaviour: OS-user authentication only). |
| 1425 | /// The refusal name out of a `Refusal` display string, or "error" for any |
| 1426 | /// other error text. Used only for trace notes (#398); never for decisions. |
| 1427 | fn refusal_name(e: &str) -> &str { |
| 1428 | e.strip_prefix("EFFECT_REFUSED ") |
| 1429 | .and_then(|rest| rest.split(':').next()) |
| 1430 | .map(str::trim) |
| 1431 | .filter(|n| !n.is_empty()) |
| 1432 | .unwrap_or("error") |
| 1433 | } |
| 1434 | |
| 1435 | /// Emits one correlation event for a control response (#398): `Ok` with the |
| 1436 | /// note's record id in `id_slot`, `Rejected` with the refusal name for a |
| 1437 | /// refusal, `Failed` for any other error. Observational only. |
| 1438 | fn trace_response( |
| 1439 | b: &ComposeBridge, |
| 1440 | kind: aien_trace::EventKind, |
| 1441 | r: &ControlResponse, |
| 1442 | mut ids: aien_trace::CorrelationIds, |
| 1443 | id_slot: fn(&mut aien_trace::CorrelationIds, u64), |
| 1444 | certainty_ok: Option<aien_trace::EffectCertainty>, |
| 1445 | ) { |
| 1446 | use aien_trace::EventStatus; |
| 1447 | let (status, certainty, note) = match r { |
| 1448 | ControlResponse::ComposeNoted(n) => { |
| 1449 | id_slot(&mut ids, n.id); |
| 1450 | (EventStatus::Ok, certainty_ok, "") |
| 1451 | } |
| 1452 | ControlResponse::Error(e) if e.starts_with("EFFECT_REFUSED ") => ( |
| 1453 | EventStatus::Rejected, |
| 1454 | Some(aien_trace::EffectCertainty::NoEffect), |
| 1455 | refusal_name(e), |
| 1456 | ), |
| 1457 | ControlResponse::Error(_) => (EventStatus::Failed, None, "error"), |
| 1458 | _ => (EventStatus::Malformed, None, "unexpected_response"), |
| 1459 | }; |
| 1460 | b.trace_event( |
| 1461 | kind, |
| 1462 | status, |
| 1463 | certainty, |
| 1464 | ids, |
| 1465 | aien_trace::EvidenceRefs::default(), |
| 1466 | note, |
| 1467 | ); |
| 1468 | } |
| 1469 | |
| 1470 | pub fn authorize( |
| 1471 | b: &ComposeBridge, |
| 1472 | req: &MintRequest, |
| 1473 | proof: Option<&crate::control::DeskProof>, |
| 1474 | ) -> ControlResponse { |
| 1475 | authorize_with_objective(b, req, proof, None) |
| 1476 | } |
| 1477 | |
| 1478 | /// sovereign-core #408: [`authorize`] for an approval that names the objective |
| 1479 | /// record it is for. The daemon re-reads the record (crate::objective); its |
| 1480 | /// text must be the goal this daemon composed for (`goal_sha256` of the |
| 1481 | /// commit record). The grant then carries the objective id and both digests. |
| 1482 | /// A missing or different record is refused by name and nothing is written. |
| 1483 | /// `None` mints exactly as [`authorize`] always did. |
| 1484 | pub fn authorize_with_objective( |
| 1485 | b: &ComposeBridge, |
| 1486 | req: &MintRequest, |
| 1487 | proof: Option<&crate::control::DeskProof>, |
| 1488 | objective_id: Option<&str>, |
| 1489 | ) -> ControlResponse { |
| 1490 | let r = authorize_inner(b, req, proof, objective_id); |
| 1491 | if b.trace_enabled() { |
| 1492 | trace_response( |
| 1493 | b, |
| 1494 | aien_trace::EventKind::AuthorityDecided, |
| 1495 | &r, |
| 1496 | aien_trace::CorrelationIds { |
| 1497 | decision_id: Some(aien_trace::BoundedId::new(&req.cx_promotion.to_string())), |
| 1498 | ..Default::default() |
| 1499 | }, |
| 1500 | |ids, id| ids.grant_id = Some(aien_trace::BoundedId::new(&id.to_string())), |
| 1501 | Some(aien_trace::EffectCertainty::NoEffect), |
| 1502 | ); |
| 1503 | } |
| 1504 | r |
| 1505 | } |
| 1506 | |
| 1507 | fn authorize_inner( |
| 1508 | b: &ComposeBridge, |
| 1509 | req: &MintRequest, |
| 1510 | proof: Option<&crate::control::DeskProof>, |
| 1511 | objective_id: Option<&str>, |
| 1512 | ) -> ControlResponse { |
| 1513 | if let Err(e) = reconcile_gate(b) { |
| 1514 | return ControlResponse::Error(e); |
| 1515 | } |
| 1516 | noted(b.with_home(|home| { |
| 1517 | let no = |name: &'static str, why: String| Refusal::new(name, why).to_string(); |
| 1518 | if req.approver.trim().is_empty() { |
| 1519 | return Err(no("NotAuthorized", "ComposeAuthorize needs an approver".into())); |
| 1520 | } |
| 1521 | if req.constraints.len() > 3 { |
| 1522 | return Err(no("NotAuthorized", "at most 3 constraint links".into())); |
| 1523 | } |
| 1524 | let desk = if b.authorize_requires_desk() { |
| 1525 | let Some(p) = proof else { |
| 1526 | return Err(no( |
| 1527 | "DeskMacRequired", |
| 1528 | "this daemon requires the approval desk MAC on ComposeAuthorize (AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=1); none was supplied".into(), |
| 1529 | )); |
| 1530 | }; |
| 1531 | if p.nonce.is_empty() |
| 1532 | || p.nonce.len() > 128 |
| 1533 | || !p.nonce.bytes().all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c)) |
| 1534 | { |
| 1535 | return Err(no("DeskMacInvalid", "nonce must be 1 to 128 of [A-Za-z0-9._-]".into())); |
| 1536 | } |
| 1537 | let key = crate::approved_auth::DeskKey::load(&crate::approved_auth::desk_key_path(b.dir())) |
| 1538 | .map_err(|e| no("NoDesk", e))?; |
| 1539 | Some((key, p)) |
| 1540 | } else { |
| 1541 | None |
| 1542 | }; |
| 1543 | let views = host_views(home)?; |
| 1544 | let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; |
| 1545 | let mut hits = l |
| 1546 | .commits |
| 1547 | .values() |
| 1548 | .filter(|c| c.cx_promotion == req.cx_promotion && c.proposal_sha256 == req.proposal_sha256); |
| 1549 | let (Some(c), None) = (hits.next(), hits.next()) else { |
| 1550 | return Err(no( |
| 1551 | "NotAuthorized", |
| 1552 | format!( |
| 1553 | "no compose-commit record names promotion #{} and this proposal: only a proposal this daemon committed (aien compose propose) can be authorized", |
| 1554 | req.cx_promotion |
| 1555 | ), |
| 1556 | )); |
| 1557 | }; |
| 1558 | let ws = std::fs::canonicalize(&req.workspace) |
| 1559 | .map_err(|e| no("OutsideWorkspace", format!("workspace {}: {e}", req.workspace)))? |
| 1560 | .display() |
| 1561 | .to_string(); |
| 1562 | if ws != c.workspace { |
| 1563 | return Err(no( |
| 1564 | "OutsideWorkspace", |
| 1565 | format!("the proposal was committed for workspace {}, not {ws}", c.workspace), |
| 1566 | )); |
| 1567 | } |
| 1568 | let target = Path::new(&c.workspace).join(&c.path).display().to_string(); |
| 1569 | // #267 follow-up: keep the confined handle; the prior hash below is |
| 1570 | // read from it, not re-resolved by path after the MAC checks. |
| 1571 | let held = open_confined(&c.workspace, &c.path, &target) |
| 1572 | .map_err(|r| outside_of(r).to_string())?; |
| 1573 | if let Some((key, p)) = &desk { |
| 1574 | // Path, content and workspace are the daemon's own commit record; |
| 1575 | // the MAC must cover exactly those. |
| 1576 | let binding = crate::approved_auth::AuthorizeBinding { |
| 1577 | cx_promotion: c.cx_promotion, |
| 1578 | proposal_sha256: c.proposal_sha256.clone(), |
| 1579 | path: c.path.clone(), |
| 1580 | content_sha256: c.content_sha256.clone(), |
| 1581 | workspace: c.workspace.clone(), |
| 1582 | approver: req.approver.trim().to_string(), |
| 1583 | constraints: req.constraints.clone(), |
| 1584 | nonce: p.nonce.clone(), |
| 1585 | desk_key_id: key.id().to_string(), |
| 1586 | }; |
| 1587 | key.verify_authorize(&binding, &p.mac) |
| 1588 | .map_err(|e| no("DeskMacInvalid", e))?; |
| 1589 | if l.desk_nonces.contains(&p.nonce) { |
| 1590 | return Err(no( |
| 1591 | "Replayed", |
| 1592 | format!("authorize nonce {} already minted a grant; a replayed authorize mints nothing", p.nonce), |
| 1593 | )); |
| 1594 | } |
| 1595 | } |
| 1596 | let prior = held.sha256()?; |
| 1597 | for &gid in l.minted_by_commit.get(&c.id).into_iter().flatten() { |
| 1598 | let g = &l.grants[&gid]; |
| 1599 | // The spent intent is judged FIRST: a revoke or a stop after the grant |
| 1600 | // never undoes a DONE effect, nor settles an intent that may still |
| 1601 | // land. Only an unspent revoked or stopped grant gives way. |
| 1602 | let dead = l.revoked.contains_key(&gid) || l.stops.iter().any(|&s| s > gid); |
| 1603 | match l.spent.get(&gid).map(|i| &l.intents[i]) { |
| 1604 | None if dead => continue, |
| 1605 | // Settled: the grant is spent for good (a new effect needs a |
| 1606 | // new grant, as before). |
| 1607 | Some(row) if row.state == EffectState::Done => { |
| 1608 | return Err(no( |
| 1609 | "AlreadySpent", |
| 1610 | format!( |
| 1611 | "grant #{gid} for this proposal settled DONE (intent #{}); one committed proposal gives at most one effect, new content needs a new compose", |
| 1612 | row.id |
| 1613 | ), |
| 1614 | )) |
| 1615 | } |
| 1616 | Some(row) if row.state.terminal() => continue, |
| 1617 | Some(row) => { |
| 1618 | return Err(no( |
| 1619 | "ReconciliationRequired", |
| 1620 | format!( |
| 1621 | "intent #{} for grant #{gid} is {}; run aien compose reconcile", |
| 1622 | row.id, |
| 1623 | row.state.name() |
| 1624 | ), |
| 1625 | )) |
| 1626 | } |
| 1627 | None if g.prior_sha256.as_ref() != Some(&prior) => continue, // stale |
| 1628 | None => { |
| 1629 | return Err(no( |
| 1630 | "AlreadyAuthorized", |
| 1631 | format!("grant #{gid} for this proposal is still live; revoke it first"), |
| 1632 | )) |
| 1633 | } |
| 1634 | } |
| 1635 | } |
| 1636 | // #408: judged after every older refusal, so those keep their order. |
| 1637 | let objective = match objective_id { |
| 1638 | None => None, |
| 1639 | Some(oid) => { |
| 1640 | let Some(goal) = c.goal_sha256.as_deref() else { |
| 1641 | return Err(no( |
| 1642 | crate::objective::MISMATCH, |
| 1643 | format!( |
| 1644 | "compose-commit #{} names no goal digest (written before sovereign-core #408); objective {oid} cannot be bound to it", |
| 1645 | c.id |
| 1646 | ), |
| 1647 | )); |
| 1648 | }; |
| 1649 | Some(crate::objective::check(oid, goal).map_err(|(n, d)| no(n, d))?) |
| 1650 | } |
| 1651 | }; |
| 1652 | let mut links = vec![c.id]; |
| 1653 | links.extend(&req.constraints); |
| 1654 | let mut text = json!({ |
| 1655 | MINTED_GRANT: 1, "compose_commit": c.id, "proposal_sha256": c.proposal_sha256, |
| 1656 | "path": c.path, "content_sha256": c.content_sha256, |
| 1657 | "approver": req.approver.trim(), "target": target, "workspace": c.workspace, |
| 1658 | "prior_sha256": prior, "cx_promotion": c.cx_promotion, "cx_evidence": c.cx_evidence, |
| 1659 | }); |
| 1660 | if let Some((key, p)) = &desk { |
| 1661 | text["desk_nonce"] = json!(p.nonce); |
| 1662 | text["desk_key_id"] = json!(key.id()); |
| 1663 | } |
| 1664 | if let Some(o) = &objective { |
| 1665 | text["objective_id"] = json!(o.objective_id); |
| 1666 | text["objective_text_sha256"] = json!(o.text_sha256); |
| 1667 | text["objective_record_sha256"] = json!(o.record_sha256); |
| 1668 | } |
| 1669 | stamp(&mut text, &views, c.id); |
| 1670 | append(home, NoteKind::Authorization, &links, &text) |
| 1671 | })) |
| 1672 | } |
| 1673 | |
| 1674 | fn host_views(home: &mut ComposeHome) -> Result<Vec<ComposeRecordView>, String> { |
| 1675 | let (recs, total) = home |
| 1676 | .compose |
| 1677 | .recall(aien_omega_compose::SUBJECT_HOST, HOST_RECALL_MAX) |
| 1678 | .map_err(|e| format!("effect ledger: host records: {e}"))?; |
| 1679 | if total > recs.len() as u64 { |
| 1680 | return Err(format!( |
| 1681 | "{}", |
| 1682 | Refusal::new( |
| 1683 | "CorruptLedger", |
| 1684 | format!("{total} host records exceed the ledger's {HOST_RECALL_MAX}") |
| 1685 | ) |
| 1686 | )); |
| 1687 | } |
| 1688 | Ok(recs |
| 1689 | .iter() |
| 1690 | .map(|r| record_view(&mut home.compose, r)) |
| 1691 | .collect()) |
| 1692 | } |
| 1693 | |
| 1694 | fn ledger(home: &mut ComposeHome) -> Result<Ledger, String> { |
| 1695 | Ledger::from_records(&host_views(home)?).map_err(|r| r.to_string()) |
| 1696 | } |
| 1697 | |
| 1698 | pub(crate) fn append( |
| 1699 | home: &mut ComposeHome, |
| 1700 | kind: NoteKind, |
| 1701 | links: &[u64], |
| 1702 | text: &Value, |
| 1703 | ) -> Result<ComposeNoteReport, String> { |
| 1704 | let text = text.to_string(); |
| 1705 | let mut l = [0u64; 4]; |
| 1706 | for (slot, &x) in l.iter_mut().zip(links.iter().filter(|&&x| x != 0)) { |
| 1707 | *slot = x; |
| 1708 | } |
| 1709 | let id = home |
| 1710 | .compose |
| 1711 | .note(kind, l, text.as_bytes()) |
| 1712 | .map_err(|e| format!("effect record: {e}"))?; |
| 1713 | let rec = home |
| 1714 | .compose |
| 1715 | .record(id) |
| 1716 | .map_err(|e| format!("effect record: re-read {id}: {e}"))?; |
| 1717 | Ok(ComposeNoteReport { |
| 1718 | machine_id: home.machine_id.clone(), |
| 1719 | id, |
| 1720 | kind: kind.name().to_string(), |
| 1721 | digest: hex(&rec.digest), |
| 1722 | text_sha256: hex(&Sha256::digest(text.as_bytes())), |
| 1723 | links: l.iter().copied().filter(|&x| x != 0).collect(), |
| 1724 | }) |
| 1725 | } |
| 1726 | |
| 1727 | fn noted(r: Result<ComposeNoteReport, String>) -> ControlResponse { |
| 1728 | match r { |
| 1729 | Ok(n) => ControlResponse::ComposeNoted(n), |
| 1730 | Err(e) => ControlResponse::Error(e), |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | /// What `open_intent` learned about the target before the grant checks. |
| 1735 | enum IntentRead { |
| 1736 | /// The hash of the target (None when absent), read through the handle |
| 1737 | /// confinement opened. |
| 1738 | Prior(Option<String>), |
| 1739 | /// The target cannot be read as a regular file (a directory, a leaf |
| 1740 | /// symlink, no permission). Refused at once as "Stale", exactly where the |
| 1741 | /// old by-path read refused it, before the grant is looked at. |
| 1742 | Stale(String), |
| 1743 | /// A directory above the target is absent: the old read saw "absent"; so |
| 1744 | /// does the grant check, then the confinement refusal follows. |
| 1745 | MissingParent(String), |
| 1746 | /// The path escapes the workspace (symlinked or non-directory component, |
| 1747 | /// bad shape). Nothing outside is read; the grant checks run with the |
| 1748 | /// grant's own prior standing in, then this refusal follows. |
| 1749 | Outside(String), |
| 1750 | } |
| 1751 | |
| 1752 | /// The prior hash an intent records (#267 follow-up): when the grant names a |
| 1753 | /// workspace, the target is confined and hashed through one held handle |
| 1754 | /// BEFORE any other check, so what is compared with the grant is what |
| 1755 | /// confinement checked. A grant with no workspace keeps the by-path read (it |
| 1756 | /// is refused right after: it names no workspace). |
| 1757 | fn intent_prior(l: &Ledger, req: &IntentRequest) -> IntentRead { |
| 1758 | let stale = |e: String| { |
| 1759 | IntentRead::Stale(Refusal::new("Stale", format!("target unreadable: {e}")).to_string()) |
| 1760 | }; |
| 1761 | let ws = l |
| 1762 | .grants |
| 1763 | .get(&req.authorization) |
| 1764 | .and_then(|g| g.workspace.as_deref()); |
| 1765 | let Some(ws) = ws else { |
| 1766 | return match file_sha256(Path::new(&req.target)) { |
| 1767 | Ok(p) => IntentRead::Prior(p), |
| 1768 | Err(e) => stale(e), |
| 1769 | }; |
| 1770 | }; |
| 1771 | match open_confined(ws, &req.path, &req.target) { |
| 1772 | Ok(t) => match t.sha256() { |
| 1773 | Ok(p) => IntentRead::Prior(p), |
| 1774 | Err(e) => stale(e), |
| 1775 | }, |
| 1776 | Err(r) => match r.name { |
| 1777 | "NotRegular" | "Unreadable" => stale(r.detail), |
| 1778 | "MissingParent" => IntentRead::MissingParent(outside_of(r).to_string()), |
| 1779 | _ => IntentRead::Outside(r.to_string()), |
| 1780 | }, |
| 1781 | } |
| 1782 | } |
| 1783 | |
| 1784 | /// ComposeEffectIntent: every check of 2.3 and the durable intent, in one |
| 1785 | /// step under the home lock. The answer's id is the intent. |
| 1786 | pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { |
| 1787 | let r = open_intent_inner(b, req); |
| 1788 | if b.trace_enabled() { |
| 1789 | trace_response( |
| 1790 | b, |
| 1791 | aien_trace::EventKind::ToolRequested, |
| 1792 | &r, |
| 1793 | aien_trace::CorrelationIds { |
| 1794 | grant_id: Some(aien_trace::BoundedId::new(&req.authorization.to_string())), |
| 1795 | ..Default::default() |
| 1796 | }, |
| 1797 | |ids, id| ids.tool_request_id = Some(aien_trace::BoundedId::new(&id.to_string())), |
| 1798 | Some(aien_trace::EffectCertainty::NoEffect), |
| 1799 | ); |
| 1800 | } |
| 1801 | r |
| 1802 | } |
| 1803 | |
| 1804 | fn open_intent_inner(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { |
| 1805 | if let Err(e) = reconcile_gate(b) { |
| 1806 | return ControlResponse::Error(e); |
| 1807 | } |
| 1808 | noted(b.with_home(|home| { |
| 1809 | let views = host_views(home)?; |
| 1810 | let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; |
| 1811 | // Refusal order is the one callers always saw: an unreadable target is |
| 1812 | // "Stale" first; then the grant checks; then confinement. A confinement |
| 1813 | // refusal found while reading is held back until the grant checks ran. |
| 1814 | let (current, deferred) = match intent_prior(&l, req) { |
| 1815 | IntentRead::Prior(p) => (p, None), |
| 1816 | IntentRead::Stale(e) => return Err(e), |
| 1817 | IntentRead::MissingParent(e) => (None, Some(e)), |
| 1818 | IntentRead::Outside(e) => ( |
| 1819 | l.grants |
| 1820 | .get(&req.authorization) |
| 1821 | .and_then(|g| g.prior_sha256.clone().flatten()), |
| 1822 | Some(e), |
| 1823 | ), |
| 1824 | }; |
| 1825 | let g = l.check_intent(req, ¤t).map_err(|r| r.to_string())?; |
| 1826 | // sovereign-core #249: a grant names its workspace; confinement (already |
| 1827 | // done above, through the handle that was read); an approved grant's backing. |
| 1828 | if g.workspace.is_none() { |
| 1829 | return Err(Refusal::new( |
| 1830 | "NotAuthorized", |
| 1831 | format!("authorization #{} names no workspace", g.id), |
| 1832 | ) |
| 1833 | .to_string()); |
| 1834 | } |
| 1835 | if let Some(e) = deferred { |
| 1836 | return Err(e); |
| 1837 | } |
| 1838 | check_approved_backing(&l, g, &views).map_err(|r| r.to_string())?; |
| 1839 | check_minted_backing(&l, g).map_err(|r| r.to_string())?; |
| 1840 | // #408: an objective-bound grant opens an intent only while its record |
| 1841 | // still holds the approved text (re-read now, after any restart). |
| 1842 | if let Some(o) = &g.objective { |
| 1843 | crate::objective::check(&o.id, &o.text_sha256).map_err(|(n, d)| { |
| 1844 | Refusal::new( |
| 1845 | n, |
| 1846 | format!( |
| 1847 | "authorization #{} is bound to objective {}: {d}", |
| 1848 | g.id, o.id |
| 1849 | ), |
| 1850 | ) |
| 1851 | .to_string() |
| 1852 | })?; |
| 1853 | } |
| 1854 | let mut text = json!({ |
| 1855 | "phase": PHASE_INTENT, "tool": "write_file", "authorization": g.id, |
| 1856 | "proposal_sha256": req.proposal_sha256, "path": req.path, "target": req.target, |
| 1857 | "content_sha256": req.content_sha256, "prior_sha256": current, |
| 1858 | "executor": {"pid": req.executor_pid, "start": req.executor_start}, |
| 1859 | }); |
| 1860 | if let Some(o) = &g.objective { |
| 1861 | text["objective_id"] = json!(o.id); |
| 1862 | text["objective_text_sha256"] = json!(o.text_sha256); |
| 1863 | } |
| 1864 | stamp(&mut text, &views, g.id); |
| 1865 | append(home, NoteKind::Effect, &[g.id], &text) |
| 1866 | })) |
| 1867 | } |
| 1868 | |
| 1869 | /// ComposeEffectAck: the executor's report after the write. The state is |
| 1870 | /// read from the world; the executor's own claim is kept beside it. |
| 1871 | pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse { |
| 1872 | if let Err(e) = reconcile_gate(b) { |
| 1873 | return ControlResponse::Error(e); |
| 1874 | } |
| 1875 | // The settled state, for the trace event only (#398). |
| 1876 | let mut settled: Option<String> = None; |
| 1877 | let mut grant: Option<u64> = None; |
| 1878 | let r = noted(b.with_home(|home| { |
| 1879 | let views = host_views(home)?; |
| 1880 | let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; |
| 1881 | let row = l |
| 1882 | .intents |
| 1883 | .get(&intent) |
| 1884 | .ok_or_else(|| format!("ComposeEffectAck: #{intent} is not an effect intent"))?; |
| 1885 | if row.state.terminal() { |
| 1886 | return Err(format!( |
| 1887 | "ComposeEffectAck: intent #{intent} is already {} (record #{})", |
| 1888 | row.state.name(), |
| 1889 | row.state_record |
| 1890 | )); |
| 1891 | } |
| 1892 | let (st, disk) = confined_world_state(&l, row); |
| 1893 | settled = Some(st.name().to_string()); |
| 1894 | grant = Some(row.authorization); |
| 1895 | let mut text = json!({ |
| 1896 | "phase": PHASE_ACK, "intent": intent, "authorization": row.authorization, |
| 1897 | "tool": "write_file", "path": row.path, "content_sha256": row.content_sha256, |
| 1898 | "state": st.name(), "disk_sha256": disk.as_ref().ok().cloned().flatten(), |
| 1899 | "disk_error": disk.as_ref().err(), "executor_reported": reported, |
| 1900 | }); |
| 1901 | if let Some(o) = &row.objective_id { |
| 1902 | text["objective_id"] = json!(o); |
| 1903 | } |
| 1904 | stamp(&mut text, &views, intent); |
| 1905 | append(home, NoteKind::Effect, &[intent, row.authorization], &text) |
| 1906 | })); |
| 1907 | // Correlation only (#398): the settled state of this intent as the ledger |
| 1908 | // judged it. DONE is the only `effect_occurred`; NOT_DONE is `no_effect`; |
| 1909 | // UNRESOLVED stays `uncertain` and nothing reading a trace may retry it. |
| 1910 | if b.trace_enabled() { |
| 1911 | use aien_trace::{EffectCertainty, EventStatus}; |
| 1912 | let (status, certainty, note) = match (&r, settled.as_deref()) { |
| 1913 | (ControlResponse::ComposeNoted(_), Some("DONE")) => ( |
| 1914 | EventStatus::Ok, |
| 1915 | Some(EffectCertainty::EffectOccurred), |
| 1916 | "DONE", |
| 1917 | ), |
| 1918 | // NOT_DONE: the world check says the effect did not happen, so it is a |
| 1919 | // definite no-effect outcome (C2 `rejected`), not `failed` (ran and |
| 1920 | // errored). |
| 1921 | (ControlResponse::ComposeNoted(_), Some("NOT_DONE")) => ( |
| 1922 | EventStatus::Rejected, |
| 1923 | Some(EffectCertainty::NoEffect), |
| 1924 | "NOT_DONE", |
| 1925 | ), |
| 1926 | (ControlResponse::ComposeNoted(_), _) => ( |
| 1927 | EventStatus::Uncertain, |
| 1928 | Some(EffectCertainty::Uncertain), |
| 1929 | "UNRESOLVED", |
| 1930 | ), |
| 1931 | (ControlResponse::Error(e), _) if e.starts_with("EFFECT_REFUSED ") => { |
| 1932 | (EventStatus::Rejected, None, refusal_name(e)) |
| 1933 | } |
| 1934 | (ControlResponse::Error(_), _) => (EventStatus::Failed, None, "error"), |
| 1935 | _ => (EventStatus::Malformed, None, "unexpected_response"), |
| 1936 | }; |
| 1937 | b.trace_event( |
| 1938 | aien_trace::EventKind::EffectExecuted, |
| 1939 | status, |
| 1940 | certainty, |
| 1941 | aien_trace::CorrelationIds { |
| 1942 | tool_request_id: Some(aien_trace::BoundedId::new(&intent.to_string())), |
| 1943 | grant_id: grant.map(|g| aien_trace::BoundedId::new(&g.to_string())), |
| 1944 | ..Default::default() |
| 1945 | }, |
| 1946 | aien_trace::EvidenceRefs::default(), |
| 1947 | note, |
| 1948 | ); |
| 1949 | } |
| 1950 | r |
| 1951 | } |
| 1952 | |
| 1953 | /// sovereign-core #408: re-read the objective record of an objective-bound |
| 1954 | /// intent for a reconcile report. Never decides the effect's state. |
| 1955 | fn objective_binding(l: &Ledger, row: &IntentRow) -> Option<ObjectiveBinding> { |
| 1956 | let id = row.objective_id.as_ref()?; |
| 1957 | let refused = |name: &str, detail: String| ObjectiveBinding { |
| 1958 | objective_id: id.clone(), |
| 1959 | record: name.to_string(), |
| 1960 | detail: Some(detail), |
| 1961 | record_unchanged: None, |
| 1962 | }; |
| 1963 | let approved = l |
| 1964 | .grants |
| 1965 | .get(&row.authorization) |
| 1966 | .and_then(|g| g.objective.as_ref()) |
| 1967 | .filter(|a| &a.id == id); |
| 1968 | let Some(a) = approved else { |
| 1969 | return Some(refused( |
| 1970 | crate::objective::MISMATCH, |
| 1971 | format!( |
| 1972 | "intent #{} names objective {id}; its grant #{} is not bound to it", |
| 1973 | row.id, row.authorization |
| 1974 | ), |
| 1975 | )); |
| 1976 | }; |
| 1977 | Some(match crate::objective::check(id, &a.text_sha256) { |
| 1978 | Ok(s) => ObjectiveBinding { |
| 1979 | objective_id: id.clone(), |
| 1980 | record: "bound".into(), |
| 1981 | detail: None, |
| 1982 | record_unchanged: Some(s.record_sha256 == a.record_sha256), |
| 1983 | }, |
| 1984 | Err((n, d)) => refused(n, d), |
| 1985 | }) |
| 1986 | } |
| 1987 | |
| 1988 | /// Reconcile every unsettled intent whose executor is gone, or record one |
| 1989 | /// operator declaration. `by` names who decided ("reconcile@start", ...). |
| 1990 | pub fn reconcile( |
| 1991 | b: &ComposeBridge, |
| 1992 | declare: Option<&ReconcileDeclare>, |
| 1993 | by: &str, |
| 1994 | ) -> ControlResponse { |
| 1995 | let r = b.with_home(|home| { |
| 1996 | let l = ledger(home)?; |
| 1997 | let mut out = Vec::new(); |
| 1998 | let mut checked = 0u64; |
| 1999 | let rows: Vec<IntentRow> = match declare { |
| 2000 | Some(d) => { |
| 2001 | let row = l |
| 2002 | .intents |
| 2003 | .get(&d.intent) |
| 2004 | .ok_or_else(|| format!("reconcile: #{} is not an effect intent", d.intent))?; |
| 2005 | if row.state.terminal() { |
| 2006 | return Err(format!( |
| 2007 | "reconcile: intent #{} is already {}", |
| 2008 | d.intent, |
| 2009 | row.state.name() |
| 2010 | )); |
| 2011 | } |
| 2012 | vec![row.clone()] |
| 2013 | } |
| 2014 | None => l.unsettled().cloned().collect(), |
| 2015 | }; |
| 2016 | for row in rows { |
| 2017 | checked += 1; |
| 2018 | let objective = objective_binding(&l, &row); |
| 2019 | if executor_alive(row.executor_pid, row.executor_start) { |
| 2020 | out.push(ReconcileOutcome { |
| 2021 | intent: row.id, |
| 2022 | authorization: row.authorization, |
| 2023 | state: row.state.name().into(), |
| 2024 | disk_sha256: None, |
| 2025 | record: None, |
| 2026 | note: format!( |
| 2027 | "executor pid {} still running; not decided", |
| 2028 | row.executor_pid |
| 2029 | ), |
| 2030 | objective: objective.clone(), |
| 2031 | }); |
| 2032 | continue; |
| 2033 | } |
| 2034 | let (world, disk) = confined_world_state(&l, &row); |
| 2035 | let disk_hex = disk.as_ref().ok().cloned().flatten(); |
| 2036 | let (st, who) = match declare { |
| 2037 | Some(d) => { |
| 2038 | let st = match d.state.as_str() { |
| 2039 | "done" | "DONE" => EffectState::Done, |
| 2040 | "not_done" | "NOT_DONE" => EffectState::NotDone, |
| 2041 | other => { |
| 2042 | return Err(format!("reconcile: --declare {other:?} (done, not_done)")) |
| 2043 | } |
| 2044 | }; |
| 2045 | if d.approver.trim().is_empty() { |
| 2046 | return Err("reconcile: a declaration needs --approver".into()); |
| 2047 | } |
| 2048 | (st, format!("operator:{}", d.approver.trim())) |
| 2049 | } |
| 2050 | None => (world, by.to_string()), |
| 2051 | }; |
| 2052 | // Never DONE for a target outside its workspace, not even by declaration. |
| 2053 | if st == EffectState::Done |
| 2054 | && disk.as_ref().is_err_and(|e| { |
| 2055 | e.starts_with("OutsideWorkspace") || e.starts_with(NOT_DAEMON_MINTED) |
| 2056 | }) |
| 2057 | { |
| 2058 | return Err(format!( |
| 2059 | "reconcile: intent #{} cannot be declared DONE: {}", |
| 2060 | row.id, |
| 2061 | disk.as_ref().err().map(String::as_str).unwrap_or_default() |
| 2062 | )); |
| 2063 | } |
| 2064 | if st == EffectState::Unresolved && row.unresolved_digest.as_ref() == Some(&disk_hex) { |
| 2065 | out.push(ReconcileOutcome { |
| 2066 | intent: row.id, |
| 2067 | authorization: row.authorization, |
| 2068 | state: st.name().into(), |
| 2069 | disk_sha256: disk_hex, |
| 2070 | record: None, |
| 2071 | note: "still UNRESOLVED, already recorded for this target digest".into(), |
| 2072 | objective: objective.clone(), |
| 2073 | }); |
| 2074 | continue; |
| 2075 | } |
| 2076 | let text = reconcile_text(&row, st, world, &disk, &who, objective.as_ref()); |
| 2077 | let n = append(home, NoteKind::Effect, &[row.id, row.authorization], &text)?; |
| 2078 | out.push(ReconcileOutcome { |
| 2079 | intent: row.id, |
| 2080 | authorization: row.authorization, |
| 2081 | state: st.name().into(), |
| 2082 | disk_sha256: disk_hex, |
| 2083 | record: Some(n.id), |
| 2084 | note: who, |
| 2085 | objective, |
| 2086 | }); |
| 2087 | } |
| 2088 | Ok(ComposeReconcileReport { |
| 2089 | compose_dir: b.dir().display().to_string(), |
| 2090 | machine_id: home.machine_id.clone(), |
| 2091 | checked, |
| 2092 | outcomes: out, |
| 2093 | }) |
| 2094 | }); |
| 2095 | let out = match r { |
| 2096 | Ok(r) => { |
| 2097 | // A full reconcile that completed lifts the refusal of 2.5; a |
| 2098 | // single declaration does not. |
| 2099 | if declare.is_none() { |
| 2100 | b.clear_reconcile_failed(); |
| 2101 | } |
| 2102 | ControlResponse::ComposeReconciled(Box::new(r)) |
| 2103 | } |
| 2104 | Err(e) => ControlResponse::Error(e), |
| 2105 | }; |
| 2106 | // Correlation only (#398): one event per reconcile call. `by` is a short |
| 2107 | // caller label ("reconcile@start", an operator name), never free text |
| 2108 | // from a model; the note is bounded anyway. |
| 2109 | if b.trace_enabled() { |
| 2110 | let (status, note) = match &out { |
| 2111 | ControlResponse::ComposeReconciled(_) => (aien_trace::EventStatus::Ok, by), |
| 2112 | ControlResponse::Error(_) => (aien_trace::EventStatus::Failed, "reconcile_failed"), |
| 2113 | _ => (aien_trace::EventStatus::Malformed, "unexpected_response"), |
| 2114 | }; |
| 2115 | b.trace_event( |
| 2116 | aien_trace::EventKind::ResultReceived, |
| 2117 | status, |
| 2118 | None, |
| 2119 | aien_trace::CorrelationIds { |
| 2120 | tool_request_id: declare.map(|d| aien_trace::BoundedId::new(&d.intent.to_string())), |
| 2121 | ..Default::default() |
| 2122 | }, |
| 2123 | aien_trace::EvidenceRefs::default(), |
| 2124 | note, |
| 2125 | ); |
| 2126 | } |
| 2127 | out |
| 2128 | } |
| 2129 | |
| 2130 | /// ComposeControl: stop, resume, revoke (ACCEPTANCE-v2 2.5, 2.6). |
| 2131 | pub fn control( |
| 2132 | b: &ComposeBridge, |
| 2133 | action: &str, |
| 2134 | approver: &str, |
| 2135 | authorization: Option<u64>, |
| 2136 | ) -> ControlResponse { |
| 2137 | let r = b.with_home(|home| { |
| 2138 | if approver.trim().is_empty() { |
| 2139 | return Err(format!("ComposeControl {action}: --approver is required")); |
| 2140 | } |
| 2141 | let l = ledger(home)?; |
| 2142 | let (text, links, revoked) = match action { |
| 2143 | "stop" | "resume" => ( |
| 2144 | json!({"control": action, "approver": approver.trim()}), |
| 2145 | vec![], |
| 2146 | None, |
| 2147 | ), |
| 2148 | "revoke" => { |
| 2149 | let a = |
| 2150 | authorization.ok_or("ComposeControl revoke: --authorization is required")?; |
| 2151 | if !l.grants.contains_key(&a) { |
| 2152 | return Err(format!( |
| 2153 | "ComposeControl revoke: #{a} is not an authorization" |
| 2154 | )); |
| 2155 | } |
| 2156 | if l.spent.contains_key(&a) |
| 2157 | || l.legacy_spent.contains_key(&a) |
| 2158 | || l.revoked.contains_key(&a) |
| 2159 | { |
| 2160 | // Spent (or already revoked): nothing to revoke, nothing recorded. |
| 2161 | return Ok(ComposeControlReport { |
| 2162 | action: action.into(), |
| 2163 | recorded: None, |
| 2164 | revoked: Some(false), |
| 2165 | }); |
| 2166 | } |
| 2167 | ( |
| 2168 | json!({"control": "revoke", "authorization": a, "approver": approver.trim()}), |
| 2169 | vec![a], |
| 2170 | Some(true), |
| 2171 | ) |
| 2172 | } |
| 2173 | other => { |
| 2174 | return Err(format!( |
| 2175 | "ComposeControl: action {other:?} (stop, resume, revoke)" |
| 2176 | )) |
| 2177 | } |
| 2178 | }; |
| 2179 | let n = append(home, NoteKind::Authorization, &links, &text)?; |
| 2180 | Ok(ComposeControlReport { |
| 2181 | action: action.into(), |
| 2182 | recorded: Some(n), |
| 2183 | revoked, |
| 2184 | }) |
| 2185 | }); |
| 2186 | match r { |
| 2187 | Ok(r) => ControlResponse::ComposeControlled(Box::new(r)), |
| 2188 | Err(e) => ControlResponse::Error(e), |
| 2189 | } |
| 2190 | } |
| 2191 | |
| 2192 | /// The tail of every start line after which effect commands refuse. |
| 2193 | pub const RECONCILE_GATE_NOTE: &str = |
| 2194 | "effect commands refuse until a successful reconcile (aien compose reconcile)"; |
| 2195 | |
| 2196 | /// Daemon start: reconcile an existing home once; one line for the log. |
| 2197 | pub fn reconcile_at_start(b: &ComposeBridge) -> String { |
| 2198 | // Test builds only (ACCEPTANCE-v3 2.6): a panic inside the spawn_blocking |
| 2199 | // task. Release builds abort on it (ACCEPTANCE-v4 row C7c). |
| 2200 | #[cfg(feature = "fault-hold")] |
| 2201 | if std::env::var("AIEN_FAULT_HOLD").as_deref() == Ok("reconcile_panic") { |
| 2202 | panic!("fault hold reconcile_panic: forced start-up reconcile failure (test build)"); |
| 2203 | } |
| 2204 | if !b.dir().join("cortex.cx").exists() { |
| 2205 | return "Reconcile: no compose home yet".into(); |
| 2206 | } |
| 2207 | // Test builds only (ACCEPTANCE-v4 2.1): force the error arm below, the |
| 2208 | // path a release build takes (it aborts on panic, Cargo.toml). |
| 2209 | #[cfg(feature = "fault-hold")] |
| 2210 | let result = if std::env::var("AIEN_FAULT_HOLD").as_deref() == Ok("reconcile_error") { |
| 2211 | ControlResponse::Error( |
| 2212 | "fault hold reconcile_error: forced start-up reconcile error (test build)".into(), |
| 2213 | ) |
| 2214 | } else { |
| 2215 | reconcile(b, None, "reconcile@start") |
| 2216 | }; |
| 2217 | #[cfg(not(feature = "fault-hold"))] |
| 2218 | let result = reconcile(b, None, "reconcile@start"); |
| 2219 | match result { |
| 2220 | ControlResponse::ComposeReconciled(r) => { |
| 2221 | let n = |st: &str| { |
| 2222 | r.outcomes |
| 2223 | .iter() |
| 2224 | .filter(|o| o.state == st && o.record.is_some()) |
| 2225 | .count() |
| 2226 | }; |
| 2227 | let pending = r.outcomes.iter().filter(|o| o.record.is_none()).count(); |
| 2228 | format!( |
| 2229 | "Reconcile: checked {} unsettled effect(s): DONE {}, NOT_DONE {}, UNRESOLVED {} recorded, {} left as they were; {}", |
| 2230 | r.checked, |
| 2231 | n("DONE"), |
| 2232 | n("NOT_DONE"), |
| 2233 | n("UNRESOLVED"), |
| 2234 | pending, |
| 2235 | serde_json::to_string(&r.outcomes).unwrap_or_default() |
| 2236 | ) |
| 2237 | } |
| 2238 | ControlResponse::Error(e) => { |
| 2239 | b.set_reconcile_failed(format!("refused: {e}")); |
| 2240 | format!("Reconcile: refused: {e}; {RECONCILE_GATE_NOTE}") |
| 2241 | } |
| 2242 | other => { |
| 2243 | b.set_reconcile_failed(format!("unexpected {other:?}")); |
| 2244 | format!("Reconcile: unexpected {other:?}; {RECONCILE_GATE_NOTE}") |
| 2245 | } |
| 2246 | } |
| 2247 | } |
| 2248 | |
| 2249 | #[cfg(test)] |
| 2250 | mod tests { |
| 2251 | use super::*; |
| 2252 | |
| 2253 | #[test] |
| 2254 | fn refusal_name_reads_only_the_name() { |
| 2255 | assert_eq!( |
| 2256 | refusal_name("EFFECT_REFUSED NotAuthorized: needs an approver"), |
| 2257 | "NotAuthorized" |
| 2258 | ); |
| 2259 | assert_eq!(refusal_name("EFFECT_REFUSED Revoked: grant #3"), "Revoked"); |
| 2260 | assert_eq!(refusal_name("EFFECT_REFUSED : odd"), "error"); |
| 2261 | assert_eq!(refusal_name("compose home refused: journal"), "error"); |
| 2262 | assert_eq!(refusal_name(""), "error"); |
| 2263 | } |
| 2264 | |
| 2265 | /// #398: the compose spine emits correlation events for authority, intent, |
| 2266 | /// ack and reconcile outcomes; refusals carry only the refusal name, and no |
| 2267 | /// event carries goal, proposal or path text. |
| 2268 | #[test] |
| 2269 | fn compose_spine_emits_correlation_events_without_content() { |
| 2270 | use aien_trace::{EffectCertainty, EventKind, EventStatus, MemorySink}; |
| 2271 | let _home = crate::home_guard::home_slot(); |
| 2272 | if !aien_omega_compose::LINKED { |
| 2273 | eprintln!("NOT_RUN: stub compose build"); |
| 2274 | return; |
| 2275 | } |
| 2276 | let t = tempfile::tempdir().unwrap(); |
| 2277 | let proposer: crate::compose::ComposeProposer = |
| 2278 | std::sync::Arc::new(|_: &str, _: std::time::Duration| { |
| 2279 | Ok(crate::compose::Generation::default()) |
| 2280 | }); |
| 2281 | let sink = std::sync::Arc::new(MemorySink::new()); |
| 2282 | let b = ComposeBridge::new(t.path().join("compose"), proposer, "test:trace") |
| 2283 | .with_trace_sink(sink.clone()); |
| 2284 | // Start-up reconcile on an empty home: one result_received event. |
| 2285 | let _ = reconcile_at_start(&b); |
| 2286 | // Refused authorization: no approver. |
| 2287 | let r = authorize( |
| 2288 | &b, |
| 2289 | &MintRequest { |
| 2290 | cx_promotion: 7, |
| 2291 | proposal_sha256: "00".repeat(32), |
| 2292 | workspace: t.path().display().to_string(), |
| 2293 | approver: " ".into(), |
| 2294 | constraints: vec![], |
| 2295 | }, |
| 2296 | None, |
| 2297 | ); |
| 2298 | assert!( |
| 2299 | matches!(r, ControlResponse::Error(ref e) if e.contains("NotAuthorized")), |
| 2300 | "{r:?}" |
| 2301 | ); |
| 2302 | // Ack of an intent that does not exist: plain error, never a certainty. |
| 2303 | let r = ack(&b, 999, &json!({"wrote": true})); |
| 2304 | assert!(matches!(r, ControlResponse::Error(_)), "{r:?}"); |
| 2305 | let events = sink.drain(); |
| 2306 | let kinds: Vec<EventKind> = events.iter().map(|e| e.kind).collect(); |
| 2307 | assert!( |
| 2308 | kinds.contains(&EventKind::AuthorityDecided) |
| 2309 | && kinds.contains(&EventKind::EffectExecuted), |
| 2310 | "{kinds:?}" |
| 2311 | ); |
| 2312 | let auth = events |
| 2313 | .iter() |
| 2314 | .find(|e| e.kind == EventKind::AuthorityDecided) |
| 2315 | .unwrap(); |
| 2316 | assert_eq!(auth.status, EventStatus::Rejected); |
| 2317 | assert_eq!(auth.effect_certainty, Some(EffectCertainty::NoEffect)); |
| 2318 | assert_eq!( |
| 2319 | auth.note.as_ref().map(|n| n.as_str()), |
| 2320 | Some("NotAuthorized") |
| 2321 | ); |
| 2322 | assert_eq!(auth.ids.decision_id.as_ref().map(|d| d.as_str()), Some("7")); |
| 2323 | let eff = events |
| 2324 | .iter() |
| 2325 | .find(|e| e.kind == EventKind::EffectExecuted) |
| 2326 | .unwrap(); |
| 2327 | assert_eq!(eff.status, EventStatus::Failed); |
| 2328 | assert_eq!(eff.effect_certainty, None); |
| 2329 | assert_eq!( |
| 2330 | eff.ids.tool_request_id.as_ref().map(|d| d.as_str()), |
| 2331 | Some("999") |
| 2332 | ); |
| 2333 | // One trace id, one root, every other event a child of it. |
| 2334 | let root = events |
| 2335 | .iter() |
| 2336 | .filter(|e| e.parent_event_id.is_none()) |
| 2337 | .count(); |
| 2338 | assert_eq!(root, 1, "{events:?}"); |
| 2339 | let root_id = events |
| 2340 | .iter() |
| 2341 | .find(|e| e.parent_event_id.is_none()) |
| 2342 | .unwrap() |
| 2343 | .event_id; |
| 2344 | assert!(events.iter().all(|e| e.trace_id == b.trace_id())); |
| 2345 | assert!(events |
| 2346 | .iter() |
| 2347 | .filter(|e| e.event_id != root_id) |
| 2348 | .all(|e| e.parent_event_id == Some(root_id))); |
| 2349 | // No content: the serialized events never carry the workspace path or |
| 2350 | // the proposal digest, only ids, kinds, statuses and refusal names. |
| 2351 | let text = serde_json::to_string(&events).unwrap(); |
| 2352 | assert!(!text.contains(&t.path().display().to_string()), "{text}"); |
| 2353 | assert!(!text.contains(&"00".repeat(32)), "{text}"); |
| 2354 | let tree = aien_trace::reconstruct(&events).unwrap(); |
| 2355 | assert_eq!(tree.len(), events.len()); |
| 2356 | } |
| 2357 | |
| 2358 | fn rec(id: u64, note: &str, text: Value) -> ComposeRecordView { |
| 2359 | ComposeRecordView { |
| 2360 | id, |
| 2361 | cls: 0, |
| 2362 | kind: 0, |
| 2363 | subject: 0, |
| 2364 | tag: 0, |
| 2365 | links: vec![], |
| 2366 | digest: String::new(), |
| 2367 | verified: true, |
| 2368 | note: Some(note.into()), |
| 2369 | text: Some(text.to_string()), |
| 2370 | } |
| 2371 | } |
| 2372 | |
| 2373 | fn grant(id: u64, prior: Value) -> ComposeRecordView { |
| 2374 | rec( |
| 2375 | id, |
| 2376 | "authorization", |
| 2377 | json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", |
| 2378 | "path": "N.md", "content_sha256": "c", |
| 2379 | "approver": "drake", "target": "/w/N.md", "prior_sha256": prior}), |
| 2380 | ) |
| 2381 | } |
| 2382 | |
| 2383 | /// A grant record nobody minted: what a caller-written note looks like. |
| 2384 | fn caller_grant(id: u64) -> ComposeRecordView { |
| 2385 | rec( |
| 2386 | id, |
| 2387 | "authorization", |
| 2388 | json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", |
| 2389 | "approver": "attacker", "target": "/w/N.md", "prior_sha256": null, |
| 2390 | "workspace": "/w"}), |
| 2391 | ) |
| 2392 | } |
| 2393 | |
| 2394 | fn req(a: u64) -> IntentRequest { |
| 2395 | IntentRequest { |
| 2396 | authorization: a, |
| 2397 | proposal_sha256: "p".into(), |
| 2398 | path: "N.md".into(), |
| 2399 | target: "/w/N.md".into(), |
| 2400 | content_sha256: "c".into(), |
| 2401 | executor_pid: 1, |
| 2402 | executor_start: 1, |
| 2403 | } |
| 2404 | } |
| 2405 | |
| 2406 | fn intent(id: u64, a: u64) -> ComposeRecordView { |
| 2407 | rec( |
| 2408 | id, |
| 2409 | "effect", |
| 2410 | json!({"phase": "intent", "tool": "write_file", "authorization": a, "path": "N.md", |
| 2411 | "target": "/w/N.md", "content_sha256": "c", "prior_sha256": null, |
| 2412 | "proposal_sha256": "p", "executor": {"pid": 1, "start": 1}}), |
| 2413 | ) |
| 2414 | } |
| 2415 | |
| 2416 | fn settle(id: u64, phase: &str, i: u64, st: &str) -> ComposeRecordView { |
| 2417 | rec( |
| 2418 | id, |
| 2419 | "effect", |
| 2420 | json!({"phase": phase, "intent": i, "state": st, "disk_sha256": null}), |
| 2421 | ) |
| 2422 | } |
| 2423 | |
| 2424 | fn refusal(l: &Ledger, a: u64, cur: Option<&str>) -> &'static str { |
| 2425 | l.check_intent(&req(a), &cur.map(str::to_string)) |
| 2426 | .unwrap_err() |
| 2427 | .name |
| 2428 | } |
| 2429 | |
| 2430 | /// A real daemon-built generation record, as a ledger row. |
| 2431 | fn generation_row(id: u64) -> ComposeRecordView { |
| 2432 | let identity = crate::generation::ModelIdentity { |
| 2433 | model_sha256: "m".repeat(64), |
| 2434 | model_digest_kind: "file".into(), |
| 2435 | model_path: "/models/m.safetensors".into(), |
| 2436 | tokenizer_sha256: "t".repeat(64), |
| 2437 | tokenizer_path: "/models/tokenizer.json".into(), |
| 2438 | }; |
| 2439 | let record = crate::generation::build_record( |
| 2440 | &identity, |
| 2441 | &crate::generation::TurnEvidence { |
| 2442 | prompt_ids: &[1, 2, 3], |
| 2443 | output_ids: &[100, 101], |
| 2444 | text: "x100 x101", |
| 2445 | total_tokens: 2, |
| 2446 | finish_reason: "eos", |
| 2447 | request_id: 7, |
| 2448 | operation_id: 8, |
| 2449 | decoding: None, |
| 2450 | ops: None, |
| 2451 | }, |
| 2452 | crate::generation::DaemonStart(1), |
| 2453 | ); |
| 2454 | rec(id, "effect", record) |
| 2455 | } |
| 2456 | |
| 2457 | /// Evidence only: generation records, anywhere in the ledger, change no |
| 2458 | /// ledger state and no authorization or intent decision. |
| 2459 | #[test] |
| 2460 | fn generation_records_change_no_decision() { |
| 2461 | let base = vec![ |
| 2462 | grant(2, Value::Null), |
| 2463 | intent(3, 2), |
| 2464 | settle(4, "ack", 3, "DONE"), |
| 2465 | grant(5, Value::Null), |
| 2466 | ]; |
| 2467 | let mut with = base.clone(); |
| 2468 | with.push(generation_row(6)); |
| 2469 | with.push(generation_row(7)); |
| 2470 | let (a, b) = ( |
| 2471 | Ledger::from_records(&base).unwrap(), |
| 2472 | Ledger::from_records(&with).unwrap(), |
| 2473 | ); |
| 2474 | assert_eq!(a.view(), b.view()); |
| 2475 | assert_eq!(refusal(&a, 2, None), refusal(&b, 2, None)); |
| 2476 | assert_eq!(refusal(&a, 2, None), "AlreadySpent"); |
| 2477 | assert_eq!( |
| 2478 | a.check_intent(&req(5), &None).map(|g| g.id), |
| 2479 | b.check_intent(&req(5), &None).map(|g| g.id) |
| 2480 | ); |
| 2481 | // A generation record alone opens nothing and spends nothing. |
| 2482 | let only = Ledger::from_records(&[generation_row(2)]).unwrap(); |
| 2483 | assert_eq!(only.view(), Ledger::default().view()); |
| 2484 | } |
| 2485 | |
| 2486 | #[test] |
| 2487 | fn generation_records_cannot_be_forged_through_compose_note() { |
| 2488 | let g = r#"{"generation":1,"model_sha256":"x"}"#; |
| 2489 | assert!(check_reserved_note("effect", g).is_err()); |
| 2490 | assert!(check_reserved_note("generation", "anything").is_err()); |
| 2491 | assert!(check_reserved_note("generation", g).is_err()); |
| 2492 | } |
| 2493 | |
| 2494 | #[test] |
| 2495 | fn provenance_cannot_be_set_through_compose_note() { |
| 2496 | let p = r#"{"provenance":{"generation_record":3,"allen_agent":"none"}}"#; |
| 2497 | for kind in ["effect", "constraint", "authorization", "provenance"] { |
| 2498 | assert!(check_reserved_note(kind, p).is_err(), "{kind}"); |
| 2499 | } |
| 2500 | // A forged copy of the daemon's own records, with provenance, is refused too. |
| 2501 | let c = r#"{"compose_commit":1,"provenance":{"generation_record":3}}"#; |
| 2502 | assert!(check_reserved_note("effect", c).is_err()); |
| 2503 | // Without the field an ordinary note is still fine. |
| 2504 | assert!(check_reserved_note("constraint", r#"{"a":1}"#).is_ok()); |
| 2505 | } |
| 2506 | |
| 2507 | fn commit_row(id: u64, prov: Option<Value>) -> ComposeRecordView { |
| 2508 | let mut v = json!({"compose_commit": 1, "task": 1, "cx_promotion": 1, "cx_evidence": 1, |
| 2509 | "proposal_sha256": "p", "path": "N.md", "content_sha256": "c", "workspace": "/w"}); |
| 2510 | if let Some(p) = prov { |
| 2511 | v["provenance"] = p; |
| 2512 | } |
| 2513 | rec(id, "effect", v) |
| 2514 | } |
| 2515 | |
| 2516 | fn with_prov(mut r: ComposeRecordView, prov: Value) -> ComposeRecordView { |
| 2517 | let mut v: Value = serde_json::from_str(r.text.as_deref().unwrap()).unwrap(); |
| 2518 | v["provenance"] = prov; |
| 2519 | r.text = Some(v.to_string()); |
| 2520 | r |
| 2521 | } |
| 2522 | |
| 2523 | /// Evidence only: whatever the provenance fields say (valid, absent, naming |
| 2524 | /// nothing, the wrong type, hostile), the ledger state and every decision |
| 2525 | /// are the ones the same records give without them. |
| 2526 | #[test] |
| 2527 | fn provenance_changes_no_decision() { |
| 2528 | let chain = |prov: Option<Value>| { |
| 2529 | let mut v = vec![ |
| 2530 | commit_row(1, prov.clone()), |
| 2531 | grant(2, Value::Null), |
| 2532 | intent(3, 2), |
| 2533 | settle(4, "ack", 3, "DONE"), |
| 2534 | grant(5, Value::Null), |
| 2535 | intent(6, 5), |
| 2536 | ]; |
| 2537 | if let Some(p) = prov { |
| 2538 | for r in v.iter_mut().skip(1) { |
| 2539 | *r = with_prov(r.clone(), p.clone()); |
| 2540 | } |
| 2541 | } |
| 2542 | v |
| 2543 | }; |
| 2544 | let base = Ledger::from_records(&chain(None)).unwrap(); |
| 2545 | for prov in [ |
| 2546 | json!({"generation_record": 7, "allen_agent": "ab".repeat(32)}), |
| 2547 | json!({"generation_record": 99999, "allen_agent": "none"}), |
| 2548 | json!({"generation_record": null, "allen_agent": "none"}), |
| 2549 | json!({"generation_record": null, "allen_agent": "none", "generation_record_stale": 9, "provenance_note": "generation_record_stale"}), |
| 2550 | json!({"generation_record": "seven", "allen_agent": 5}), |
| 2551 | json!("garbage"), |
| 2552 | json!(null), |
| 2553 | json!({"generation_record": u64::MAX, "allen_agent": "\u{0}x".repeat(500)}), |
| 2554 | ] { |
| 2555 | let l = Ledger::from_records(&chain(Some(prov.clone()))).unwrap(); |
| 2556 | assert_eq!(base.view(), l.view(), "{prov}"); |
| 2557 | for a in [2u64, 5, 9] { |
| 2558 | assert_eq!(refusal(&base, a, None), refusal(&l, a, None), "{prov} #{a}"); |
| 2559 | } |
| 2560 | assert_eq!( |
| 2561 | base.check_intent(&req(5), &None).map(|g| g.id), |
| 2562 | l.check_intent(&req(5), &None).map(|g| g.id) |
| 2563 | ); |
| 2564 | assert_eq!(base.commits, l.commits, "{prov}"); |
| 2565 | assert_eq!(base.grants, l.grants, "{prov}"); |
| 2566 | assert_eq!(base.intents, l.intents, "{prov}"); |
| 2567 | } |
| 2568 | } |
| 2569 | |
| 2570 | /// The same, for the code: the only reader of provenance is |
| 2571 | /// `Provenance::from_text`, reached only through `stamp`/`inherit`, and the |
| 2572 | /// ledger-side code that mentions provenance is a short, named list of |
| 2573 | /// writers that call it after their decisions are made. Nothing in |
| 2574 | /// `Ledger`, `check_*`, the world checks or reconcile can see it. |
| 2575 | #[test] |
| 2576 | fn provenance_is_read_by_no_decision_code() { |
| 2577 | let src = include_str!("effects.rs"); |
| 2578 | let prod = src.split("#[cfg(test)]\nmod tests").next().unwrap(); |
| 2579 | let tokens = [ |
| 2580 | "PROVENANCE", |
| 2581 | "Provenance", |
| 2582 | "provenance", |
| 2583 | "stamp(", |
| 2584 | "inherit(", |
| 2585 | "generation_record", |
| 2586 | "allen_agent", |
| 2587 | "stale_generation", |
| 2588 | "provenance_note", |
| 2589 | ]; |
| 2590 | // The enclosing `fn` of every mention. |
| 2591 | let mut cur = String::from("<top>"); |
| 2592 | let mut hits: Vec<(String, String)> = Vec::new(); |
| 2593 | for line in prod.lines() { |
| 2594 | let t = line.trim_start(); |
| 2595 | if let Some(i) = t.find("fn ") { |
| 2596 | let pre = &t[..i]; |
| 2597 | if pre.is_empty() || pre == "pub " || pre == "pub(crate) " { |
| 2598 | cur = t[i + 3..] |
| 2599 | .split(|c: char| !(c.is_alphanumeric() || c == '_')) |
| 2600 | .next() |
| 2601 | .unwrap() |
| 2602 | .to_string(); |
| 2603 | } |
| 2604 | } |
| 2605 | if t.starts_with("//") { |
| 2606 | continue; |
| 2607 | } |
| 2608 | if tokens.iter().any(|k| line.contains(k)) { |
| 2609 | hits.push((cur.clone(), t.to_string())); |
| 2610 | } |
| 2611 | } |
| 2612 | let writers = [ |
| 2613 | "stamp", |
| 2614 | "write_compose_commit", |
| 2615 | "write_approved_grant", |
| 2616 | "authorize", |
| 2617 | "authorize_inner", |
| 2618 | "open_intent", |
| 2619 | "open_intent_inner", |
| 2620 | "ack", |
| 2621 | "check_reserved_note", |
| 2622 | ]; |
| 2623 | for (f, line) in &hits { |
| 2624 | assert!( |
| 2625 | writers.contains(&f.as_str()), |
| 2626 | "{f} mentions provenance: {line}" |
| 2627 | ); |
| 2628 | } |
| 2629 | // Inside the writers that also decide, the only mention is the stamp |
| 2630 | // call (or the reserved-field refusal), never a read of the fields. |
| 2631 | for (f, line) in &hits { |
| 2632 | if [ |
| 2633 | "authorize", |
| 2634 | "authorize_inner", |
| 2635 | "open_intent", |
| 2636 | "open_intent_inner", |
| 2637 | "ack", |
| 2638 | ] |
| 2639 | .contains(&f.as_str()) |
| 2640 | { |
| 2641 | assert!( |
| 2642 | line.starts_with("stamp(&mut text, &views, "), |
| 2643 | "{f} touches provenance other than by stamp: {line}" |
| 2644 | ); |
| 2645 | } |
| 2646 | } |
| 2647 | // Everything else in the crate: the field's name and its reader appear |
| 2648 | // only in generation.rs (definition), effects.rs (above), compose/bridge.rs |
| 2649 | // (the writer of the commit) and server.rs/control.rs (plumbing). Every |
| 2650 | // source file, subdirectories included. |
| 2651 | let mut files = Vec::new(); |
| 2652 | let mut dirs = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; |
| 2653 | while let Some(d) = dirs.pop() { |
| 2654 | for e in std::fs::read_dir(d).unwrap() { |
| 2655 | let p = e.unwrap().path(); |
| 2656 | if p.is_dir() { |
| 2657 | dirs.push(p); |
| 2658 | } else { |
| 2659 | files.push(p); |
| 2660 | } |
| 2661 | } |
| 2662 | } |
| 2663 | for p in files { |
| 2664 | let name = p.file_name().unwrap().to_string_lossy().into_owned(); |
| 2665 | if !name.ends_with(".rs") { |
| 2666 | continue; |
| 2667 | } |
| 2668 | let s = std::fs::read_to_string(&p).unwrap(); |
| 2669 | let s = s.split("#[cfg(test)]").next().unwrap(); |
| 2670 | let reads = s.contains("Provenance::from_text") || s.contains("generation::inherit"); |
| 2671 | let allowed = ["generation.rs", "effects.rs"].contains(&name.as_str()); |
| 2672 | assert!(!reads || allowed, "{name} reads provenance"); |
| 2673 | } |
| 2674 | // The Ledger types carry no provenance field at all. |
| 2675 | for ty in [ |
| 2676 | "pub struct Grant", |
| 2677 | "pub struct CommitRow", |
| 2678 | "pub struct IntentRow", |
| 2679 | "pub struct Ledger", |
| 2680 | ] { |
| 2681 | let body = prod |
| 2682 | .split(ty) |
| 2683 | .nth(1) |
| 2684 | .unwrap() |
| 2685 | .split("\n}\n") |
| 2686 | .next() |
| 2687 | .unwrap(); |
| 2688 | assert!(!body.to_lowercase().contains("provenance"), "{ty}"); |
| 2689 | } |
| 2690 | } |
| 2691 | |
| 2692 | #[test] |
| 2693 | fn old_records_without_provenance_read_as_explicit_none() { |
| 2694 | use crate::generation::{inherit, Provenance, NO_AGENT}; |
| 2695 | let old = vec![commit_row(1, None), grant(2, Value::Null), intent(3, 2)]; |
| 2696 | // The ledger opens and verifies as before. |
| 2697 | assert!(Ledger::from_records(&old).is_ok()); |
| 2698 | let p = inherit(&old, 1); |
| 2699 | assert_eq!(p, Provenance::default()); |
| 2700 | assert_eq!(p.allen_agent, NO_AGENT); |
| 2701 | assert_eq!(p.generation_record, None); |
| 2702 | // Missing record, or text that is not a record at all: the plain default |
| 2703 | // (no provenance field was ever there), never an error. |
| 2704 | assert_eq!(inherit(&old, 77), Provenance::default()); |
| 2705 | assert_eq!(Provenance::from_text("not json"), Provenance::default()); |
| 2706 | // A provenance field that is PRESENT but damaged is not silently "none": |
| 2707 | // the values default and a visible note says why. |
| 2708 | let bad_agent = Provenance::from_text( |
| 2709 | r#"{"provenance":{"allen_agent":"nope","generation_record":-1}}"#, |
| 2710 | ); |
| 2711 | assert_eq!(bad_agent.allen_agent, NO_AGENT); |
| 2712 | assert_eq!(bad_agent.note.as_deref(), Some("allen_agent_malformed")); |
| 2713 | assert_ne!(bad_agent, Provenance::default()); |
| 2714 | assert_eq!( |
| 2715 | bad_agent.to_json()["provenance_note"], |
| 2716 | "allen_agent_malformed" |
| 2717 | ); |
| 2718 | let not_obj = Provenance::from_text(r#"{"provenance":"garbage"}"#); |
| 2719 | assert_eq!(not_obj.note.as_deref(), Some("provenance_malformed")); |
| 2720 | // A generation id that names no generation record is not copied as a |
| 2721 | // plain null: the old id stays visible and a note says it is stale. |
| 2722 | let named = vec![commit_row( |
| 2723 | 1, |
| 2724 | Some(json!({"generation_record": 9, "allen_agent": "ab".repeat(32)})), |
| 2725 | )]; |
| 2726 | let p = inherit(&named, 1); |
| 2727 | assert_eq!(p.generation_record, None); |
| 2728 | assert_eq!(p.stale_generation, Some(9)); |
| 2729 | assert_eq!(p.note.as_deref(), Some("generation_record_stale")); |
| 2730 | assert_eq!(p.allen_agent, "ab".repeat(32)); |
| 2731 | let j = p.to_json(); |
| 2732 | assert_eq!(j["generation_record"], Value::Null); |
| 2733 | assert_eq!(j["generation_record_stale"], 9); |
| 2734 | assert_eq!(j["provenance_note"], "generation_record_stale"); |
| 2735 | // The marker survives the next copy down the chain (grant -> intent). |
| 2736 | let next = vec![rec( |
| 2737 | 2, |
| 2738 | "effect", |
| 2739 | json!({"phase": "intent", "provenance": j}), |
| 2740 | )]; |
| 2741 | let q = inherit(&next, 2); |
| 2742 | assert_eq!(q.stale_generation, Some(9)); |
| 2743 | assert_eq!(q.note.as_deref(), Some("generation_record_stale")); |
| 2744 | // ... and kept when it does (the record must be a verified generation record). |
| 2745 | let mut with_gen = named.clone(); |
| 2746 | with_gen.push(generation_row(9)); |
| 2747 | assert_eq!(inherit(&with_gen, 1).generation_record, Some(9)); |
| 2748 | // A non-generation record (or an unverified one) does not count. |
| 2749 | let mut not_gen = named; |
| 2750 | not_gen.push(rec(9, "effect", json!({"x": 1}))); |
| 2751 | assert_eq!(inherit(¬_gen, 1).generation_record, None); |
| 2752 | let mut bad = with_gen; |
| 2753 | bad[1].verified = false; |
| 2754 | assert_eq!(inherit(&bad, 1).generation_record, None); |
| 2755 | } |
| 2756 | |
| 2757 | /// A record that names a nonexistent generation id is refused at write time. |
| 2758 | #[test] |
| 2759 | fn a_commit_naming_no_generation_record_is_not_written() { |
| 2760 | let _home = crate::home_guard::home_slot(); |
| 2761 | use crate::compose::{ComposeBridge, Generation}; |
| 2762 | use crate::generation::Provenance; |
| 2763 | if !aien_omega_compose::LINKED { |
| 2764 | eprintln!("NOT_RUN: stub compose build"); |
| 2765 | return; |
| 2766 | } |
| 2767 | let t = tempfile::tempdir().unwrap(); |
| 2768 | let proposer: crate::compose::ComposeProposer = |
| 2769 | std::sync::Arc::new(|_: &str, _: std::time::Duration| Ok(Generation::default())); |
| 2770 | let b = ComposeBridge::new(t.path().join("compose"), proposer, "test:fixed"); |
| 2771 | let note = match b.note("constraint", "an ordinary note", &[]) { |
| 2772 | ControlResponse::ComposeNoted(n) => n.id, |
| 2773 | other => panic!("{other:?}"), |
| 2774 | }; |
| 2775 | let write = |g: Option<u64>| { |
| 2776 | b.with_home(|home| { |
| 2777 | write_compose_commit( |
| 2778 | home, |
| 2779 | "/w", |
| 2780 | 1, |
| 2781 | 1, |
| 2782 | 1, |
| 2783 | "p", |
| 2784 | "N.md", |
| 2785 | "c", |
| 2786 | None, |
| 2787 | &Provenance { |
| 2788 | generation_record: g, |
| 2789 | allen_agent: "none".into(), |
| 2790 | ..Default::default() |
| 2791 | }, |
| 2792 | ) |
| 2793 | }) |
| 2794 | }; |
| 2795 | let before = host_count(&b); |
| 2796 | for bad in [999_999u64, note, 1] { |
| 2797 | let e = write(Some(bad)).unwrap_err(); |
| 2798 | assert!(e.contains("not a verified generation record"), "{bad}: {e}"); |
| 2799 | } |
| 2800 | assert_eq!(host_count(&b), before, "nothing was written"); |
| 2801 | // A real generation record is accepted, and none is accepted. |
| 2802 | let g = b |
| 2803 | .with_home(|home| crate::generation::write(home, &generation_json())) |
| 2804 | .unwrap(); |
| 2805 | let ok = write(Some(g)); |
| 2806 | assert!(ok.is_ok(), "{ok:?}"); |
| 2807 | let ok = write(None); |
| 2808 | assert!(ok.is_ok(), "{ok:?}"); |
| 2809 | } |
| 2810 | |
| 2811 | fn generation_json() -> Value { |
| 2812 | json!({"generation": 1, "v": 1, "model_sha256": "x"}) |
| 2813 | } |
| 2814 | |
| 2815 | fn host_count(b: &crate::compose::ComposeBridge) -> usize { |
| 2816 | match b.recall(&[], None) { |
| 2817 | ControlResponse::ComposeRecalled(r) => r.host.len(), |
| 2818 | other => panic!("{other:?}"), |
| 2819 | } |
| 2820 | } |
| 2821 | |
| 2822 | /// sovereign-core #408: records written before the objective fields load |
| 2823 | /// exactly as before (no objective), and the new fields are read back. |
| 2824 | #[test] |
| 2825 | fn objective_fields_are_additive_on_grants_and_intents() { |
| 2826 | let old = Ledger::from_records(&[grant(2, Value::Null), intent(3, 2)]).unwrap(); |
| 2827 | assert_eq!(old.grants[&2].objective, None); |
| 2828 | assert_eq!(old.intents[&3].objective_id, None); |
| 2829 | assert!(old.view()["intents"][0].get("objective_id").is_none()); |
| 2830 | let oid = "a".repeat(64); |
| 2831 | let mut g = json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", |
| 2832 | "path": "N.md", "content_sha256": "c", "approver": "drake", "target": "/w/N.md", |
| 2833 | "prior_sha256": null, "objective_id": oid, "objective_text_sha256": "b".repeat(64), |
| 2834 | "objective_record_sha256": "c".repeat(64)}); |
| 2835 | let mut i = json!({"phase": "intent", "tool": "write_file", "authorization": 2, |
| 2836 | "path": "N.md", "target": "/w/N.md", "content_sha256": "c", "prior_sha256": null, |
| 2837 | "proposal_sha256": "p", "executor": {"pid": 1, "start": 1}, "objective_id": oid}); |
| 2838 | let l = Ledger::from_records(&[ |
| 2839 | rec(2, "authorization", g.clone()), |
| 2840 | rec(3, "effect", i.clone()), |
| 2841 | ]) |
| 2842 | .unwrap(); |
| 2843 | let o = l.grants[&2].objective.as_ref().unwrap(); |
| 2844 | assert_eq!( |
| 2845 | (o.id.as_str(), o.text_sha256.as_str()), |
| 2846 | (oid.as_str(), "b".repeat(64).as_str()) |
| 2847 | ); |
| 2848 | assert_eq!(l.intents[&3].objective_id.as_deref(), Some(oid.as_str())); |
| 2849 | assert_eq!(l.view()["intents"][0]["objective_id"], json!(oid)); |
| 2850 | // A commit without the goal digest (written before #408) still loads. |
| 2851 | let c = rec( |
| 2852 | 1, |
| 2853 | "effect", |
| 2854 | json!({"compose_commit": 1, "task": 1, "cx_promotion": 1, |
| 2855 | "cx_evidence": 1, "proposal_sha256": "p", "path": "N.md", "content_sha256": "c", |
| 2856 | "workspace": "/w"}), |
| 2857 | ); |
| 2858 | assert_eq!( |
| 2859 | Ledger::from_records(&[c]).unwrap().commits[&1].goal_sha256, |
| 2860 | None |
| 2861 | ); |
| 2862 | // A daemon-written grant naming an objective without its digest is damaged state. |
| 2863 | g.as_object_mut().unwrap().remove("objective_text_sha256"); |
| 2864 | assert!(Ledger::from_records(&[rec(2, "authorization", g)]).is_err()); |
| 2865 | i["objective_id"] = json!(7); |
| 2866 | assert!(Ledger::from_records(&[grant(2, Value::Null), rec(3, "effect", i)]).is_err()); |
| 2867 | } |
| 2868 | |
| 2869 | #[test] |
| 2870 | fn fresh_grant_opens_once() { |
| 2871 | let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); |
| 2872 | assert_eq!(l.check_intent(&req(2), &None).unwrap().id, 2); |
| 2873 | let l = Ledger::from_records(&[grant(2, Value::Null), intent(3, 2)]).unwrap(); |
| 2874 | assert_eq!(refusal(&l, 2, None), "ReconciliationRequired"); |
| 2875 | } |
| 2876 | |
| 2877 | #[test] |
| 2878 | fn terminal_states_spend_the_grant() { |
| 2879 | for st in ["DONE", "NOT_DONE"] { |
| 2880 | let l = Ledger::from_records(&[ |
| 2881 | grant(2, Value::Null), |
| 2882 | intent(3, 2), |
| 2883 | settle(4, "ack", 3, st), |
| 2884 | ]) |
| 2885 | .unwrap(); |
| 2886 | assert_eq!(refusal(&l, 2, None), "AlreadySpent", "{st}"); |
| 2887 | } |
| 2888 | let l = Ledger::from_records(&[ |
| 2889 | grant(2, Value::Null), |
| 2890 | intent(3, 2), |
| 2891 | settle(4, "reconcile", 3, "UNRESOLVED"), |
| 2892 | ]) |
| 2893 | .unwrap(); |
| 2894 | assert_eq!(refusal(&l, 2, None), "ReconciliationRequired"); |
| 2895 | assert_eq!(l.intents[&3].unresolved_digest, Some(None)); |
| 2896 | } |
| 2897 | |
| 2898 | #[test] |
| 2899 | fn stop_resume_stale_and_revoke() { |
| 2900 | let stop = rec( |
| 2901 | 3, |
| 2902 | "authorization", |
| 2903 | json!({"control": "stop", "approver": "drake"}), |
| 2904 | ); |
| 2905 | let resume = rec( |
| 2906 | 4, |
| 2907 | "authorization", |
| 2908 | json!({"control": "resume", "approver": "drake"}), |
| 2909 | ); |
| 2910 | let l = Ledger::from_records(&[grant(2, Value::Null), stop.clone()]).unwrap(); |
| 2911 | assert_eq!(refusal(&l, 2, None), "Stopped"); |
| 2912 | let l = |
| 2913 | Ledger::from_records(&[grant(2, Value::Null), stop.clone(), resume.clone()]).unwrap(); |
| 2914 | assert_eq!(refusal(&l, 2, None), "Stale"); |
| 2915 | let l = Ledger::from_records(&[grant(2, Value::Null), stop, resume, grant(5, Value::Null)]) |
| 2916 | .unwrap(); |
| 2917 | assert!(l.check_intent(&req(5), &None).is_ok()); |
| 2918 | let revoke = rec( |
| 2919 | 3, |
| 2920 | "authorization", |
| 2921 | json!({"control": "revoke", "authorization": 2, "approver": "d"}), |
| 2922 | ); |
| 2923 | let l = Ledger::from_records(&[grant(2, Value::Null), revoke]).unwrap(); |
| 2924 | assert_eq!(refusal(&l, 2, None), "Revoked"); |
| 2925 | } |
| 2926 | |
| 2927 | #[test] |
| 2928 | fn a_caller_written_grant_is_never_honoured() { |
| 2929 | // Fields that would pass every other check; no marker, so no grant. |
| 2930 | let l = Ledger::from_records(&[caller_grant(2)]).unwrap(); |
| 2931 | let e = l.check_intent(&req(2), &None).unwrap_err(); |
| 2932 | assert_eq!(e.name, "NotAuthorized"); |
| 2933 | assert!(e.detail.contains("caller-written"), "{}", e.detail); |
| 2934 | // An intent it opened before the rule is never settled by the world. |
| 2935 | let l = Ledger::from_records(&[caller_grant(2), intent(3, 2)]).unwrap(); |
| 2936 | let (st, disk) = confined_world_state(&l, &l.intents[&3]); |
| 2937 | assert_eq!(st, EffectState::Unresolved); |
| 2938 | assert!(disk.unwrap_err().starts_with(NOT_DAEMON_MINTED)); |
| 2939 | // A minted grant with no compose-commit record behind it opens nothing. |
| 2940 | let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); |
| 2941 | let e = check_minted_backing(&l, &l.grants[&2]).unwrap_err(); |
| 2942 | assert!( |
| 2943 | e.detail.contains("no such compose-commit record"), |
| 2944 | "{}", |
| 2945 | e.detail |
| 2946 | ); |
| 2947 | } |
| 2948 | |
| 2949 | #[test] |
| 2950 | fn world_change_and_legacy_grants_are_stale() { |
| 2951 | let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); |
| 2952 | assert_eq!(refusal(&l, 2, Some("x")), "Stale"); |
| 2953 | let legacy = rec( |
| 2954 | 2, |
| 2955 | "authorization", |
| 2956 | json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", |
| 2957 | "path": "N.md", "content_sha256": "c", "approver": "d"}), |
| 2958 | ); |
| 2959 | let l = Ledger::from_records(&[legacy]).unwrap(); |
| 2960 | assert_eq!(refusal(&l, 2, None), "Stale"); |
| 2961 | let old = rec( |
| 2962 | 3, |
| 2963 | "effect", |
| 2964 | json!({"tool": "write_file", "authorization": 2, "success": true}), |
| 2965 | ); |
| 2966 | let l = Ledger::from_records(&[grant(2, Value::Null), old]).unwrap(); |
| 2967 | assert_eq!(refusal(&l, 2, None), "AlreadySpent"); |
| 2968 | } |
| 2969 | |
| 2970 | #[test] |
| 2971 | fn other_proposal_or_target_is_not_authorized() { |
| 2972 | let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); |
| 2973 | let mut r = req(2); |
| 2974 | r.content_sha256 = "other".into(); |
| 2975 | assert_eq!(l.check_intent(&r, &None).unwrap_err().name, "NotAuthorized"); |
| 2976 | let mut r = req(2); |
| 2977 | r.target = "/elsewhere".into(); |
| 2978 | assert_eq!(l.check_intent(&r, &None).unwrap_err().name, "NotAuthorized"); |
| 2979 | assert_eq!(refusal(&l, 9, None), "NotAuthorized"); |
| 2980 | } |
| 2981 | |
| 2982 | #[test] |
| 2983 | fn damaged_or_inconsistent_ledger_is_refused() { |
| 2984 | let mut bad = grant(2, Value::Null); |
| 2985 | bad.verified = false; |
| 2986 | assert_eq!( |
| 2987 | Ledger::from_records(&[bad]).unwrap_err().name, |
| 2988 | "CorruptLedger" |
| 2989 | ); |
| 2990 | let two = [grant(2, Value::Null), intent(3, 2), intent(4, 2)]; |
| 2991 | assert_eq!( |
| 2992 | Ledger::from_records(&two).unwrap_err().name, |
| 2993 | "CorruptLedger" |
| 2994 | ); |
| 2995 | let after = [ |
| 2996 | grant(2, Value::Null), |
| 2997 | intent(3, 2), |
| 2998 | settle(4, "ack", 3, "DONE"), |
| 2999 | settle(5, "reconcile", 3, "NOT_DONE"), |
| 3000 | ]; |
| 3001 | assert_eq!( |
| 3002 | Ledger::from_records(&after).unwrap_err().name, |
| 3003 | "CorruptLedger" |
| 3004 | ); |
| 3005 | let orphan = [settle(4, "ack", 3, "DONE")]; |
| 3006 | assert_eq!( |
| 3007 | Ledger::from_records(&orphan).unwrap_err().name, |
| 3008 | "CorruptLedger" |
| 3009 | ); |
| 3010 | } |
| 3011 | |
| 3012 | /// #267 red/green: a parent swapped for a symlink to a directory holding |
| 3013 | /// the expected bytes, exactly between confinement and the read, must not |
| 3014 | /// make the world check DONE. (Old code: confine_target, then read by |
| 3015 | /// path, reached the outside file and returned DONE.) |
| 3016 | #[test] |
| 3017 | fn swap_between_confinement_and_read_is_not_done() { |
| 3018 | let t = tempfile::tempdir().unwrap(); |
| 3019 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3020 | let (ws, outside) = (root.join("ws"), root.join("outside")); |
| 3021 | std::fs::create_dir_all(ws.join("d")).unwrap(); |
| 3022 | std::fs::create_dir_all(&outside).unwrap(); |
| 3023 | std::fs::write(ws.join("d/f"), b"inside").unwrap(); |
| 3024 | std::fs::write(outside.join("f"), b"expected").unwrap(); |
| 3025 | let l = race_ledger(&ws, b"expected"); |
| 3026 | let (w2, o2) = (ws.clone(), outside.clone()); |
| 3027 | test_hooks::set_pause(move || { |
| 3028 | std::fs::rename(w2.join("d"), w2.join("d.held")).unwrap(); |
| 3029 | std::os::unix::fs::symlink(&o2, w2.join("d")).unwrap(); |
| 3030 | }); |
| 3031 | let (st, disk) = confined_world_state(&l, &l.intents[&3]); |
| 3032 | assert_ne!(st, EffectState::Done, "read outside bytes: {disk:?}"); |
| 3033 | assert_eq!(st, EffectState::Unresolved); |
| 3034 | assert_eq!(disk.unwrap(), Some(hex(&Sha256::digest(b"inside")))); |
| 3035 | } |
| 3036 | |
| 3037 | /// #267 follow-up, grant creation: the REAL `write_approved_grant`, with the |
| 3038 | /// parent swapped for a symlink to a directory holding other bytes exactly |
| 3039 | /// between its confinement and its read. The grant must record the hash of |
| 3040 | /// the file confinement checked, and a `base` equal to that hash must |
| 3041 | /// still pass. (With the by-path read the recorded prior is the OUTSIDE |
| 3042 | /// hash and `base` is refused as BaseChanged.) |
| 3043 | #[test] |
| 3044 | fn write_approved_grant_records_the_prior_of_the_confined_file() { |
| 3045 | let _home = crate::home_guard::home_slot(); |
| 3046 | use crate::compose::{ComposeBridge, Generation}; |
| 3047 | if !aien_omega_compose::LINKED { |
| 3048 | eprintln!("NOT_RUN: stub compose build"); |
| 3049 | return; |
| 3050 | } |
| 3051 | let t = tempfile::tempdir().unwrap(); |
| 3052 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3053 | let (ws, outside) = (root.join("ws"), root.join("outside")); |
| 3054 | std::fs::create_dir_all(ws.join("d")).unwrap(); |
| 3055 | std::fs::create_dir_all(&outside).unwrap(); |
| 3056 | std::fs::write(ws.join("d/NOTES.md"), b"inside").unwrap(); |
| 3057 | std::fs::write(outside.join("NOTES.md"), b"expected").unwrap(); |
| 3058 | let proposer: crate::compose::ComposeProposer = |
| 3059 | std::sync::Arc::new(|_: &str, _: std::time::Duration| { |
| 3060 | Ok(Generation { |
| 3061 | text: "filename: d/NOTES.md\nkeep it\n".to_string(), |
| 3062 | tokens: 4, |
| 3063 | finish_reason: Some("eos".into()), |
| 3064 | ..Default::default() |
| 3065 | }) |
| 3066 | }); |
| 3067 | let b = ComposeBridge::new(root.join("compose"), proposer, "test:fixed"); |
| 3068 | let r = b.run_task("g", ws.to_str().unwrap()); |
| 3069 | let ControlResponse::ComposeTaskResult(rep) = r else { |
| 3070 | panic!("run_task did not produce a result: {r:?}") |
| 3071 | }; |
| 3072 | let cx = rep.cx_promotion; |
| 3073 | let link = ApprovedLink { |
| 3074 | approval_key: "k".into(), |
| 3075 | replay_claim: cx, |
| 3076 | cx_promotion: cx, |
| 3077 | cx_evidence: cx, |
| 3078 | }; |
| 3079 | let w = ws.to_str().unwrap(); |
| 3080 | let prior_of = |id: u64| -> Value { |
| 3081 | let ControlResponse::ComposeRecalled(r) = b.recall(&[id], None) else { |
| 3082 | panic!("recall failed") |
| 3083 | }; |
| 3084 | let v: Value = serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap(); |
| 3085 | v["prior_sha256"].clone() |
| 3086 | }; |
| 3087 | for base in [None, Some(hex(&Sha256::digest(b"inside")))] { |
| 3088 | let (w2, o2) = (ws.clone(), outside.clone()); |
| 3089 | test_hooks::set_pause(move || swap_in_symlink(&w2, &o2)); |
| 3090 | let r = write_approved_grant( |
| 3091 | &b, |
| 3092 | w, |
| 3093 | "d/NOTES.md", |
| 3094 | "c", |
| 3095 | "drake", |
| 3096 | &json!({}), |
| 3097 | &link, |
| 3098 | "p", |
| 3099 | base.as_deref(), |
| 3100 | ); |
| 3101 | let (id, _) = r.unwrap_or_else(|e| panic!("grant refused: {e}")); |
| 3102 | assert_eq!( |
| 3103 | prior_of(id), |
| 3104 | json!(hex(&Sha256::digest(b"inside"))), |
| 3105 | "the grant recorded bytes that confinement did not check" |
| 3106 | ); |
| 3107 | // put the directory back for the next round |
| 3108 | std::fs::remove_file(ws.join("d")).unwrap(); |
| 3109 | std::fs::rename(ws.join("d.held"), ws.join("d")).unwrap(); |
| 3110 | } |
| 3111 | } |
| 3112 | |
| 3113 | fn swap_in_symlink(ws: &Path, outside: &Path) { |
| 3114 | std::fs::rename(ws.join("d"), ws.join("d.held")).unwrap(); |
| 3115 | std::os::unix::fs::symlink(outside, ws.join("d")).unwrap(); |
| 3116 | } |
| 3117 | |
| 3118 | fn h(b: &[u8]) -> Option<String> { |
| 3119 | Some(hex(&Sha256::digest(b))) |
| 3120 | } |
| 3121 | |
| 3122 | /// Both the openat2 path and the forced ENOSYS fallback walk give the same |
| 3123 | /// exact refusal for every shape: a symlink in a middle component, a symlink |
| 3124 | /// to a file in a middle component (ELOOP) as against a plain file there |
| 3125 | /// (ENOTDIR), a symlink as the last component, a missing parent, and a |
| 3126 | /// `..` path. |
| 3127 | #[test] |
| 3128 | fn fallback_walk_refuses_symlinks_and_outside_paths() { |
| 3129 | let t = tempfile::tempdir().unwrap(); |
| 3130 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3131 | let (ws, outside) = (root.join("ws"), root.join("outside")); |
| 3132 | std::fs::create_dir_all(ws.join("a/b")).unwrap(); |
| 3133 | std::fs::create_dir_all(&outside).unwrap(); |
| 3134 | std::fs::write(outside.join("f"), b"expected").unwrap(); |
| 3135 | std::fs::write(ws.join("a/b/f"), b"inside").unwrap(); |
| 3136 | std::fs::write(ws.join("a/file"), b"plain file").unwrap(); |
| 3137 | std::os::unix::fs::symlink(&outside, ws.join("s")).unwrap(); |
| 3138 | std::os::unix::fs::symlink(&outside, ws.join("a/l")).unwrap(); |
| 3139 | std::os::unix::fs::symlink(outside.join("f"), ws.join("a/b/lf")).unwrap(); |
| 3140 | std::os::unix::fs::symlink(ws.join("a/file"), ws.join("a/lfile")).unwrap(); |
| 3141 | let w = ws.to_str().unwrap(); |
| 3142 | let open = |p: &str| open_confined(w, p, &ws.join(p).display().to_string()); |
| 3143 | for forced in [false, true] { |
| 3144 | test_hooks::set_force_fallback(forced); |
| 3145 | assert_eq!(open("a/b/f").unwrap().sha256().unwrap(), h(b"inside")); |
| 3146 | assert!(open("a/b/new").unwrap().file.is_none()); |
| 3147 | for (p, want) in [ |
| 3148 | ("s/f", "OutsideWorkspace"), // symlink to a dir, middle |
| 3149 | ("a/l/f", "OutsideWorkspace"), // same, deeper |
| 3150 | ("a/lfile/f", "OutsideWorkspace"), // symlink to a FILE, middle: ELOOP |
| 3151 | ("a/file/f", "OutsideWorkspace"), // plain file, middle: ENOTDIR |
| 3152 | ("a/b/lf", "NotRegular"), // symlink, last component |
| 3153 | ("s", "NotRegular"), // symlink, only component |
| 3154 | ("a/missing/f", "MissingParent"), |
| 3155 | ] { |
| 3156 | let e = open(p) |
| 3157 | .err() |
| 3158 | .unwrap_or_else(|| panic!("{p} was opened (forced={forced})")); |
| 3159 | assert_eq!(e.name, want, "{p} (forced={forced}): {}", e.detail); |
| 3160 | } |
| 3161 | let e = open_confined(w, "../outside/f", &format!("{w}/../outside/f")); |
| 3162 | assert_eq!(e.err().unwrap().name, "OutsideWorkspace"); |
| 3163 | } |
| 3164 | test_hooks::set_force_fallback(false); |
| 3165 | } |
| 3166 | |
| 3167 | /// Ledger with one daemon-minted grant for `ws` and one open intent |
| 3168 | /// (#3) writing `d/f` with content `want`. |
| 3169 | fn race_ledger(ws: &Path, want: &[u8]) -> Ledger { |
| 3170 | let target = ws.join("d/f").display().to_string(); |
| 3171 | let g = rec( |
| 3172 | 2, |
| 3173 | "authorization", |
| 3174 | json!({"minted_grant": 1, "compose_commit": 1, "proposal_sha256": "p", |
| 3175 | "path": "d/f", "content_sha256": hex(&Sha256::digest(want)), |
| 3176 | "approver": "drake", "target": target, "prior_sha256": null, |
| 3177 | "workspace": ws.display().to_string()}), |
| 3178 | ); |
| 3179 | let i = rec( |
| 3180 | 3, |
| 3181 | "effect", |
| 3182 | json!({"phase": "intent", "tool": "write_file", "authorization": 2, "path": "d/f", |
| 3183 | "target": target, "content_sha256": hex(&Sha256::digest(want)), |
| 3184 | "prior_sha256": null, "proposal_sha256": "p", |
| 3185 | "executor": {"pid": 1, "start": 1}}), |
| 3186 | ); |
| 3187 | Ledger::from_records(&[g, i]).unwrap() |
| 3188 | } |
| 3189 | |
| 3190 | /// #267, deterministic: after confinement hands back a held handle, a |
| 3191 | /// swap of the parent directory for a symlink to outside bytes cannot |
| 3192 | /// redirect the read; the handle still reads the inside object. |
| 3193 | #[test] |
| 3194 | fn held_handle_ignores_a_parent_swap() { |
| 3195 | let t = tempfile::tempdir().unwrap(); |
| 3196 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3197 | let (ws, outside) = (root.join("ws"), root.join("outside")); |
| 3198 | std::fs::create_dir_all(ws.join("d")).unwrap(); |
| 3199 | std::fs::create_dir_all(&outside).unwrap(); |
| 3200 | std::fs::write(ws.join("d/f"), b"inside").unwrap(); |
| 3201 | std::fs::write(outside.join("f"), b"outside").unwrap(); |
| 3202 | let target = ws.join("d/f").display().to_string(); |
| 3203 | let h = open_confined(ws.to_str().unwrap(), "d/f", &target).unwrap(); |
| 3204 | std::fs::rename(ws.join("d"), ws.join("d.held")).unwrap(); |
| 3205 | std::os::unix::fs::symlink(&outside, ws.join("d")).unwrap(); |
| 3206 | // By path the old code would now read the outside file ... |
| 3207 | assert_eq!( |
| 3208 | file_sha256(Path::new(&target)).unwrap(), |
| 3209 | Some(hex(&Sha256::digest(b"outside"))) |
| 3210 | ); |
| 3211 | // ... the held handle reads what confinement checked. |
| 3212 | assert_eq!(h.sha256().unwrap(), Some(hex(&Sha256::digest(b"inside")))); |
| 3213 | // A fresh walk refuses the swapped directory. |
| 3214 | let e = open_confined(ws.to_str().unwrap(), "d/f", &target) |
| 3215 | .err() |
| 3216 | .unwrap(); |
| 3217 | assert_eq!(e.name, "OutsideWorkspace"); |
| 3218 | } |
| 3219 | |
| 3220 | /// #267 acceptance: a parent directory swapped for a symlink to a |
| 3221 | /// directory holding the expected bytes, raced against ack/reconcile's |
| 3222 | /// `confined_world_state`, never yields DONE (the inside file differs). |
| 3223 | #[test] |
| 3224 | fn parent_swap_race_never_reads_outside_bytes() { |
| 3225 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3226 | let t = tempfile::tempdir().unwrap(); |
| 3227 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3228 | let (ws, outside) = (root.join("ws"), root.join("outside")); |
| 3229 | std::fs::create_dir_all(ws.join("d")).unwrap(); |
| 3230 | std::fs::create_dir_all(&outside).unwrap(); |
| 3231 | std::fs::write(ws.join("d/f"), b"inside").unwrap(); |
| 3232 | std::fs::write(outside.join("f"), b"expected").unwrap(); |
| 3233 | let l = race_ledger(&ws, b"expected"); |
| 3234 | let stop = std::sync::Arc::new(AtomicBool::new(false)); |
| 3235 | let swapper = { |
| 3236 | let (stop, ws, outside) = (stop.clone(), ws.clone(), outside.clone()); |
| 3237 | std::thread::spawn(move || { |
| 3238 | while !stop.load(Ordering::Relaxed) { |
| 3239 | // dir -> symlink to outside, then back. |
| 3240 | std::fs::rename(ws.join("d"), ws.join("d.held")).unwrap(); |
| 3241 | std::os::unix::fs::symlink(&outside, ws.join("d")).unwrap(); |
| 3242 | std::fs::remove_file(ws.join("d")).unwrap(); |
| 3243 | std::fs::rename(ws.join("d.held"), ws.join("d")).unwrap(); |
| 3244 | } |
| 3245 | }) |
| 3246 | }; |
| 3247 | let (mut done, mut seen) = (0u32, std::collections::BTreeMap::<String, u32>::new()); |
| 3248 | let end = std::time::Instant::now() + std::time::Duration::from_secs(8); |
| 3249 | while std::time::Instant::now() < end { |
| 3250 | let (st, disk) = confined_world_state(&l, &l.intents[&3]); |
| 3251 | if st == EffectState::Done { |
| 3252 | done += 1; |
| 3253 | } |
| 3254 | *seen |
| 3255 | .entry(format!("{} {:?}", st.name(), disk.is_ok())) |
| 3256 | .or_default() += 1; |
| 3257 | } |
| 3258 | stop.store(true, Ordering::Relaxed); |
| 3259 | swapper.join().unwrap(); |
| 3260 | assert_eq!(done, 0, "DONE for bytes outside the workspace: {seen:?}"); |
| 3261 | } |
| 3262 | #[test] |
| 3263 | fn world_state_reads_the_target() { |
| 3264 | let d = tempfile::tempdir().unwrap(); |
| 3265 | let t = d.path().join("N.md"); |
| 3266 | let c = hex(&Sha256::digest(b"new")); |
| 3267 | let mut row = IntentRow { |
| 3268 | id: 3, |
| 3269 | authorization: 2, |
| 3270 | path: "N.md".into(), |
| 3271 | target: t.display().to_string(), |
| 3272 | content_sha256: c.clone(), |
| 3273 | prior_sha256: None, |
| 3274 | executor_pid: 0, |
| 3275 | executor_start: 0, |
| 3276 | state: EffectState::Open, |
| 3277 | state_record: 0, |
| 3278 | unresolved_digest: None, |
| 3279 | objective_id: None, |
| 3280 | }; |
| 3281 | assert_eq!(world_state(&row).0, EffectState::NotDone); |
| 3282 | std::fs::write(&t, b"new").unwrap(); |
| 3283 | assert_eq!(world_state(&row).0, EffectState::Done); |
| 3284 | std::fs::write(&t, b"other").unwrap(); |
| 3285 | assert_eq!(world_state(&row).0, EffectState::Unresolved); |
| 3286 | row.prior_sha256 = Some(hex(&Sha256::digest(b"other"))); |
| 3287 | assert_eq!(world_state(&row).0, EffectState::NotDone); |
| 3288 | std::fs::remove_file(&t).unwrap(); |
| 3289 | std::fs::create_dir(&t).unwrap(); |
| 3290 | assert_eq!(world_state(&row).0, EffectState::Unresolved); |
| 3291 | } |
| 3292 | |
| 3293 | #[test] |
| 3294 | fn executor_liveness_uses_pid_and_start_time() { |
| 3295 | let (pid, start) = self_executor(); |
| 3296 | assert!(start > 0); |
| 3297 | assert!(executor_alive(pid, start)); |
| 3298 | assert!(!executor_alive(pid, start + 1)); |
| 3299 | assert!(!executor_alive(0, 0)); |
| 3300 | } |
| 3301 | |
| 3302 | #[test] |
| 3303 | fn reserved_records_cannot_be_forged_through_compose_note() { |
| 3304 | assert!(check_reserved_note("effect", r#"{"phase":"ack","intent":3}"#).is_err()); |
| 3305 | // #323: the NEXT-PHASE-1 spend note, with or without an authorization. |
| 3306 | let legacy = r#"{"tool":"write_file","authorization":2,"success":true}"#; |
| 3307 | assert!(check_reserved_note("effect", legacy).is_err()); |
| 3308 | assert!(check_reserved_note("effect", r#"{"tool":"write_file"}"#).is_err()); |
| 3309 | // The ledger still reads one from an old journal. |
| 3310 | let l = Ledger::from_records(&[ |
| 3311 | grant(2, Value::Null), |
| 3312 | rec(3, "effect", serde_json::from_str(legacy).unwrap()), |
| 3313 | ]) |
| 3314 | .unwrap(); |
| 3315 | assert_eq!(l.legacy_spent.get(&2), Some(&3)); |
| 3316 | assert!(check_reserved_note("authorization", r#"{"control":"resume"}"#).is_err()); |
| 3317 | assert!(check_reserved_note("effect", r#"{"tool":"inspect"}"#).is_ok()); |
| 3318 | assert!(check_reserved_note("constraint", "plain text").is_ok()); |
| 3319 | } |
| 3320 | |
| 3321 | #[test] |
| 3322 | fn grants_are_confined_and_the_approved_kind_is_reserved() { |
| 3323 | let t = tempfile::tempdir().unwrap(); |
| 3324 | let root = std::fs::canonicalize(t.path()).unwrap(); |
| 3325 | let ws = root.join("ws"); |
| 3326 | std::fs::create_dir_all(ws.join("d")).unwrap(); |
| 3327 | let w = ws.to_str().unwrap(); |
| 3328 | let tg = |p: &str| ws.join(p).display().to_string(); |
| 3329 | assert!(confine_target(w, "N.md", &tg("N.md")).is_ok()); |
| 3330 | assert!(confine_target(w, "d/N.md", &tg("d/N.md")).is_ok()); |
| 3331 | let out = |ws: &str, p: &str, t: &str| confine_target(ws, p, t).unwrap_err().name; |
| 3332 | assert_eq!(out(w, "N.md", "/etc/N.md"), "OutsideWorkspace"); |
| 3333 | assert_eq!(out(w, "../N.md", &tg("../N.md")), "OutsideWorkspace"); |
| 3334 | assert_eq!(out(w, "/etc/passwd", "/etc/passwd"), "OutsideWorkspace"); |
| 3335 | assert_eq!(out(w, "./N.md", &tg("./N.md")), "OutsideWorkspace"); |
| 3336 | assert_eq!(out(w, "", w), "OutsideWorkspace"); |
| 3337 | assert_eq!(out("/", "etc/passwd", "/etc/passwd"), "OutsideWorkspace"); |
| 3338 | assert_eq!(out("ws", "N.md", "ws/N.md"), "OutsideWorkspace"); |
| 3339 | assert_eq!( |
| 3340 | out(&format!("{w}/d/.."), "N.md", &format!("{w}/d/../N.md")), |
| 3341 | "OutsideWorkspace" |
| 3342 | ); |
| 3343 | std::os::unix::fs::symlink(&root, ws.join("up")).unwrap(); |
| 3344 | assert_eq!(out(w, "up/x", &tg("up/x")), "OutsideWorkspace"); |
| 3345 | std::os::unix::fs::symlink("/etc/hostname", ws.join("l")).unwrap(); |
| 3346 | assert_eq!(out(w, "l", &tg("l")), "OutsideWorkspace"); |
| 3347 | std::os::unix::fs::symlink(&ws, root.join("wl")).unwrap(); |
| 3348 | let wl = root.join("wl").display().to_string(); |
| 3349 | assert_eq!(out(&wl, "N.md", &format!("{wl}/N.md")), "OutsideWorkspace"); |
| 3350 | |
| 3351 | let g = |extra: Value| { |
| 3352 | let mut v = json!({"proposal_sha256": "p", "path": "N.md", "content_sha256": "c", |
| 3353 | "approver": "x", "target": tg("N.md"), "prior_sha256": null, "workspace": w}); |
| 3354 | for (k, x) in extra.as_object().unwrap() { |
| 3355 | v[k] = x.clone(); |
| 3356 | } |
| 3357 | v.to_string() |
| 3358 | }; |
| 3359 | // sovereign-core #261: every authorization note is refused, whatever it says. |
| 3360 | for text in [ |
| 3361 | g(json!({})), |
| 3362 | g(json!({"approved_grant": 1})), |
| 3363 | g(json!({"minted_grant": 1, "compose_commit": 1})), |
| 3364 | g(json!({"target": "/etc/N.md"})), |
| 3365 | json!({"control": "resume", "approver": "x"}).to_string(), |
| 3366 | "not json".to_string(), |
| 3367 | ] { |
| 3368 | let e = check_reserved_note("authorization", &text).unwrap_err(); |
| 3369 | assert!(e.contains("sovereign-core #261"), "{e}"); |
| 3370 | } |
| 3371 | assert!(check_reserved_note( |
| 3372 | "effect", |
| 3373 | &json!({"compose_commit": 1, "proposal_sha256": "p"}).to_string() |
| 3374 | ) |
| 3375 | .is_err()); |
| 3376 | |
| 3377 | // Approved grants (476ca4 c25): fields bound to the approval key, one per |
| 3378 | // claim, and a COMMITTED claim behind it. |
| 3379 | let rec = |id: u64, links: Vec<u64>, text: String| ComposeRecordView { |
| 3380 | links, |
| 3381 | ..super::tests::rec(id, "authorization", serde_json::from_str(&text).unwrap()) |
| 3382 | }; |
| 3383 | let ident = crate::approved_auth::ApprovalIdentity { |
| 3384 | trace_id: "t".into(), |
| 3385 | request_id: "r".into(), |
| 3386 | approval_id: "a".into(), |
| 3387 | approver: "x".into(), |
| 3388 | path: "N.md".into(), |
| 3389 | content_sha256: "c".into(), |
| 3390 | approved_proposal_sha256: "s".into(), |
| 3391 | desk_key_id: "k".into(), |
| 3392 | workspace: w.into(), |
| 3393 | }; |
| 3394 | let key = crate::approved_auth::approval_key(&ident); |
| 3395 | let approved = |extra: Value| { |
| 3396 | let mut e = json!({"approved_grant": 1, "approval_key": key, "replay_claim": 3, |
| 3397 | "cx_promotion": 1, "cx_evidence": 2, "trace_id": "t", "request_id": "r", |
| 3398 | "approval_id": "a", "approved_proposal_sha256": "s", "desk_key_id": "k"}); |
| 3399 | for (k, x) in extra.as_object().unwrap() { |
| 3400 | e[k] = x.clone(); |
| 3401 | } |
| 3402 | g(e) |
| 3403 | }; |
| 3404 | let why = |recs: &[ComposeRecordView], id: u64| { |
| 3405 | let l = Ledger::from_records(recs).unwrap(); |
| 3406 | let r = check_approved_backing(&l, &l.grants[&id], recs).unwrap_err(); |
| 3407 | assert_eq!(r.name, "NotAuthorized"); |
| 3408 | r.detail |
| 3409 | }; |
| 3410 | // Bound fields, no claim behind it. |
| 3411 | let one = rec(5, vec![1, 2, 3], approved(json!({}))); |
| 3412 | assert!(why(std::slice::from_ref(&one), 5).contains("no such replay claim")); |
| 3413 | // Path, content, target or ids not the ones the approval key binds. |
| 3414 | for bad in [ |
| 3415 | json!({"path": "O.md", "target": tg("O.md")}), |
| 3416 | json!({"content_sha256": "other"}), |
| 3417 | json!({"request_id": "r2"}), |
| 3418 | json!({"approval_key": "0".repeat(64)}), |
| 3419 | ] { |
| 3420 | let r = rec(5, vec![1, 2, 3], approved(bad.clone())); |
| 3421 | assert!( |
| 3422 | why(std::slice::from_ref(&r), 5).contains("not the bound approval"), |
| 3423 | "{bad}" |
| 3424 | ); |
| 3425 | } |
| 3426 | // A byte copy of the grant (same claim, same links): neither opens. |
| 3427 | let copy = rec(6, vec![1, 2, 3], approved(json!({}))); |
| 3428 | let both = [one.clone(), copy]; |
| 3429 | for id in [5, 6] { |
| 3430 | assert!(why(&both, id).contains("more than one approved grant")); |
| 3431 | } |
| 3432 | // A grant without the marker needs no backing; the approved one without |
| 3433 | // its fields is a corrupt ledger, not a generic grant. |
| 3434 | assert!(Ledger::from_records(&[rec(6, vec![], g(json!({"approved_grant": 1})))]).is_err()); |
| 3435 | } |
| 3436 | } |