//! Broker-controlled approval ledger for privileged plan execution. //! //! Plans are staged in per-user storage, which the reviewing user fully //! controls: they can replace a plan, recompute its seal, and delete the //! consumption marker. The privileged broker therefore keeps its own record of //! which approvals it has already consumed. //! //! The ledger lives in a root-owned directory (`/var/lib/phoebus/approvals`, //! 0700, records 0600) that the unprivileged user cannot write. //! //! ## Stable approval identity //! //! A record is keyed by [`approval_key`], derived from the random plan ID, the //! *canonical* approval digest (recomputed from the executable actions and the //! reviewed material effects), the initiating uid and the canonical target //! root. Presentation-only fields (summary, rationale, recommendations) are //! deliberately absent: editing them cannot mint a fresh ledger entry for an //! already-consumed approval. A newly reviewed identical operation gets a new //! random plan ID and is therefore allowed, while every replay of the original //! approval is refused. //! //! ## Monotonic, crash-safe terminal transitions //! //! A claim records the owning process identity (`pid`, process start time and //! boot id). The terminal status is published exactly once by atomically //! linking a fully written record into `.terminal`; the link fails if a //! terminal already exists, so a terminal status can never be overwritten or //! changed to another terminal status. Reconciliation only marks a record //! interrupted when its owner is provably gone (the pid no longer exists, the //! pid was reused by a different process, or the machine rebooted), so a live //! executor is never mistaken for a crashed one. //! //! The ledger is *not* a signature scheme and does not claim to be: the //! independently preserved digest supplied by the approval UI is what binds the //! human decision. The ledger anchors consumption so user-editable files cannot //! be used to replay or replace an approved plan. use std::io::Write; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use phoebus_executor::error::{ExecError, Result}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// Terminal states a consumed approval can reach. There is deliberately no /// "retry" transition: a plan whose approval was claimed is never automatically /// re-executed. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApprovalStatus { /// Claimed and executing. InProgress, /// Completed and verified. Consumed, /// The action or verification failed; completed steps are retained. Failed, /// The process died after claiming but before finishing. Interrupted, /// Claimed after the plan's TTL; recorded for truthful reporting. Expired, } impl ApprovalStatus { pub fn as_str(self) -> &'static str { match self { ApprovalStatus::InProgress => "in_progress", ApprovalStatus::Consumed => "consumed", ApprovalStatus::Failed => "failed", ApprovalStatus::Interrupted => "interrupted", ApprovalStatus::Expired => "expired", } } pub fn is_terminal(self) -> bool { !matches!(self, ApprovalStatus::InProgress) } } /// Identity of the process that claimed an approval, used to distinguish a live /// executor from a crashed one during reconciliation. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ProcessIdentity { pub pid: u32, /// The process start time (`/proc//stat` field 22), in clock ticks. pub start_ticks: u64, /// The kernel boot id, so a pid reused after a reboot is never mistaken for /// the same process. pub boot_id: String, } impl ProcessIdentity { /// Identity of the current process. pub fn current() -> Self { let pid = std::process::id(); let start_ticks = std::fs::read_to_string(format!("/proc/{pid}/stat")) .ok() .and_then(|s| parse_start_ticks(&s)) .unwrap_or(0); Self { pid, start_ticks, boot_id: boot_id(), } } /// Whether the owning process is still running. A missing `/proc` entry, a /// different start time (pid reuse) or a different boot id all mean the /// executor is gone. pub fn is_alive(&self) -> bool { let current_boot = boot_id(); if !self.boot_id.is_empty() && !current_boot.is_empty() && self.boot_id != current_boot { return false; } match std::fs::read_to_string(format!("/proc/{}/stat", self.pid)) { Ok(text) => match parse_start_ticks(&text) { // A start time of 0 means it could not be recorded; fall back to // "present" rather than mislabel a live process. Some(ticks) => self.start_ticks == 0 || ticks == self.start_ticks, None => true, }, Err(_) => false, } } } fn parse_start_ticks(stat: &str) -> Option { // The command name is parenthesised and may contain spaces or parentheses; // parse the fields after the last ')'. let close = stat.rfind(')')?; let rest = stat.get(close + 1..)?.trim_start(); let fields: Vec<&str> = rest.split_whitespace().collect(); // fields[0] is field 3 (state); starttime is field 22 -> index 19. fields.get(19).and_then(|s| s.parse::().ok()) } fn boot_id() -> String { std::fs::read_to_string("/proc/sys/kernel/random/boot_id") .map(|s| s.trim().to_string()) .unwrap_or_default() } /// The stable identity of an approval, independent of presentation fields. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ApprovalIdentity { /// The ledger key: a hex fingerprint over the fields below. pub key: String, pub plan_id: String, /// The canonical approval digest, independently recomputed at the /// privileged boundary. pub digest: String, pub initiator_uid: u32, pub target_root: String, pub expires_unix: u64, pub action_count: usize, } impl ApprovalIdentity { pub fn new( plan_id: impl Into, digest: impl Into, initiator_uid: u32, target_root: impl Into, expires_unix: u64, action_count: usize, ) -> Self { let plan_id = plan_id.into(); let digest = digest.into(); let target_root = target_root.into(); let key = approval_key(&plan_id, &digest, initiator_uid, &target_root); Self { key, plan_id, digest, initiator_uid, target_root, expires_unix, action_count, } } } /// Derive the stable ledger key. Deliberately excludes summary, rationale, /// recommendations, timestamps and the plan's self-consistency seal, all of /// which the reviewing user can edit and recompute. pub fn approval_key(plan_id: &str, digest: &str, initiator_uid: u32, target_root: &str) -> String { let mut hasher = Sha256::new(); hasher.update(b"phoebus-approval-key-v1\0"); hasher.update(plan_id.as_bytes()); hasher.update(b"\0"); hasher.update(digest.as_bytes()); hasher.update(b"\0"); hasher.update(initiator_uid.to_le_bytes()); hasher.update(b"\0"); hasher.update(target_root.as_bytes()); format!("{:x}", hasher.finalize()) } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ApprovalRecord { /// The stable [`approval_key`]. pub approval_key: String, pub plan_id: String, /// The canonical approval digest. pub digest: String, pub initiator_uid: u32, pub target_root: String, pub expires_unix: u64, pub created_unix: u64, #[serde(default)] pub finished_unix: u64, pub status: String, #[serde(default)] pub result: String, /// How many actions the approved plan contained, for truthful reporting. #[serde(default)] pub action_count: usize, /// The claiming process, when known (older records may lack it). #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option, } /// The outcome of a terminal transition. #[derive(Debug, Clone)] pub enum Finished { /// This call recorded the terminal status. Recorded, /// A terminal status already existed and was left unchanged. AlreadyTerminal(Box), } /// A guard proving this process claimed the approval. Dropping it does not /// release the claim: the durable record is the anti-replay anchor. #[derive(Debug)] pub struct ApprovalClaim { key: String, } impl ApprovalClaim { pub fn key(&self) -> &str { &self.key } } #[derive(Debug, Clone)] pub struct ApprovalLedger { dir: PathBuf, } impl ApprovalLedger { /// The broker's ledger. `PHOEBUS_APPROVALS_DIR` overrides the location for /// tests and for an installed system that relocates its state. `pkexec` /// strips unknown environment variables, so this is not user-controllable /// on the privileged path. pub fn for_broker() -> Self { if let Ok(dir) = std::env::var("PHOEBUS_APPROVALS_DIR") { return Self { dir: PathBuf::from(dir), }; } Self { dir: PathBuf::from("/var/lib/phoebus/approvals"), } } /// An explicit directory, for tests. pub fn with_dir(dir: impl Into) -> Self { Self { dir: dir.into() } } pub fn dir(&self) -> &Path { &self.dir } fn ensure_dir(&self) -> Result<()> { std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700)); } Ok(()) } fn valid_key(key: &str) -> bool { !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| b.is_ascii_hexdigit()) } fn main_path(&self, key: &str) -> Result { if !Self::valid_key(key) { return Err(ExecError::operation( "approval", "ledger path", "approval key is not a hex digest", )); } Ok(self.dir.join(format!("{key}.json"))) } fn terminal_path(&self, key: &str) -> Result { if !Self::valid_key(key) { return Err(ExecError::operation( "approval", "ledger path", "approval key is not a hex digest", )); } Ok(self.dir.join(format!("{key}.terminal"))) } /// Atomically claim an approval for execution. Fails if the key has already /// been claimed or terminated, which is what makes replay impossible after /// the user deletes their own plan and claim files. pub fn claim(&self, identity: &ApprovalIdentity) -> Result { self.claim_with_owner(identity, ProcessIdentity::current()) } /// Claim with an explicit owner identity (used by tests to simulate a live /// or an abandoned executor). pub fn claim_with_owner( &self, identity: &ApprovalIdentity, owner: ProcessIdentity, ) -> Result { self.ensure_dir()?; let path = self.main_path(&identity.key)?; // A terminal marker is authoritative: even if the main record was // removed (which the user cannot do to root-owned files), the approval // stays consumed. if self.terminal_path(&identity.key)?.exists() { let prior = self.get(&identity.key).unwrap_or(None); return Err(self.already_used(prior.as_ref())); } let record = ApprovalRecord { approval_key: identity.key.clone(), plan_id: identity.plan_id.clone(), digest: identity.digest.clone(), initiator_uid: identity.initiator_uid, target_root: identity.target_root.clone(), expires_unix: identity.expires_unix, created_unix: now_unix(), finished_unix: 0, status: ApprovalStatus::InProgress.as_str().to_string(), result: "in progress".into(), action_count: identity.action_count, owner: Some(owner), }; let text = serde_json::to_string_pretty(&record) .map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?; let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } match opts.open(&path) { Ok(mut file) => { file.write_all(text.as_bytes()) .and_then(|_| file.flush()) .and_then(|_| file.sync_all()) .map_err(|e| ExecError::io(path.clone(), e))?; Ok(ApprovalClaim { key: identity.key.clone(), }) } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { let prior = self.get(&identity.key).unwrap_or(None); Err(self.already_used(prior.as_ref())) } Err(e) => Err(ExecError::io(path, e)), } } fn already_used(&self, prior: Option<&ApprovalRecord>) -> ExecError { let detail = prior .map(|r| format!("{} ({})", r.status, r.result)) .unwrap_or_else(|| "already claimed".to_string()); ExecError::operation( "approval", "claim", format!( "this approval was already used: {detail}; re-run the workflow to review a \ fresh plan instead of repeating a mutation" ), ) } /// Record the terminal status of a claimed approval. The transition is /// atomic and monotonic: the first terminal status wins and can never be /// overwritten or changed to another terminal status. pub fn finish(&self, key: &str, status: ApprovalStatus, result: &str) -> Result { if !status.is_terminal() { return Err(ExecError::operation( "approval", "finish", "finish requires a terminal status", )); } self.ensure_dir()?; let main = self.main_path(key)?; let terminal = self.terminal_path(key)?; // Read the current state. If it is already terminal, leave it untouched. let mut record = match self.get(key)? { Some(record) => record, None => { return Err(ExecError::operation( "approval", "finish", "no approval record to finish", )) } }; if record.status != ApprovalStatus::InProgress.as_str() { return Ok(Finished::AlreadyTerminal(Box::new(record))); } record.status = status.as_str().to_string(); record.result = result.to_string(); record.finished_unix = now_unix(); let text = serde_json::to_string_pretty(&record) .map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?; // Write a fully formed record to a unique temp file, then publish it // with an atomic hard link that fails if a terminal already exists. let tmp = self .dir .join(format!(".{key}.{}.terminal.tmp", std::process::id())); { let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } let mut fh = match opts.open(&tmp) { Ok(fh) => fh, Err(e) => return Err(ExecError::io(tmp.clone(), e)), }; fh.write_all(text.as_bytes()) .and_then(|_| fh.flush()) .and_then(|_| fh.sync_all()) .map_err(|e| ExecError::io(tmp.clone(), e))?; } match std::fs::hard_link(&tmp, &terminal) { Ok(()) => { let _ = std::fs::remove_file(&tmp); // Mirror the terminal state into the main record (best effort; // the terminal marker is authoritative). let _ = write_atomic(&main, text.as_bytes()); Ok(Finished::Recorded) } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { let _ = std::fs::remove_file(&tmp); match self.get(key)? { Some(existing) => Ok(Finished::AlreadyTerminal(Box::new(existing))), None => Err(ExecError::io(terminal, e)), } } Err(e) => { let _ = std::fs::remove_file(&tmp); Err(ExecError::io(terminal, e)) } } } /// Read a record. The terminal marker is authoritative when present. An /// invalid key simply has no record. pub fn get(&self, key: &str) -> Result> { if !Self::valid_key(key) { return Ok(None); } if let Some(record) = self.read_terminal(key)? { return Ok(Some(record)); } if let Some(record) = self.read_main(key)? { return Ok(Some(record)); } Ok(None) } fn read_terminal(&self, key: &str) -> Result> { let path = self.terminal_path(key)?; self.read_record(&path) } fn read_main(&self, key: &str) -> Result> { let path = self.main_path(key)?; self.read_record(&path) } fn read_record(&self, path: &Path) -> Result> { if !path.is_file() { return Ok(None); } let text = std::fs::read_to_string(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?; let record = serde_json::from_str(&text) .map_err(|e| ExecError::operation("approval", "deserialize", e.to_string()))?; Ok(Some(record)) } /// Reconcile approvals whose owner is provably gone. A live executor is /// never touched: a record is only marked interrupted when its owning /// process no longer exists (or the machine rebooted). The transition uses /// the same atomic terminal publication as [`finish`], so it cannot /// overwrite a real terminal result. pub fn reconcile_interrupted(&self) -> Result { if !self.dir.is_dir() { return Ok(0); } let entries = std::fs::read_dir(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?; let mut reconciled = 0; for entry in entries.flatten() { let path = entry.path(); if path.extension().and_then(|e| e.to_str()) != Some("json") { continue; } let Some(key) = path.file_stem().and_then(|s| s.to_str()) else { continue; }; if !Self::valid_key(key) { continue; } // Already terminal. if self.terminal_path(key)?.exists() { continue; } let Ok(Some(record)) = self.read_main(key) else { continue; }; if record.status != ApprovalStatus::InProgress.as_str() { continue; } // Only reconcile when the owner is provably gone. if record .owner .as_ref() .map(|owner| owner.is_alive()) .unwrap_or(false) { continue; } if let Ok(Finished::Recorded) = self.finish( key, ApprovalStatus::Interrupted, "the executing process ended before completing", ) { reconciled += 1; } } Ok(reconciled) } } /// Atomically replace `path` with `bytes` (temp file + rename). Best effort. fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { let dir = path.parent().unwrap_or_else(|| Path::new(".")); let tmp = dir.join(format!(".{}.{}.tmp", std::process::id(), now_unix())); { let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } let mut fh = opts.open(&tmp)?; fh.write_all(bytes)?; fh.flush()?; fh.sync_all()?; } match std::fs::rename(&tmp, path) { Ok(()) => Ok(()), Err(e) => { let _ = std::fs::remove_file(&tmp); Err(e) } } } fn now_unix() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } /// Resolve the authenticated caller of a privileged broker invocation. /// /// `pkexec` sets `PKEXEC_UID` to the uid of the process that requested /// elevation; that is the authoritative initiator. The `--plan-uid` argument is /// treated as untrusted input and only consulted when the broker already runs /// as root for an internal (non-Polkit) invocation. pub fn broker_initiator_uid( explicit_plan_uid: Option, effective_ground_uid: u32, ) -> Result { if let Ok(value) = std::env::var("PKEXEC_UID") { if let Ok(uid) = value.trim().parse::() { return Ok(uid); } return Err(ExecError::operation( "approval", "caller identity", "PKEXEC_UID was not a valid uid; refusing to execute", )); } if effective_ground_uid == 0 { if let Some(uid) = explicit_plan_uid { return Ok(uid); } return Err(ExecError::operation( "approval", "caller identity", "--execute-plan requires the initiating uid (--plan-uid) when no authenticated \ PKEXEC_UID context is present", )); } Err(ExecError::operation( "approval", "caller identity", "cannot establish the authenticated caller; refusing privileged execution", )) } #[cfg(test)] mod tests { use super::*; use tempfile::tempdir; fn identity() -> ApprovalIdentity { ApprovalIdentity::new("plan-a", "digest-a", 1000, "/", 9999999999, 1) } fn dead_owner() -> ProcessIdentity { ProcessIdentity { pid: u32::MAX, start_ticks: 1, boot_id: boot_id(), } } #[test] fn a_claim_can_only_be_taken_once() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let _claim = ledger.claim(&id).unwrap(); let err = ledger.claim(&id).unwrap_err(); assert!(err.to_string().contains("already used"), "{err}"); } #[test] fn concurrent_claims_allow_at_most_one_execution() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let handles: Vec<_> = (0..8) .map(|_| { let ledger = ledger.clone(); let id = id.clone(); std::thread::spawn(move || ledger.claim(&id).is_ok()) }) .collect(); let successes = handles .into_iter() .map(|h| h.join().expect("claim thread panicked")) .filter(|won| *won) .count(); assert_eq!(successes, 1, "exactly one claim may win"); } #[test] fn finish_records_a_terminal_status_and_retains_the_record() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let claim = ledger.claim(&id).unwrap(); let finished = ledger .finish(claim.key(), ApprovalStatus::Consumed, "ok") .unwrap(); assert!(matches!(finished, Finished::Recorded)); let record = ledger.get(&id.key).unwrap().unwrap(); assert_eq!(record.status, "consumed"); } #[test] fn terminal_status_is_monotonic_and_cannot_be_overwritten() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let claim = ledger.claim(&id).unwrap(); ledger .finish(claim.key(), ApprovalStatus::Consumed, "ok") .unwrap(); // A second, conflicting terminal transition must be refused and must // not change the recorded status. let second = ledger .finish(claim.key(), ApprovalStatus::Failed, "boom") .unwrap(); assert!(matches!(second, Finished::AlreadyTerminal(ref r) if r.status == "consumed")); assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "consumed"); } #[test] fn a_live_operation_is_not_reconciled() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); // The current process owns this claim and is running. let _claim = ledger.claim(&id).unwrap(); assert_eq!(ledger.reconcile_interrupted().unwrap(), 0); assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "in_progress"); } #[test] fn a_genuinely_abandoned_operation_is_recovered() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let _claim = ledger.claim_with_owner(&id, dead_owner()).unwrap(); assert_eq!(ledger.reconcile_interrupted().unwrap(), 1); assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "interrupted"); // And it cannot be retried. assert!(ledger.claim(&id).is_err()); } #[test] fn reconciliation_racing_completion_yields_exactly_one_stable_terminal() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let _claim = ledger.claim_with_owner(&id, dead_owner()).unwrap(); let reconciler = { let ledger = ledger.clone(); std::thread::spawn(move || ledger.reconcile_interrupted().is_ok()) }; let finisher = { let ledger = ledger.clone(); let key = id.key.clone(); std::thread::spawn(move || ledger.finish(&key, ApprovalStatus::Consumed, "ok").is_ok()) }; reconciler.join().unwrap(); finisher.join().unwrap(); let first = ledger.get(&id.key).unwrap().unwrap(); assert!(ApprovalStatus::Consumed.is_terminal()); // Whatever won, the status is terminal and stable under a later finish. let later = ledger .finish(&id.key, ApprovalStatus::Failed, "late") .unwrap(); assert!(matches!(later, Finished::AlreadyTerminal(_))); let second = ledger.get(&id.key).unwrap().unwrap(); assert_eq!( first.status, second.status, "terminal status must not change" ); assert!(second.status == "consumed" || second.status == "interrupted"); } #[test] fn a_replay_is_refused_even_after_the_user_plan_files_are_gone() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); let id = identity(); let claim = ledger.claim(&id).unwrap(); ledger .finish(claim.key(), ApprovalStatus::Consumed, "ok") .unwrap(); assert!(ledger.claim(&id).is_err()); } #[test] fn the_key_ignores_presentation_fields_but_changes_with_identity() { // Same id/digest/uid/root -> same key regardless of anything else. assert_eq!( approval_key("plan-a", "d", 1000, "/"), approval_key("plan-a", "d", 1000, "/") ); // A new plan id is a new approval. assert_ne!( approval_key("plan-a", "d", 1000, "/"), approval_key("plan-b", "d", 1000, "/") ); // A different digest, user or root is a different approval. assert_ne!( approval_key("plan-a", "d", 1000, "/"), approval_key("plan-a", "e", 1000, "/") ); assert_ne!( approval_key("plan-a", "d", 1000, "/"), approval_key("plan-a", "d", 1001, "/") ); assert_ne!( approval_key("plan-a", "d", 1000, "/"), approval_key("plan-a", "d", 1000, "/alt") ); } #[test] fn rejects_non_hex_keys() { let dir = tempdir().unwrap(); let ledger = ApprovalLedger::with_dir(dir.path()); assert!(ledger.get("../escape").unwrap().is_none()); assert!(ledger .finish("not-a-hash", ApprovalStatus::Consumed, "x") .is_err()); } }