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-cli / src / approval.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 | //! Approval floors ordered above every mode (sc#667). |
| 17 | //! |
| 18 | //! One ordering rule the chat loop cannot skip. For every tool request: |
| 19 | //! |
| 20 | //! 1. **Floors**, unconditional in every mode including `yolo` and `off`: |
| 21 | //! a hardline command list, deletion or rewrite of the runtime's own files |
| 22 | //! (binary, approval policy, checkpoint store, session journals), `sudo` |
| 23 | //! fed a password through stdin, and the operator's own deny patterns. |
| 24 | //! 2. **Policy deny** from the existing nine-tier `SafetyEngine` (confinement, |
| 25 | //! vault rules). A mode loosens questions, never a denial. |
| 26 | //! 3. **Mode**: `yolo` and `off` allow what is left. |
| 27 | //! 4. **Permanent allowlist** from the operator's policy file. |
| 28 | //! 5. **Presence**: with no person present, anything that still needs a |
| 29 | //! decision is denied (unattended defaults to deny). |
| 30 | //! 6. **Dangerous patterns** and the engine's own questions decide whether a |
| 31 | //! decision is needed at all. |
| 32 | //! 7. **Decision**: in `smart` mode a guardian model may deny or escalate. |
| 33 | //! It is never the final allow. Escalate, approve, and failure all go to |
| 34 | //! the person. Otherwise the person is asked directly. |
| 35 | //! |
| 36 | //! The functions in the pure section take values and return values: no |
| 37 | //! clock, disk, environment or terminal. The edges (policy file, presence, |
| 38 | //! runtime paths, the prompt and the guardian model) sit at the bottom and in |
| 39 | //! `tools.rs`, so the pure part can move to Omega as a semantic identity |
| 40 | //! (ADR 0024). |
| 41 | //! |
| 42 | //! Prior art: Hermes Agent, Nous Research, MIT licence, commit 5480918 |
| 43 | //! (read 2026-10-18), `tools/approval_floors.py`, `tools/approval.py`, |
| 44 | //! `tools/approval_smart.py`. Mechanism re-implemented from reading; no code |
| 45 | //! copied. |
| 46 | |
| 47 | use regex::Regex; |
| 48 | use serde::{Deserialize, Serialize}; |
| 49 | use serde_json::Value; |
| 50 | use std::path::{Component, Path, PathBuf}; |
| 51 | |
| 52 | use crate::safety::{is_high_risk_command, is_high_risk_path, SafetyDecision}; |
| 53 | |
| 54 | // --------------------------------------------------------------------------- |
| 55 | // Pure part |
| 56 | // --------------------------------------------------------------------------- |
| 57 | |
| 58 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 59 | #[serde(rename_all = "lowercase")] |
| 60 | pub enum ApprovalMode { |
| 61 | /// Ask the person whenever a decision is needed (the default). |
| 62 | Manual, |
| 63 | /// Ask the guardian model first; it may approve, deny or escalate. |
| 64 | Smart, |
| 65 | /// Approve everything the floors and the policy denials leave. |
| 66 | Yolo, |
| 67 | /// Approvals switched off; same effect as `Yolo`. Floors still hold. |
| 68 | Off, |
| 69 | } |
| 70 | |
| 71 | #[cfg(test)] |
| 72 | pub const ALL_MODES: [ApprovalMode; 4] = [ |
| 73 | ApprovalMode::Manual, |
| 74 | ApprovalMode::Smart, |
| 75 | ApprovalMode::Yolo, |
| 76 | ApprovalMode::Off, |
| 77 | ]; |
| 78 | |
| 79 | impl ApprovalMode { |
| 80 | pub fn parse(text: &str) -> Option<Self> { |
| 81 | match text.trim().to_ascii_lowercase().as_str() { |
| 82 | "manual" | "ask" => Some(Self::Manual), |
| 83 | "smart" | "guardian" => Some(Self::Smart), |
| 84 | "yolo" => Some(Self::Yolo), |
| 85 | "off" => Some(Self::Off), |
| 86 | _ => None, |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 92 | pub enum Presence { |
| 93 | Person, |
| 94 | Unattended, |
| 95 | } |
| 96 | |
| 97 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 98 | pub enum Floor { |
| 99 | Hardline, |
| 100 | RuntimeSelfDelete, |
| 101 | SudoPipedPassword, |
| 102 | OperatorDeny, |
| 103 | } |
| 104 | |
| 105 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 106 | pub enum Stage { |
| 107 | Floor(Floor), |
| 108 | PolicyDeny, |
| 109 | Mode, |
| 110 | Allowlist, |
| 111 | Presence, |
| 112 | Clear, |
| 113 | Guardian, |
| 114 | } |
| 115 | |
| 116 | #[derive(Debug, Clone, PartialEq)] |
| 117 | pub enum Verdict { |
| 118 | Allow { |
| 119 | by: Stage, |
| 120 | }, |
| 121 | Deny { |
| 122 | by: Stage, |
| 123 | reason: String, |
| 124 | }, |
| 125 | /// Smart mode with a closed breaker: the edge asks the guardian, then |
| 126 | /// calls [`after_guardian`]. |
| 127 | AskGuardian { |
| 128 | reason: String, |
| 129 | }, |
| 130 | AskPerson { |
| 131 | reason: String, |
| 132 | }, |
| 133 | } |
| 134 | |
| 135 | /// The operator's policy file as written on disk. |
| 136 | #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] |
| 137 | pub struct OperatorPolicy { |
| 138 | #[serde(default)] |
| 139 | pub mode: Option<ApprovalMode>, |
| 140 | /// Regular expressions; a match on the request's subject denies it in |
| 141 | /// every mode. |
| 142 | #[serde(default)] |
| 143 | pub deny: Vec<String>, |
| 144 | /// Regular expressions; a match skips the question (never a floor). |
| 145 | #[serde(default)] |
| 146 | pub allow: Vec<String>, |
| 147 | } |
| 148 | |
| 149 | /// Compiled policy. Fail closed: a deny pattern that does not compile, or a |
| 150 | /// policy file that does not parse, denies every request with the reason. |
| 151 | #[derive(Debug, Clone, Default)] |
| 152 | pub struct CompiledPolicy { |
| 153 | /// Parsed from the policy file and not consulted. The process mode is the |
| 154 | /// CLI flag or `AIEN_APPROVAL_MODE`, fixed at startup. |
| 155 | #[allow(dead_code)] |
| 156 | pub mode: Option<ApprovalMode>, |
| 157 | deny: Vec<Regex>, |
| 158 | allow: Vec<Regex>, |
| 159 | broken: Option<String>, |
| 160 | pub warnings: Vec<String>, |
| 161 | } |
| 162 | |
| 163 | impl CompiledPolicy { |
| 164 | pub fn compile(policy: &OperatorPolicy) -> Self { |
| 165 | let mut out = CompiledPolicy { |
| 166 | mode: policy.mode, |
| 167 | ..Default::default() |
| 168 | }; |
| 169 | for (i, pattern) in policy.deny.iter().enumerate() { |
| 170 | match Regex::new(pattern) { |
| 171 | Ok(re) => out.deny.push(re), |
| 172 | Err(err) => { |
| 173 | out.broken = Some(format!( |
| 174 | "operator deny pattern {} ({:?}) does not compile: {}", |
| 175 | i + 1, |
| 176 | pattern, |
| 177 | err |
| 178 | )); |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | for (i, pattern) in policy.allow.iter().enumerate() { |
| 183 | match Regex::new(pattern) { |
| 184 | Ok(re) => out.allow.push(re), |
| 185 | // An allow pattern that does not compile grants nothing. |
| 186 | Err(err) => out.warnings.push(format!( |
| 187 | "operator allow pattern {} ({:?}) ignored: {}", |
| 188 | i + 1, |
| 189 | pattern, |
| 190 | err |
| 191 | )), |
| 192 | } |
| 193 | } |
| 194 | out |
| 195 | } |
| 196 | |
| 197 | /// Why every request is being denied, when the policy is broken. |
| 198 | pub fn broken(&self) -> Option<&str> { |
| 199 | self.broken.as_deref() |
| 200 | } |
| 201 | |
| 202 | /// The policy file exists but cannot be read or parsed. |
| 203 | pub fn unreadable(reason: String) -> Self { |
| 204 | CompiledPolicy { |
| 205 | broken: Some(format!("approval policy unreadable: {}", reason)), |
| 206 | ..Default::default() |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Values the edge measures once per session. |
| 212 | #[derive(Debug, Clone, Default)] |
| 213 | pub struct RuntimeFacts { |
| 214 | /// Files and directories the agent must never delete or rewrite. |
| 215 | pub protected: Vec<PathBuf>, |
| 216 | /// Expansion for `~` and `$HOME` in commands. |
| 217 | pub home: PathBuf, |
| 218 | /// Base for relative paths when a request names no `cwd`. |
| 219 | pub cwd: PathBuf, |
| 220 | } |
| 221 | |
| 222 | /// One tool request at the gate. |
| 223 | pub struct Gate<'a> { |
| 224 | pub tool: &'a str, |
| 225 | pub args: &'a Value, |
| 226 | /// What the existing nine-tier `SafetyEngine` said. |
| 227 | pub base: &'a SafetyDecision, |
| 228 | pub mode: ApprovalMode, |
| 229 | pub presence: Presence, |
| 230 | pub policy: &'a CompiledPolicy, |
| 231 | pub facts: &'a RuntimeFacts, |
| 232 | /// A guardian is configured and its breaker is closed. |
| 233 | pub guardian_ready: bool, |
| 234 | } |
| 235 | |
| 236 | /// The ordering rule. Floors first, every mode. A person-required action |
| 237 | /// never skips a floor. |
| 238 | pub fn decide(gate: &Gate) -> Verdict { |
| 239 | if let Some((floor, reason)) = check_floors(gate.tool, gate.args, gate.policy, gate.facts) { |
| 240 | return Verdict::Deny { |
| 241 | by: Stage::Floor(floor), |
| 242 | reason, |
| 243 | }; |
| 244 | } |
| 245 | if let SafetyDecision::Deny(reason) = gate.base { |
| 246 | return Verdict::Deny { |
| 247 | by: Stage::PolicyDeny, |
| 248 | reason: reason.clone(), |
| 249 | }; |
| 250 | } |
| 251 | if let Some(reason) = requires_person(gate.tool, gate.args) { |
| 252 | if gate.presence == Presence::Unattended { |
| 253 | return Verdict::Deny { |
| 254 | by: Stage::Presence, |
| 255 | reason: format!("person required, unattended default is deny: {reason}"), |
| 256 | }; |
| 257 | } |
| 258 | return Verdict::AskPerson { reason }; |
| 259 | } |
| 260 | if matches!(gate.mode, ApprovalMode::Yolo | ApprovalMode::Off) { |
| 261 | // `run_command` is executed by `bash -c`. Yolo and off do not waive that. |
| 262 | if gate.tool == "run_command" { |
| 263 | if gate.presence == Presence::Unattended { |
| 264 | return Verdict::Deny { |
| 265 | by: Stage::Presence, |
| 266 | reason: "run_command requires the person, unattended default is deny".into(), |
| 267 | }; |
| 268 | } |
| 269 | return Verdict::AskPerson { |
| 270 | reason: "run_command requires the person".into(), |
| 271 | }; |
| 272 | } |
| 273 | return Verdict::Allow { by: Stage::Mode }; |
| 274 | } |
| 275 | let subject = subject(gate.tool, gate.args); |
| 276 | if gate |
| 277 | .policy |
| 278 | .allow |
| 279 | .iter() |
| 280 | .any(|re| matches_subject(re, &subject)) |
| 281 | { |
| 282 | return Verdict::Allow { |
| 283 | by: Stage::Allowlist, |
| 284 | }; |
| 285 | } |
| 286 | let reason = match needs_decision(gate.tool, gate.args, gate.base) { |
| 287 | None => return Verdict::Allow { by: Stage::Clear }, |
| 288 | Some(reason) => reason, |
| 289 | }; |
| 290 | if gate.presence == Presence::Unattended { |
| 291 | return Verdict::Deny { |
| 292 | by: Stage::Presence, |
| 293 | reason: format!("no person present to approve, unattended default is deny: {reason}"), |
| 294 | }; |
| 295 | } |
| 296 | if gate.mode == ApprovalMode::Smart && gate.guardian_ready { |
| 297 | return Verdict::AskGuardian { reason }; |
| 298 | } |
| 299 | Verdict::AskPerson { reason } |
| 300 | } |
| 301 | |
| 302 | /// What the guardian model answered. |
| 303 | #[derive(Debug, Clone, PartialEq)] |
| 304 | pub enum GuardianAnswer { |
| 305 | Approve, |
| 306 | Deny(String), |
| 307 | Escalate, |
| 308 | /// Timeout, transport error or an answer that did not parse. |
| 309 | Failed(String), |
| 310 | } |
| 311 | |
| 312 | /// Second half of [`decide`] after an `AskGuardian` verdict. |
| 313 | pub fn after_guardian(answer: &GuardianAnswer, reason: String) -> Verdict { |
| 314 | match answer { |
| 315 | // The guardian may deny or escalate. An approve is an escalation: |
| 316 | // the person is the only final allow. |
| 317 | GuardianAnswer::Deny(why) => Verdict::Deny { |
| 318 | by: Stage::Guardian, |
| 319 | reason: format!("guardian denied: {why}"), |
| 320 | }, |
| 321 | GuardianAnswer::Approve | GuardianAnswer::Escalate | GuardianAnswer::Failed(_) => { |
| 322 | Verdict::AskPerson { reason } |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// Actions that stay with the person in every mode, including `yolo` and `off`. |
| 328 | /// Floors are decided first. This does not waive a floor. |
| 329 | pub fn requires_person(tool: &str, args: &Value) -> Option<String> { |
| 330 | let action = args.get("action").and_then(Value::as_str).unwrap_or(""); |
| 331 | if tool == "sandbox" && action == "promote" { |
| 332 | return Some("sandbox promote requires the person".into()); |
| 333 | } |
| 334 | if matches!(tool, "skill" | "skills") && action == "optimize" { |
| 335 | return Some("skill optimize requires the person".into()); |
| 336 | } |
| 337 | None |
| 338 | } |
| 339 | |
| 340 | /// Where a shell word lands relative to a protected path. The word is |
| 341 | /// brace-expanded, resolved against the command's own working directory, and |
| 342 | /// matched one path component at a time with `*`, `?` and `[...]`. |
| 343 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 344 | enum Cover { |
| 345 | None, |
| 346 | /// The word names the protected path or something inside it. |
| 347 | Inside, |
| 348 | /// The word names a parent of the protected path. |
| 349 | Parent, |
| 350 | } |
| 351 | |
| 352 | fn word_covers(word: &str, protected: &Path, home: &Path, base: &Path) -> Cover { |
| 353 | let mut best = Cover::None; |
| 354 | for alt in expand_braces(word) { |
| 355 | let abs = lexical_abs(&alt, home, base); |
| 356 | let want: Vec<_> = protected.components().collect(); |
| 357 | let got: Vec<_> = abs.components().collect(); |
| 358 | let matched = want.iter().zip(&got).all(|(w, g)| { |
| 359 | match (w.as_os_str().to_str(), g.as_os_str().to_str()) { |
| 360 | (Some(w), Some(g)) => glob_match(g, w), |
| 361 | _ => w == g, |
| 362 | } |
| 363 | }); |
| 364 | if !matched || got.is_empty() { |
| 365 | continue; |
| 366 | } |
| 367 | if got.len() >= want.len() { |
| 368 | return Cover::Inside; |
| 369 | } |
| 370 | best = Cover::Parent; |
| 371 | } |
| 372 | best |
| 373 | } |
| 374 | |
| 375 | /// Bash brace expansion of `a{b,c}d` forms, nested, capped at 256 words. |
| 376 | fn expand_braces(word: &str) -> Vec<String> { |
| 377 | const CAP: usize = 256; |
| 378 | let bytes = word.as_bytes(); |
| 379 | let Some(open) = bytes.iter().position(|&b| b == b'{') else { |
| 380 | return vec![word.to_string()]; |
| 381 | }; |
| 382 | let mut depth = 0usize; |
| 383 | let mut commas = Vec::new(); |
| 384 | let mut close = None; |
| 385 | for (i, &b) in bytes.iter().enumerate().skip(open) { |
| 386 | match b { |
| 387 | b'{' => depth += 1, |
| 388 | b'}' => { |
| 389 | depth -= 1; |
| 390 | if depth == 0 { |
| 391 | close = Some(i); |
| 392 | break; |
| 393 | } |
| 394 | } |
| 395 | b',' if depth == 1 => commas.push(i), |
| 396 | _ => {} |
| 397 | } |
| 398 | } |
| 399 | let (Some(close), false) = (close, commas.is_empty()) else { |
| 400 | // No list inside: the braces are literal; expand what follows. |
| 401 | let head = &word[..=open]; |
| 402 | return expand_braces(&word[open + 1..]) |
| 403 | .into_iter() |
| 404 | .map(|tail| format!("{head}{tail}")) |
| 405 | .take(CAP) |
| 406 | .collect(); |
| 407 | }; |
| 408 | let mut cuts = vec![open]; |
| 409 | cuts.extend(commas); |
| 410 | cuts.push(close); |
| 411 | let mut out = Vec::new(); |
| 412 | for pair in cuts.windows(2) { |
| 413 | let joined = format!( |
| 414 | "{}{}{}", |
| 415 | &word[..open], |
| 416 | &word[pair[0] + 1..pair[1]], |
| 417 | &word[close + 1..] |
| 418 | ); |
| 419 | for w in expand_braces(&joined) { |
| 420 | if out.len() == CAP { |
| 421 | return out; |
| 422 | } |
| 423 | out.push(w); |
| 424 | } |
| 425 | } |
| 426 | out |
| 427 | } |
| 428 | |
| 429 | fn glob_match(pat: &str, name: &str) -> bool { |
| 430 | fn class(pat: &[u8], c: u8) -> Option<(bool, usize)> { |
| 431 | // `pat` starts after `[`. Returns (matched, bytes consumed incl. `]`). |
| 432 | let (negate, start) = match pat.first() { |
| 433 | Some(b'!') | Some(b'^') => (true, 1), |
| 434 | _ => (false, 0), |
| 435 | }; |
| 436 | let mut i = start; |
| 437 | let mut hit = false; |
| 438 | while i < pat.len() { |
| 439 | if pat[i] == b']' && i > start { |
| 440 | return Some((hit != negate, i + 1)); |
| 441 | } |
| 442 | if i + 2 < pat.len() && pat[i + 1] == b'-' && pat[i + 2] != b']' { |
| 443 | hit |= pat[i] <= c && c <= pat[i + 2]; |
| 444 | i += 3; |
| 445 | } else { |
| 446 | hit |= pat[i] == c; |
| 447 | i += 1; |
| 448 | } |
| 449 | } |
| 450 | None |
| 451 | } |
| 452 | fn rec(pat: &[u8], name: &[u8]) -> bool { |
| 453 | match pat.first() { |
| 454 | None => name.is_empty(), |
| 455 | Some(b'*') => rec(&pat[1..], name) || (!name.is_empty() && rec(pat, &name[1..])), |
| 456 | Some(b'?') => !name.is_empty() && rec(&pat[1..], &name[1..]), |
| 457 | Some(b'[') if !name.is_empty() => match class(&pat[1..], name[0]) { |
| 458 | Some((true, used)) => rec(&pat[1 + used..], &name[1..]), |
| 459 | Some((false, _)) => false, |
| 460 | None => name[0] == b'[' && rec(&pat[1..], &name[1..]), |
| 461 | }, |
| 462 | Some(&c) => name.first().copied() == Some(c) && rec(&pat[1..], &name[1..]), |
| 463 | } |
| 464 | } |
| 465 | rec(pat.as_bytes(), name.as_bytes()) |
| 466 | } |
| 467 | |
| 468 | /// The path part of a shell word: after a redirect operator or `of=`. |
| 469 | fn path_part(token: &str) -> &str { |
| 470 | let t = token.rsplit('>').next().unwrap_or(token); |
| 471 | t.strip_prefix("of=").unwrap_or(t) |
| 472 | } |
| 473 | |
| 474 | /// True when a command string writes a protected runtime file, including |
| 475 | /// forms the redirect scanner does not name on its own. |
| 476 | fn command_names_protected_write(cmd: &str, cwd: &Path, facts: &RuntimeFacts) -> bool { |
| 477 | let expanded = expand_policy_env(cmd); |
| 478 | let lower = expanded.to_ascii_lowercase(); |
| 479 | let mentions = facts.protected.iter().any(|p| { |
| 480 | expanded.contains(&p.to_string_lossy().to_string()) |
| 481 | || p.file_name() |
| 482 | .and_then(|n| n.to_str()) |
| 483 | .is_some_and(|n| lower.contains(&n.to_ascii_lowercase())) |
| 484 | || expanded.split_whitespace().any(|tok| { |
| 485 | let word = path_part(tok).trim_matches(|c| c == '\'' || c == '"'); |
| 486 | word_covers(word, p, &facts.home, cwd) == Cover::Inside |
| 487 | }) |
| 488 | }) || lower.contains("$aien_approval_policy") |
| 489 | || lower.contains("${aien_approval_policy}"); |
| 490 | if !mentions { |
| 491 | return false; |
| 492 | } |
| 493 | lower.contains('>') |
| 494 | || lower.contains(" of=") |
| 495 | || lower.contains("dd ") |
| 496 | || lower.contains("python") |
| 497 | || lower.contains("perl") |
| 498 | || lower.contains("tee") |
| 499 | || lower.contains("sed") |
| 500 | || lower.contains("cp ") |
| 501 | || lower.contains("mv ") |
| 502 | || lower.contains("install") |
| 503 | || lower.contains("truncate") |
| 504 | } |
| 505 | |
| 506 | fn expand_policy_env(cmd: &str) -> String { |
| 507 | match std::env::var("AIEN_APPROVAL_POLICY") { |
| 508 | Ok(path) => cmd |
| 509 | .replace("${AIEN_APPROVAL_POLICY}", &path) |
| 510 | .replace("$AIEN_APPROVAL_POLICY", &path), |
| 511 | Err(_) => cmd.to_string(), |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | /// Read the guardian's reply. Only the first word counts; anything else is a |
| 516 | /// failure, which escalates to the person and counts against the breaker. |
| 517 | pub fn parse_guardian_reply(text: &str) -> GuardianAnswer { |
| 518 | let trimmed = text.trim(); |
| 519 | let first = trimmed |
| 520 | .split_whitespace() |
| 521 | .next() |
| 522 | .unwrap_or("") |
| 523 | .trim_matches(|c: char| !c.is_ascii_alphabetic()) |
| 524 | .to_ascii_uppercase(); |
| 525 | match first.as_str() { |
| 526 | "APPROVE" => GuardianAnswer::Approve, |
| 527 | "DENY" => GuardianAnswer::Deny(trimmed.chars().take(200).collect()), |
| 528 | "ESCALATE" => GuardianAnswer::Escalate, |
| 529 | _ => GuardianAnswer::Failed(format!( |
| 530 | "unparseable guardian reply: {:?}", |
| 531 | trimmed.chars().take(80).collect::<String>() |
| 532 | )), |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | /// Circuit breaker in front of the guardian model. After `threshold` |
| 537 | /// consecutive failures it opens and stays open for the session, so a broken |
| 538 | /// or slow guardian costs at most `threshold` calls; every request then goes |
| 539 | /// to the person. |
| 540 | #[derive(Debug, Clone, PartialEq)] |
| 541 | pub struct GuardianBreaker { |
| 542 | threshold: u32, |
| 543 | consecutive_failures: u32, |
| 544 | open: bool, |
| 545 | } |
| 546 | |
| 547 | impl GuardianBreaker { |
| 548 | pub fn new(threshold: u32) -> Self { |
| 549 | Self { |
| 550 | threshold: threshold.max(1), |
| 551 | consecutive_failures: 0, |
| 552 | open: false, |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | pub fn is_closed(&self) -> bool { |
| 557 | !self.open |
| 558 | } |
| 559 | |
| 560 | pub fn record(&mut self, answer: &GuardianAnswer) { |
| 561 | if matches!(answer, GuardianAnswer::Failed(_)) { |
| 562 | self.consecutive_failures += 1; |
| 563 | if self.consecutive_failures >= self.threshold { |
| 564 | self.open = true; |
| 565 | } |
| 566 | } else { |
| 567 | self.consecutive_failures = 0; |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | impl Default for GuardianBreaker { |
| 573 | fn default() -> Self { |
| 574 | Self::new(3) |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | /// The text a request is matched against: the command for `run_command`, |
| 579 | /// the path for file tools, otherwise the tool name and its arguments. |
| 580 | pub fn subject(tool: &str, args: &Value) -> String { |
| 581 | match tool { |
| 582 | "run_command" => command_of(args).to_string(), |
| 583 | "view_file" |
| 584 | | "write_to_file" |
| 585 | | "create_file" |
| 586 | | "replace_file_content" |
| 587 | | "edit_file" |
| 588 | | "list_dir" |
| 589 | | "list_directory" |
| 590 | | "create_dir" => path_of(args).to_string(), |
| 591 | _ => format!("{} {}", tool, args), |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | fn command_of(args: &Value) -> &str { |
| 596 | args.get("command") |
| 597 | .or_else(|| args.get("CommandLine")) |
| 598 | .and_then(Value::as_str) |
| 599 | .unwrap_or("") |
| 600 | } |
| 601 | |
| 602 | fn path_of(args: &Value) -> &str { |
| 603 | args.get("path") |
| 604 | .or_else(|| args.get("target_file")) |
| 605 | .or_else(|| args.get("TargetFile")) |
| 606 | .or_else(|| args.get("AbsolutePath")) |
| 607 | .or_else(|| args.get("directory_path")) |
| 608 | .or_else(|| args.get("DirectoryPath")) |
| 609 | .and_then(Value::as_str) |
| 610 | .unwrap_or("") |
| 611 | } |
| 612 | |
| 613 | fn cwd_of<'a>(args: &'a Value, facts: &'a RuntimeFacts) -> PathBuf { |
| 614 | match args |
| 615 | .get("cwd") |
| 616 | .or_else(|| args.get("Cwd")) |
| 617 | .and_then(Value::as_str) |
| 618 | { |
| 619 | Some(c) if !c.is_empty() => lexical_abs(c, &facts.home, &facts.cwd), |
| 620 | _ => facts.cwd.clone(), |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | fn matches_subject(re: &Regex, subject: &str) -> bool { |
| 625 | re.is_match(subject) || re.is_match(&normalize_command(subject)) |
| 626 | } |
| 627 | |
| 628 | /// Quotes and backslashes removed, whitespace collapsed, lower case. |
| 629 | /// Closes the cheap spellings that slip past a plain substring match |
| 630 | /// (`r''m -rf /`, `rm -rf /`, `RM -RF /`). |
| 631 | pub fn normalize_command(cmd: &str) -> String { |
| 632 | strip_quotes(cmd).to_lowercase() |
| 633 | } |
| 634 | |
| 635 | /// Split a shell line into simple commands on `;`, `&&`, `||`, `|`, `&`, |
| 636 | /// newlines, `$(`, `(`, `)` and backticks. Returns each segment and whether |
| 637 | /// it receives a pipe from the previous one. |
| 638 | fn segments(normalized: &str) -> Vec<(String, bool)> { |
| 639 | let mut out = Vec::new(); |
| 640 | let mut current = String::new(); |
| 641 | let mut piped_next = false; |
| 642 | let mut piped_current = false; |
| 643 | let chars: Vec<char> = normalized.chars().collect(); |
| 644 | let mut i = 0; |
| 645 | while i < chars.len() { |
| 646 | let c = chars[i]; |
| 647 | let next = chars.get(i + 1).copied(); |
| 648 | let boundary = match (c, next) { |
| 649 | ('&', Some('&')) | ('|', Some('|')) => { |
| 650 | i += 1; |
| 651 | true |
| 652 | } |
| 653 | ('|', _) => { |
| 654 | piped_next = true; |
| 655 | true |
| 656 | } |
| 657 | ('$', Some('(')) => { |
| 658 | i += 1; |
| 659 | true |
| 660 | } |
| 661 | (';' | '&' | '\n' | '`' | '(' | ')' | '{' | '}', _) => true, |
| 662 | _ => false, |
| 663 | }; |
| 664 | if boundary { |
| 665 | if !current.trim().is_empty() { |
| 666 | out.push((current.trim().to_string(), piped_current)); |
| 667 | } |
| 668 | current.clear(); |
| 669 | piped_current = piped_next; |
| 670 | piped_next = false; |
| 671 | } else { |
| 672 | current.push(c); |
| 673 | } |
| 674 | i += 1; |
| 675 | } |
| 676 | if !current.trim().is_empty() { |
| 677 | out.push((current.trim().to_string(), piped_current)); |
| 678 | } |
| 679 | out |
| 680 | } |
| 681 | |
| 682 | /// Wrappers that run the next word as the real command. |
| 683 | const WRAPPERS: [&str; 9] = [ |
| 684 | "sudo", "env", "nice", "nohup", "time", "command", "exec", "busybox", "doas", |
| 685 | ]; |
| 686 | |
| 687 | /// Strip wrappers and `NAME=value` assignments; return the real command's |
| 688 | /// base name and its arguments. |
| 689 | fn real_command(tokens: &[&str]) -> Option<(String, Vec<String>)> { |
| 690 | let mut i = 0; |
| 691 | while i < tokens.len() { |
| 692 | let t = tokens[i]; |
| 693 | let base = t.rsplit('/').next().unwrap_or(t); |
| 694 | if WRAPPERS.contains(&base) { |
| 695 | i += 1; |
| 696 | // Skip the wrapper's own flags (and a numeric niceness). |
| 697 | while i < tokens.len() |
| 698 | && (tokens[i].starts_with('-') || tokens[i].parse::<i64>().is_ok()) |
| 699 | { |
| 700 | i += 1; |
| 701 | } |
| 702 | continue; |
| 703 | } |
| 704 | if t.contains('=') && !t.starts_with('-') && !t.starts_with('/') { |
| 705 | i += 1; |
| 706 | continue; |
| 707 | } |
| 708 | let args = tokens[i + 1..].iter().map(|s| s.to_string()).collect(); |
| 709 | return Some((base.to_string(), args)); |
| 710 | } |
| 711 | None |
| 712 | } |
| 713 | |
| 714 | const CRITICAL_ROOTS: [&str; 16] = [ |
| 715 | "/", "/*", "~", "~/", "~/*", "$home", "${home}", "/home", "/root", "/etc", "/usr", "/boot", |
| 716 | "/var", "/bin", "/lib", "/sbin", |
| 717 | ]; |
| 718 | |
| 719 | fn is_critical_target(arg: &str) -> bool { |
| 720 | let trimmed = if arg.len() > 1 { |
| 721 | arg.trim_end_matches('/') |
| 722 | } else { |
| 723 | arg |
| 724 | }; |
| 725 | let trimmed = if trimmed.is_empty() { "/" } else { trimmed }; |
| 726 | CRITICAL_ROOTS.contains(&trimmed) |
| 727 | || CRITICAL_ROOTS.contains(&arg) |
| 728 | || matches!(trimmed, "/home/*" | "/root/*" | "$home/*" | "${home}/*") |
| 729 | } |
| 730 | |
| 731 | fn has_short_flag(args: &[String], flag: char) -> bool { |
| 732 | args.iter() |
| 733 | .any(|a| a.starts_with('-') && !a.starts_with("--") && a[1..].contains(flag)) |
| 734 | } |
| 735 | |
| 736 | const RAW_DISKS: [&str; 8] = [ |
| 737 | "/dev/sd", |
| 738 | "/dev/nvme", |
| 739 | "/dev/mmcblk", |
| 740 | "/dev/vd", |
| 741 | "/dev/hd", |
| 742 | "/dev/xvd", |
| 743 | "/dev/disk", |
| 744 | "/dev/mapper/", |
| 745 | ]; |
| 746 | |
| 747 | fn names_raw_disk(arg: &str) -> bool { |
| 748 | RAW_DISKS.iter().any(|d| arg.starts_with(d)) |
| 749 | } |
| 750 | |
| 751 | /// Floor 1: commands nothing may approve. |
| 752 | pub fn hardline(cmd: &str) -> Option<String> { |
| 753 | let norm = normalize_command(cmd); |
| 754 | let squeezed: String = norm.chars().filter(|c| !c.is_whitespace()).collect(); |
| 755 | if squeezed.contains(":(){:|:&};:") { |
| 756 | return Some("fork bomb".into()); |
| 757 | } |
| 758 | if norm.contains("--no-preserve-root") { |
| 759 | return Some("rm --no-preserve-root".into()); |
| 760 | } |
| 761 | for disk in RAW_DISKS { |
| 762 | if squeezed.contains(&format!(">{disk}")) { |
| 763 | return Some(format!("redirect onto raw disk {disk}*")); |
| 764 | } |
| 765 | } |
| 766 | for (segment, _) in segments(&norm) { |
| 767 | let tokens: Vec<&str> = segment.split_whitespace().collect(); |
| 768 | let Some((name, args)) = real_command(&tokens) else { |
| 769 | continue; |
| 770 | }; |
| 771 | let targets: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); |
| 772 | match name.as_str() { |
| 773 | "rm" => { |
| 774 | let recursive = |
| 775 | has_short_flag(&args, 'r') || args.iter().any(|a| a == "--recursive"); |
| 776 | if recursive { |
| 777 | if let Some(t) = targets.iter().find(|t| is_critical_target(t)) { |
| 778 | return Some(format!("recursive delete of {t}")); |
| 779 | } |
| 780 | } |
| 781 | } |
| 782 | "chmod" | "chown" | "chgrp" => { |
| 783 | // Arguments are lower case here, so `-R` reads as `-r`. |
| 784 | let recursive = |
| 785 | has_short_flag(&args, 'r') || args.iter().any(|a| a == "--recursive"); |
| 786 | if recursive && targets.iter().any(|t| is_critical_target(t)) { |
| 787 | return Some(format!("recursive {name} of a system root")); |
| 788 | } |
| 789 | } |
| 790 | n if n.starts_with("mkfs") || n == "wipefs" || n == "mkswap" => { |
| 791 | if args.iter().any(|a| names_raw_disk(a)) { |
| 792 | return Some(format!("{n} on a raw disk")); |
| 793 | } |
| 794 | } |
| 795 | "dd" => { |
| 796 | if args |
| 797 | .iter() |
| 798 | .any(|a| a.strip_prefix("of=").is_some_and(names_raw_disk)) |
| 799 | { |
| 800 | return Some("dd onto a raw disk".into()); |
| 801 | } |
| 802 | } |
| 803 | "shred" => { |
| 804 | if args.iter().any(|a| names_raw_disk(a)) { |
| 805 | return Some("shred of a raw disk".into()); |
| 806 | } |
| 807 | } |
| 808 | "kill" if args.iter().any(|a| a == "1" || a == "-1") => { |
| 809 | return Some("kill of init or of every process".into()); |
| 810 | } |
| 811 | _ => {} |
| 812 | } |
| 813 | } |
| 814 | None |
| 815 | } |
| 816 | |
| 817 | /// Floor 3: `sudo` reading a password from stdin (`-S`, `--stdin`, or a pipe |
| 818 | /// into sudo). A password in a command line ends up in history and logs. |
| 819 | pub fn sudo_piped_password(cmd: &str) -> Option<String> { |
| 820 | // Case matters here: `sudo -S` reads stdin, `sudo -s` opens a shell. |
| 821 | let stripped = strip_quotes(cmd); |
| 822 | for (segment, piped_in) in segments(&stripped) { |
| 823 | let tokens: Vec<&str> = segment.split_whitespace().collect(); |
| 824 | let Some(pos) = tokens |
| 825 | .iter() |
| 826 | .position(|t| t.rsplit('/').next().map(str::to_lowercase).as_deref() == Some("sudo")) |
| 827 | else { |
| 828 | continue; |
| 829 | }; |
| 830 | let flags: Vec<&str> = tokens[pos + 1..] |
| 831 | .iter() |
| 832 | .take_while(|t| t.starts_with('-')) |
| 833 | .copied() |
| 834 | .collect(); |
| 835 | if flags.contains(&"--stdin") |
| 836 | || flags |
| 837 | .iter() |
| 838 | .any(|f| !f.starts_with("--") && f[1..].contains('S')) |
| 839 | { |
| 840 | return Some("sudo -S reads a password from stdin".into()); |
| 841 | } |
| 842 | if segment.contains("<<") { |
| 843 | return Some("sudo fed through a here-document or here-string".into()); |
| 844 | } |
| 845 | if piped_in && pos == 0 { |
| 846 | return Some("password piped into sudo".into()); |
| 847 | } |
| 848 | } |
| 849 | None |
| 850 | } |
| 851 | |
| 852 | /// Quotes and backslashes removed, whitespace collapsed, case kept. |
| 853 | fn strip_quotes(cmd: &str) -> String { |
| 854 | let stripped: String = cmd |
| 855 | .replace("\\\n", " ") |
| 856 | .chars() |
| 857 | .filter(|c| !matches!(c, '\'' | '"' | '\\')) |
| 858 | .collect(); |
| 859 | stripped.split_whitespace().collect::<Vec<_>>().join(" ") |
| 860 | } |
| 861 | |
| 862 | /// Lexical absolute path: `~` and `$HOME` expanded, relative joined to |
| 863 | /// `base`, `.` and `..` folded. No disk access. |
| 864 | pub fn lexical_abs(path: &str, home: &Path, base: &Path) -> PathBuf { |
| 865 | let expanded = if path == "~" || path == "$home" || path == "$HOME" { |
| 866 | home.to_path_buf() |
| 867 | } else if let Some(rest) = path |
| 868 | .strip_prefix("~/") |
| 869 | .or_else(|| path.strip_prefix("$HOME/")) |
| 870 | .or_else(|| path.strip_prefix("$home/")) |
| 871 | .or_else(|| path.strip_prefix("${HOME}/")) |
| 872 | { |
| 873 | home.join(rest) |
| 874 | } else { |
| 875 | PathBuf::from(path) |
| 876 | }; |
| 877 | let joined = if expanded.is_relative() { |
| 878 | base.join(expanded) |
| 879 | } else { |
| 880 | expanded |
| 881 | }; |
| 882 | let mut out = PathBuf::new(); |
| 883 | for comp in joined.components() { |
| 884 | match comp { |
| 885 | Component::ParentDir => { |
| 886 | out.pop(); |
| 887 | } |
| 888 | Component::CurDir => {} |
| 889 | other => out.push(other.as_os_str()), |
| 890 | } |
| 891 | } |
| 892 | out |
| 893 | } |
| 894 | |
| 895 | const MUTATING: [&str; 16] = [ |
| 896 | "rm", "rmdir", "mv", "shred", "truncate", "unlink", "cp", "ln", "chmod", "chown", "tee", "dd", |
| 897 | "install", "rsync", "find", "sed", |
| 898 | ]; |
| 899 | |
| 900 | /// Floor 2: the agent deleting or rewriting the runtime itself. |
| 901 | pub fn runtime_self_delete(tool: &str, args: &Value, facts: &RuntimeFacts) -> Option<String> { |
| 902 | if facts.protected.is_empty() { |
| 903 | return None; |
| 904 | } |
| 905 | match tool { |
| 906 | "write_to_file" | "create_file" | "replace_file_content" | "edit_file" | "create_dir" => { |
| 907 | let raw = path_of(args); |
| 908 | if raw.is_empty() { |
| 909 | return None; |
| 910 | } |
| 911 | let p = lexical_abs(raw, &facts.home, &facts.cwd); |
| 912 | // Creating something *above* a protected path is harmless for a |
| 913 | // file write; only writes inside a protected entry count here. |
| 914 | let hit = facts.protected.iter().find(|r| p.starts_with(r))?; |
| 915 | Some(format!( |
| 916 | "{} would rewrite the runtime's own file {}", |
| 917 | tool, |
| 918 | hit.display() |
| 919 | )) |
| 920 | } |
| 921 | "run_command" => { |
| 922 | let cwd = cwd_of(args, facts); |
| 923 | let original = command_of(args); |
| 924 | if command_names_protected_write(original, &cwd, facts) { |
| 925 | return Some( |
| 926 | "command would rewrite the runtime's own approval policy or another protected file" |
| 927 | .into(), |
| 928 | ); |
| 929 | } |
| 930 | // Paths are case-sensitive: segment the quote-stripped original, |
| 931 | // compare verbs in lower case. |
| 932 | let stripped: String = original |
| 933 | .chars() |
| 934 | .filter(|c| !matches!(c, '\'' | '"' | '\\')) |
| 935 | .collect(); |
| 936 | for (segment, _) in segments(&stripped) { |
| 937 | let tokens: Vec<&str> = segment.split_whitespace().collect(); |
| 938 | let redirect_targets: Vec<&str> = tokens |
| 939 | .iter() |
| 940 | .enumerate() |
| 941 | .filter_map(|(i, t)| { |
| 942 | if let Some(rest) = t.find('>').map(|i| t[i..].trim_start_matches('>')) { |
| 943 | if rest.is_empty() { |
| 944 | tokens.get(i + 1).copied() |
| 945 | } else { |
| 946 | Some(rest) |
| 947 | } |
| 948 | } else { |
| 949 | None |
| 950 | } |
| 951 | }) |
| 952 | .collect(); |
| 953 | for t in &redirect_targets { |
| 954 | if let Some(hit) = facts |
| 955 | .protected |
| 956 | .iter() |
| 957 | .find(|r| word_covers(t, r, &facts.home, &cwd) == Cover::Inside) |
| 958 | { |
| 959 | return Some(format!( |
| 960 | "shell redirect would overwrite the runtime's own file {}", |
| 961 | hit.display() |
| 962 | )); |
| 963 | } |
| 964 | } |
| 965 | let lowered: Vec<String> = tokens.iter().map(|t| t.to_lowercase()).collect(); |
| 966 | let lowered_refs: Vec<&str> = lowered.iter().map(String::as_str).collect(); |
| 967 | let Some((name, _)) = real_command(&lowered_refs) else { |
| 968 | continue; |
| 969 | }; |
| 970 | if !MUTATING.contains(&name.as_str()) { |
| 971 | continue; |
| 972 | } |
| 973 | // `sed` only mutates with -i; `find` only with -delete/-exec. |
| 974 | if name == "sed" && !lowered.iter().any(|t| t.starts_with("-i")) { |
| 975 | continue; |
| 976 | } |
| 977 | if name == "find" && !lowered.iter().any(|t| t == "-delete" || t == "-exec") { |
| 978 | continue; |
| 979 | } |
| 980 | // Deleting a parent deletes the runtime too, so deleting |
| 981 | // verbs (and the source side of `mv`) also match a parent of |
| 982 | // a protected entry. Other verbs must point inside one. |
| 983 | let operands: Vec<&str> = tokens |
| 984 | .iter() |
| 985 | .skip_while(|t| t.to_lowercase().rsplit('/').next() != Some(name.as_str())) |
| 986 | .skip(1) |
| 987 | .filter(|t| !t.starts_with('-')) |
| 988 | .copied() |
| 989 | .collect(); |
| 990 | for (i, t) in operands.iter().enumerate() { |
| 991 | let deleting = |
| 992 | matches!(name.as_str(), "rm" | "rmdir" | "shred" | "unlink" | "find") |
| 993 | || (name == "mv" && i + 1 < operands.len()); |
| 994 | let hit = facts |
| 995 | .protected |
| 996 | .iter() |
| 997 | .find(|r| match word_covers(t, r, &facts.home, &cwd) { |
| 998 | Cover::Inside => true, |
| 999 | Cover::Parent => deleting, |
| 1000 | Cover::None => false, |
| 1001 | }) |
| 1002 | .cloned(); |
| 1003 | if let Some(hit) = hit { |
| 1004 | return Some(format!( |
| 1005 | "{} would delete or rewrite the runtime's own file {}", |
| 1006 | name, |
| 1007 | hit.display() |
| 1008 | )); |
| 1009 | } |
| 1010 | } |
| 1011 | } |
| 1012 | None |
| 1013 | } |
| 1014 | _ => None, |
| 1015 | } |
| 1016 | } |
| 1017 | |
| 1018 | /// All four floors. Order only changes the reason given; every floor denies. |
| 1019 | pub fn check_floors( |
| 1020 | tool: &str, |
| 1021 | args: &Value, |
| 1022 | policy: &CompiledPolicy, |
| 1023 | facts: &RuntimeFacts, |
| 1024 | ) -> Option<(Floor, String)> { |
| 1025 | if let Some(broken) = &policy.broken { |
| 1026 | return Some((Floor::OperatorDeny, broken.clone())); |
| 1027 | } |
| 1028 | if tool == "run_command" { |
| 1029 | let cmd = command_of(args); |
| 1030 | if let Some(why) = hardline(cmd) { |
| 1031 | return Some((Floor::Hardline, format!("hardline floor: {why}"))); |
| 1032 | } |
| 1033 | if let Some(why) = sudo_piped_password(cmd) { |
| 1034 | return Some((Floor::SudoPipedPassword, format!("sudo floor: {why}"))); |
| 1035 | } |
| 1036 | } |
| 1037 | if let Some(why) = runtime_self_delete(tool, args, facts) { |
| 1038 | return Some((Floor::RuntimeSelfDelete, format!("runtime floor: {why}"))); |
| 1039 | } |
| 1040 | let subject = subject(tool, args); |
| 1041 | if let Some(re) = policy.deny.iter().find(|re| matches_subject(re, &subject)) { |
| 1042 | return Some(( |
| 1043 | Floor::OperatorDeny, |
| 1044 | format!("operator deny pattern {:?} matched", re.as_str()), |
| 1045 | )); |
| 1046 | } |
| 1047 | None |
| 1048 | } |
| 1049 | |
| 1050 | /// Does this request need a decision (person or guardian)? `None` = clear. |
| 1051 | fn needs_decision(tool: &str, args: &Value, base: &SafetyDecision) -> Option<String> { |
| 1052 | if let SafetyDecision::AskUser(reason) = base { |
| 1053 | return Some(reason.clone()); |
| 1054 | } |
| 1055 | match tool { |
| 1056 | "run_command" if is_high_risk_command(command_of(args)) => { |
| 1057 | Some("dangerous command pattern".into()) |
| 1058 | } |
| 1059 | "write_to_file" | "create_file" | "replace_file_content" | "edit_file" |
| 1060 | if is_high_risk_path(path_of(args)) => |
| 1061 | { |
| 1062 | Some("write to an operating system path".into()) |
| 1063 | } |
| 1064 | _ => None, |
| 1065 | } |
| 1066 | } |
| 1067 | |
| 1068 | // --------------------------------------------------------------------------- |
| 1069 | // Edges: policy file, presence, mode, runtime facts |
| 1070 | // --------------------------------------------------------------------------- |
| 1071 | |
| 1072 | /// `$AIEN_APPROVAL_POLICY`, else `~/basecamp/approval-policy.json`. |
| 1073 | pub fn policy_path(home: &Path) -> PathBuf { |
| 1074 | std::env::var_os("AIEN_APPROVAL_POLICY") |
| 1075 | .map(PathBuf::from) |
| 1076 | .unwrap_or_else(|| home.join("basecamp/approval-policy.json")) |
| 1077 | } |
| 1078 | |
| 1079 | /// Missing file = empty policy. Unreadable or unparseable = deny everything. |
| 1080 | pub fn load_policy(path: &Path) -> CompiledPolicy { |
| 1081 | match std::fs::read_to_string(path) { |
| 1082 | Ok(text) => match serde_json::from_str::<OperatorPolicy>(&text) { |
| 1083 | Ok(policy) => CompiledPolicy::compile(&policy), |
| 1084 | Err(err) => CompiledPolicy::unreadable(format!("{}: {}", path.display(), err)), |
| 1085 | }, |
| 1086 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => CompiledPolicy::default(), |
| 1087 | Err(err) => CompiledPolicy::unreadable(format!("{}: {}", path.display(), err)), |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | /// Mode comes from the CLI flag or `$AIEN_APPROVAL_MODE`, captured for the |
| 1092 | /// process. The policy file's `mode` field is not a source. An unknown word |
| 1093 | /// falls back to manual. |
| 1094 | pub fn resolve_mode(_policy: &CompiledPolicy) -> ApprovalMode { |
| 1095 | mode_from_startup_inputs( |
| 1096 | std::env::var("AIEN_APPROVAL_MODE").ok().as_deref(), |
| 1097 | cli_approval_mode().as_deref(), |
| 1098 | ) |
| 1099 | } |
| 1100 | |
| 1101 | pub fn mode_from_startup_inputs(env_value: Option<&str>, cli_value: Option<&str>) -> ApprovalMode { |
| 1102 | if let Some(mode) = cli_value.and_then(ApprovalMode::parse) { |
| 1103 | return mode; |
| 1104 | } |
| 1105 | if let Some(value) = env_value { |
| 1106 | return ApprovalMode::parse(value).unwrap_or(ApprovalMode::Manual); |
| 1107 | } |
| 1108 | ApprovalMode::Manual |
| 1109 | } |
| 1110 | |
| 1111 | static CLI_APPROVAL_MODE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None); |
| 1112 | |
| 1113 | /// Record `--approval-mode` from process start. Later calls do not replace it. |
| 1114 | pub fn set_cli_approval_mode(text: &str) { |
| 1115 | let mut slot = CLI_APPROVAL_MODE.lock().unwrap_or_else(|e| e.into_inner()); |
| 1116 | if slot.is_none() { |
| 1117 | *slot = Some(text.to_string()); |
| 1118 | } |
| 1119 | } |
| 1120 | |
| 1121 | fn cli_approval_mode() -> Option<String> { |
| 1122 | CLI_APPROVAL_MODE |
| 1123 | .lock() |
| 1124 | .unwrap_or_else(|e| e.into_inner()) |
| 1125 | .clone() |
| 1126 | } |
| 1127 | |
| 1128 | /// A person is present when stdin is a terminal and `AIEN_UNATTENDED` is not |
| 1129 | /// set to a true value. |
| 1130 | pub fn resolve_presence() -> Presence { |
| 1131 | use std::io::IsTerminal; |
| 1132 | let flagged = std::env::var("AIEN_UNATTENDED") |
| 1133 | .map(|v| matches!(v.trim(), "1" | "true" | "yes")) |
| 1134 | .unwrap_or(false); |
| 1135 | if !flagged && std::io::stdin().is_terminal() { |
| 1136 | Presence::Person |
| 1137 | } else { |
| 1138 | Presence::Unattended |
| 1139 | } |
| 1140 | } |
| 1141 | |
| 1142 | /// The runtime's own files: this binary, the policy file, the checkpoint |
| 1143 | /// store and the session journals. |
| 1144 | pub fn runtime_facts(home: &Path, policy_file: &Path) -> RuntimeFacts { |
| 1145 | let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf()); |
| 1146 | let mut protected = vec![ |
| 1147 | lexical_abs(&policy_file.to_string_lossy(), home, &cwd), |
| 1148 | crate::checkpoint::store_root(home), |
| 1149 | home.join("basecamp/sessions"), |
| 1150 | ]; |
| 1151 | if let Ok(exe) = std::env::current_exe() { |
| 1152 | protected.push(exe); |
| 1153 | } |
| 1154 | RuntimeFacts { |
| 1155 | protected, |
| 1156 | home: home.to_path_buf(), |
| 1157 | cwd, |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | /// Everything the gate needs from the environment. Mode is fixed at startup. |
| 1162 | /// Deny and allow rules are loaded from the policy file on each call. |
| 1163 | #[derive(Debug, Clone)] |
| 1164 | pub struct GateContext { |
| 1165 | pub mode: ApprovalMode, |
| 1166 | pub presence: Presence, |
| 1167 | pub policy: CompiledPolicy, |
| 1168 | pub facts: RuntimeFacts, |
| 1169 | } |
| 1170 | |
| 1171 | impl GateContext { |
| 1172 | pub fn from_env() -> Self { |
| 1173 | let home = crate::platform::PlatformContext::detect().home_dir; |
| 1174 | let path = policy_path(&home); |
| 1175 | let mode = *STARTUP_MODE.get_or_init(|| resolve_mode(&CompiledPolicy::default())); |
| 1176 | // Deny and allow rules are read again each call. Mode stays the startup value. |
| 1177 | Self::load_at(&home, &path, mode) |
| 1178 | } |
| 1179 | |
| 1180 | pub fn load_at(home: &Path, policy_file: &Path, mode: ApprovalMode) -> Self { |
| 1181 | Self { |
| 1182 | mode, |
| 1183 | presence: resolve_presence(), |
| 1184 | facts: runtime_facts(home, policy_file), |
| 1185 | policy: load_policy(policy_file), |
| 1186 | } |
| 1187 | } |
| 1188 | } |
| 1189 | |
| 1190 | static STARTUP_MODE: std::sync::OnceLock<ApprovalMode> = std::sync::OnceLock::new(); |
| 1191 | |
| 1192 | fn breaker() -> &'static std::sync::Mutex<GuardianBreaker> { |
| 1193 | static BREAKER: std::sync::OnceLock<std::sync::Mutex<GuardianBreaker>> = |
| 1194 | std::sync::OnceLock::new(); |
| 1195 | BREAKER.get_or_init(|| std::sync::Mutex::new(GuardianBreaker::default())) |
| 1196 | } |
| 1197 | |
| 1198 | pub fn guardian_ready() -> bool { |
| 1199 | breaker().lock().map(|b| b.is_closed()).unwrap_or(false) |
| 1200 | } |
| 1201 | |
| 1202 | pub fn record_guardian(answer: &GuardianAnswer) { |
| 1203 | if let Ok(mut b) = breaker().lock() { |
| 1204 | b.record(answer); |
| 1205 | } |
| 1206 | } |
| 1207 | |
| 1208 | pub const GUARDIAN_PROMPT: &str = "You are the approval guardian for an agent's tool request on the operator's machine. \ |
| 1209 | Answer with exactly one word first: APPROVE if the request is routine and reversible, DENY if it would destroy data, \ |
| 1210 | leak secrets or harm the machine, ESCALATE if a person should decide. After the word you may give one short reason."; |
| 1211 | |
| 1212 | #[cfg(test)] |
| 1213 | mod tests { |
| 1214 | use super::*; |
| 1215 | use serde_json::json; |
| 1216 | |
| 1217 | fn facts() -> RuntimeFacts { |
| 1218 | RuntimeFacts { |
| 1219 | protected: vec![ |
| 1220 | PathBuf::from("/home/op/basecamp/approval-policy.json"), |
| 1221 | PathBuf::from("/home/op/basecamp/checkpoints"), |
| 1222 | PathBuf::from("/home/op/basecamp/sessions"), |
| 1223 | PathBuf::from("/opt/aien/bin/aien-cli"), |
| 1224 | ], |
| 1225 | home: PathBuf::from("/home/op"), |
| 1226 | cwd: PathBuf::from("/home/op/work"), |
| 1227 | } |
| 1228 | } |
| 1229 | |
| 1230 | fn policy(deny: &[&str], allow: &[&str]) -> CompiledPolicy { |
| 1231 | CompiledPolicy::compile(&OperatorPolicy { |
| 1232 | mode: None, |
| 1233 | deny: deny.iter().map(|s| s.to_string()).collect(), |
| 1234 | allow: allow.iter().map(|s| s.to_string()).collect(), |
| 1235 | }) |
| 1236 | } |
| 1237 | |
| 1238 | fn run( |
| 1239 | tool: &str, |
| 1240 | args: &Value, |
| 1241 | base: &SafetyDecision, |
| 1242 | mode: ApprovalMode, |
| 1243 | presence: Presence, |
| 1244 | policy: &CompiledPolicy, |
| 1245 | ) -> Verdict { |
| 1246 | decide(&Gate { |
| 1247 | tool, |
| 1248 | args, |
| 1249 | base, |
| 1250 | mode, |
| 1251 | presence, |
| 1252 | policy, |
| 1253 | facts: &facts(), |
| 1254 | guardian_ready: true, |
| 1255 | }) |
| 1256 | } |
| 1257 | |
| 1258 | fn cmd(c: &str) -> Value { |
| 1259 | json!({"command": c, "cwd": "/home/op/work"}) |
| 1260 | } |
| 1261 | |
| 1262 | // Acceptance: an operator deny pattern blocks a command in every mode, |
| 1263 | // one test per mode, with a person present and unattended. |
| 1264 | fn operator_deny_blocks(mode: ApprovalMode) { |
| 1265 | let pol = policy(&[r"git\s+push"], &[r".*"]); |
| 1266 | for presence in [Presence::Person, Presence::Unattended] { |
| 1267 | let v = run( |
| 1268 | "run_command", |
| 1269 | &cmd("git push origin main"), |
| 1270 | &SafetyDecision::Allow, |
| 1271 | mode, |
| 1272 | presence, |
| 1273 | &pol, |
| 1274 | ); |
| 1275 | assert!( |
| 1276 | matches!( |
| 1277 | v, |
| 1278 | Verdict::Deny { |
| 1279 | by: Stage::Floor(Floor::OperatorDeny), |
| 1280 | .. |
| 1281 | } |
| 1282 | ), |
| 1283 | "mode {mode:?} presence {presence:?}: {v:?}" |
| 1284 | ); |
| 1285 | } |
| 1286 | // Negative control: an unmatched command is allowed in manual and smart. |
| 1287 | // Yolo and off still ask, because run_command is bash -c. |
| 1288 | let v = run( |
| 1289 | "run_command", |
| 1290 | &cmd("git status"), |
| 1291 | &SafetyDecision::Allow, |
| 1292 | mode, |
| 1293 | Presence::Person, |
| 1294 | &pol, |
| 1295 | ); |
| 1296 | if matches!(mode, ApprovalMode::Yolo | ApprovalMode::Off) { |
| 1297 | assert!( |
| 1298 | matches!(v, Verdict::AskPerson { .. }), |
| 1299 | "mode {mode:?}: {v:?}" |
| 1300 | ); |
| 1301 | } else { |
| 1302 | assert!(matches!(v, Verdict::Allow { .. }), "mode {mode:?}: {v:?}"); |
| 1303 | } |
| 1304 | } |
| 1305 | |
| 1306 | #[test] |
| 1307 | fn operator_deny_blocks_in_manual_mode() { |
| 1308 | operator_deny_blocks(ApprovalMode::Manual); |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn operator_deny_blocks_in_smart_mode() { |
| 1313 | operator_deny_blocks(ApprovalMode::Smart); |
| 1314 | } |
| 1315 | |
| 1316 | #[test] |
| 1317 | fn operator_deny_blocks_in_yolo_mode() { |
| 1318 | operator_deny_blocks(ApprovalMode::Yolo); |
| 1319 | } |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn operator_deny_blocks_in_off_mode() { |
| 1323 | operator_deny_blocks(ApprovalMode::Off); |
| 1324 | } |
| 1325 | |
| 1326 | #[test] |
| 1327 | fn operator_deny_outranks_the_allowlist_and_spelling_tricks() { |
| 1328 | let pol = policy(&[r"git push"], &[r"^git push"]); |
| 1329 | for spelling in ["git push", "git push", "g''it push", "GIT PUSH --force"] { |
| 1330 | let v = run( |
| 1331 | "run_command", |
| 1332 | &cmd(spelling), |
| 1333 | &SafetyDecision::Allow, |
| 1334 | ApprovalMode::Yolo, |
| 1335 | Presence::Person, |
| 1336 | &pol, |
| 1337 | ); |
| 1338 | assert!( |
| 1339 | matches!( |
| 1340 | v, |
| 1341 | Verdict::Deny { |
| 1342 | by: Stage::Floor(Floor::OperatorDeny), |
| 1343 | .. |
| 1344 | } |
| 1345 | ), |
| 1346 | "{spelling}: {v:?}" |
| 1347 | ); |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | #[test] |
| 1352 | fn operator_deny_covers_file_tools_by_path() { |
| 1353 | let pol = policy(&[r"/secrets/"], &[]); |
| 1354 | let v = run( |
| 1355 | "write_to_file", |
| 1356 | &json!({"path": "/home/op/work/secrets/a.txt", "content": "x"}), |
| 1357 | &SafetyDecision::Allow, |
| 1358 | ApprovalMode::Off, |
| 1359 | Presence::Person, |
| 1360 | &pol, |
| 1361 | ); |
| 1362 | assert!( |
| 1363 | matches!( |
| 1364 | v, |
| 1365 | Verdict::Deny { |
| 1366 | by: Stage::Floor(Floor::OperatorDeny), |
| 1367 | .. |
| 1368 | } |
| 1369 | ), |
| 1370 | "{v:?}" |
| 1371 | ); |
| 1372 | } |
| 1373 | |
| 1374 | #[test] |
| 1375 | fn broken_policy_fails_closed_in_every_mode() { |
| 1376 | let pol = policy(&["(unclosed"], &[]); |
| 1377 | let unreadable = CompiledPolicy::unreadable("bad json".into()); |
| 1378 | for mode in ALL_MODES { |
| 1379 | for p in [&pol, &unreadable] { |
| 1380 | let v = run( |
| 1381 | "view_file", |
| 1382 | &json!({"path": "/home/op/work/a"}), |
| 1383 | &SafetyDecision::Allow, |
| 1384 | mode, |
| 1385 | Presence::Person, |
| 1386 | p, |
| 1387 | ); |
| 1388 | assert!( |
| 1389 | matches!( |
| 1390 | v, |
| 1391 | Verdict::Deny { |
| 1392 | by: Stage::Floor(Floor::OperatorDeny), |
| 1393 | .. |
| 1394 | } |
| 1395 | ), |
| 1396 | "{v:?}" |
| 1397 | ); |
| 1398 | } |
| 1399 | } |
| 1400 | // A broken allow pattern grants nothing and is reported. |
| 1401 | let pol = policy(&[], &["(unclosed"]); |
| 1402 | assert_eq!(pol.warnings.len(), 1); |
| 1403 | } |
| 1404 | |
| 1405 | #[test] |
| 1406 | fn hardline_floor_holds_in_every_mode() { |
| 1407 | let pol = policy(&[], &[r".*"]); |
| 1408 | let bad = [ |
| 1409 | "rm -rf /", |
| 1410 | "rm -rf /*", |
| 1411 | "sudo rm -fr ~", |
| 1412 | "rm -r -f $HOME", |
| 1413 | "cd /tmp && rm -Rf /home/", |
| 1414 | "r''m -rf /", |
| 1415 | "rm --recursive --force /etc", |
| 1416 | "rm -rf --no-preserve-root /x", |
| 1417 | "mkfs.ext4 /dev/nvme0n1p2", |
| 1418 | "dd if=/dev/zero of=/dev/sda bs=1M", |
| 1419 | "echo x > /dev/sda", |
| 1420 | ":(){ :|:& };:", |
| 1421 | "kill -9 -1", |
| 1422 | "chmod -R 777 /", |
| 1423 | "nice -n 10 rm -rf /usr", |
| 1424 | "X=1 rm -rf /boot", |
| 1425 | ]; |
| 1426 | for mode in ALL_MODES { |
| 1427 | for c in bad { |
| 1428 | let v = run( |
| 1429 | "run_command", |
| 1430 | &cmd(c), |
| 1431 | &SafetyDecision::Allow, |
| 1432 | mode, |
| 1433 | Presence::Person, |
| 1434 | &pol, |
| 1435 | ); |
| 1436 | assert!( |
| 1437 | matches!( |
| 1438 | v, |
| 1439 | Verdict::Deny { |
| 1440 | by: Stage::Floor(Floor::Hardline), |
| 1441 | .. |
| 1442 | } |
| 1443 | ), |
| 1444 | "{mode:?} {c}: {v:?}" |
| 1445 | ); |
| 1446 | } |
| 1447 | } |
| 1448 | } |
| 1449 | |
| 1450 | #[test] |
| 1451 | fn hardline_negative_controls_pass() { |
| 1452 | for c in [ |
| 1453 | "rm -rf /tmp/build", |
| 1454 | "rm -rf ./target", |
| 1455 | "rm -rf ~/work/old", |
| 1456 | "rm /home/op/a.txt", |
| 1457 | "dd if=/dev/zero of=/tmp/disk.img bs=1M count=10", |
| 1458 | "mkfs.ext4 /tmp/disk.img", |
| 1459 | "kill -9 4242", |
| 1460 | "chmod -R 755 ./bin", |
| 1461 | "echo hi > /dev/null", |
| 1462 | "cargo test", |
| 1463 | ] { |
| 1464 | assert_eq!(hardline(c), None, "{c}"); |
| 1465 | } |
| 1466 | } |
| 1467 | |
| 1468 | #[test] |
| 1469 | fn sudo_password_floor_holds_in_every_mode() { |
| 1470 | let pol = policy(&[], &[r".*"]); |
| 1471 | for mode in ALL_MODES { |
| 1472 | for c in [ |
| 1473 | "echo hunter2 | sudo -S apt install x", |
| 1474 | "sudo -S true <<< hunter2", |
| 1475 | "sudo --stdin ls", |
| 1476 | "printf pw | sudo ls", |
| 1477 | "sudo -kS ls", |
| 1478 | ] { |
| 1479 | let v = run( |
| 1480 | "run_command", |
| 1481 | &cmd(c), |
| 1482 | &SafetyDecision::Allow, |
| 1483 | mode, |
| 1484 | Presence::Person, |
| 1485 | &pol, |
| 1486 | ); |
| 1487 | assert!( |
| 1488 | matches!( |
| 1489 | v, |
| 1490 | Verdict::Deny { |
| 1491 | by: Stage::Floor(Floor::SudoPipedPassword), |
| 1492 | .. |
| 1493 | } |
| 1494 | ), |
| 1495 | "{mode:?} {c}: {v:?}" |
| 1496 | ); |
| 1497 | } |
| 1498 | } |
| 1499 | // Negative controls: plain sudo, and sudo -s (a shell, lower case). |
| 1500 | for c in ["sudo ls /root", "sudo -s", "sudo -u op ls | grep x"] { |
| 1501 | assert_eq!(sudo_piped_password(c), None, "{c}"); |
| 1502 | } |
| 1503 | } |
| 1504 | |
| 1505 | #[test] |
| 1506 | fn runtime_floor_holds_in_every_mode() { |
| 1507 | let pol = policy(&[], &[r".*"]); |
| 1508 | let cases = [ |
| 1509 | ("run_command", cmd("rm -rf ~/basecamp/checkpoints")), |
| 1510 | ("run_command", cmd("rm -rf /home/op/basecamp")), |
| 1511 | ( |
| 1512 | "run_command", |
| 1513 | cmd("cd /tmp; mv /opt/aien/bin/aien-cli /tmp/x"), |
| 1514 | ), |
| 1515 | ( |
| 1516 | "run_command", |
| 1517 | cmd("echo '{}' > ~/basecamp/approval-policy.json"), |
| 1518 | ), |
| 1519 | ( |
| 1520 | "run_command", |
| 1521 | cmd("sed -i s/deny/x/ /home/op/basecamp/approval-policy.json"), |
| 1522 | ), |
| 1523 | ( |
| 1524 | "run_command", |
| 1525 | json!({"command": "rm -r sessions", "cwd": "/home/op/basecamp"}), |
| 1526 | ), |
| 1527 | ( |
| 1528 | "write_to_file", |
| 1529 | json!({"path": "/home/op/basecamp/approval-policy.json", "content": "{}"}), |
| 1530 | ), |
| 1531 | ( |
| 1532 | "run_command", |
| 1533 | cmd("find /home/op/basecamp/sessions -delete"), |
| 1534 | ), |
| 1535 | ( |
| 1536 | "replace_file_content", |
| 1537 | json!({"path": "../basecamp/checkpoints/ledger/s.jsonl", "target": "a", "replacement": "b"}), |
| 1538 | ), |
| 1539 | ]; |
| 1540 | for mode in ALL_MODES { |
| 1541 | for (tool, args) in &cases { |
| 1542 | let v = run( |
| 1543 | tool, |
| 1544 | args, |
| 1545 | &SafetyDecision::Allow, |
| 1546 | mode, |
| 1547 | Presence::Person, |
| 1548 | &pol, |
| 1549 | ); |
| 1550 | assert!( |
| 1551 | matches!( |
| 1552 | v, |
| 1553 | Verdict::Deny { |
| 1554 | by: Stage::Floor(Floor::RuntimeSelfDelete), |
| 1555 | .. |
| 1556 | } |
| 1557 | ), |
| 1558 | "{mode:?} {tool} {args}: {v:?}" |
| 1559 | ); |
| 1560 | } |
| 1561 | } |
| 1562 | // Negative controls: reading the runtime's files and writing beside them. |
| 1563 | let f = facts(); |
| 1564 | for (tool, args) in [ |
| 1565 | ("run_command", cmd("cat ~/basecamp/approval-policy.json")), |
| 1566 | ("run_command", cmd("ls /home/op/basecamp/sessions")), |
| 1567 | ("run_command", cmd("rm -rf /home/op/basecamp/other")), |
| 1568 | ( |
| 1569 | "write_to_file", |
| 1570 | json!({"path": "/home/op/basecamp/notes.md", "content": "x"}), |
| 1571 | ), |
| 1572 | ] { |
| 1573 | assert_eq!(runtime_self_delete(tool, &args, &f), None, "{tool} {args}"); |
| 1574 | } |
| 1575 | } |
| 1576 | |
| 1577 | #[test] |
| 1578 | fn floors_come_before_mode_order_is_load_bearing() { |
| 1579 | // The policy-engine denial also survives yolo and off. |
| 1580 | let pol = policy(&[], &[]); |
| 1581 | for mode in ALL_MODES { |
| 1582 | let v = run( |
| 1583 | "write_to_file", |
| 1584 | &json!({"path": "/home/op/work/.env"}), |
| 1585 | &SafetyDecision::Deny("vault".into()), |
| 1586 | mode, |
| 1587 | Presence::Person, |
| 1588 | &pol, |
| 1589 | ); |
| 1590 | assert_eq!( |
| 1591 | v, |
| 1592 | Verdict::Deny { |
| 1593 | by: Stage::PolicyDeny, |
| 1594 | reason: "vault".into() |
| 1595 | } |
| 1596 | ); |
| 1597 | } |
| 1598 | } |
| 1599 | |
| 1600 | #[test] |
| 1601 | fn modes_after_the_floors() { |
| 1602 | let pol = policy(&[], &[]); |
| 1603 | let ask = SafetyDecision::AskUser("q".into()); |
| 1604 | let a = cmd("make deploy"); |
| 1605 | assert_eq!( |
| 1606 | run( |
| 1607 | "run_command", |
| 1608 | &a, |
| 1609 | &ask, |
| 1610 | ApprovalMode::Yolo, |
| 1611 | Presence::Unattended, |
| 1612 | &pol |
| 1613 | ), |
| 1614 | Verdict::Deny { |
| 1615 | by: Stage::Presence, |
| 1616 | reason: "run_command requires the person, unattended default is deny".into(), |
| 1617 | } |
| 1618 | ); |
| 1619 | assert_eq!( |
| 1620 | run( |
| 1621 | "run_command", |
| 1622 | &a, |
| 1623 | &ask, |
| 1624 | ApprovalMode::Off, |
| 1625 | Presence::Person, |
| 1626 | &pol |
| 1627 | ), |
| 1628 | Verdict::AskPerson { |
| 1629 | reason: "run_command requires the person".into(), |
| 1630 | } |
| 1631 | ); |
| 1632 | assert_eq!( |
| 1633 | run( |
| 1634 | "run_command", |
| 1635 | &a, |
| 1636 | &ask, |
| 1637 | ApprovalMode::Manual, |
| 1638 | Presence::Person, |
| 1639 | &pol |
| 1640 | ), |
| 1641 | Verdict::AskPerson { reason: "q".into() } |
| 1642 | ); |
| 1643 | assert_eq!( |
| 1644 | run( |
| 1645 | "run_command", |
| 1646 | &a, |
| 1647 | &ask, |
| 1648 | ApprovalMode::Smart, |
| 1649 | Presence::Person, |
| 1650 | &pol |
| 1651 | ), |
| 1652 | Verdict::AskGuardian { reason: "q".into() } |
| 1653 | ); |
| 1654 | } |
| 1655 | |
| 1656 | #[test] |
| 1657 | fn unattended_defaults_to_deny_but_clear_requests_pass() { |
| 1658 | let pol = policy(&[], &[]); |
| 1659 | for mode in [ApprovalMode::Manual, ApprovalMode::Smart] { |
| 1660 | let v = run( |
| 1661 | "run_command", |
| 1662 | &cmd("shutdown -h now"), |
| 1663 | &SafetyDecision::Allow, |
| 1664 | mode, |
| 1665 | Presence::Unattended, |
| 1666 | &pol, |
| 1667 | ); |
| 1668 | assert!( |
| 1669 | matches!( |
| 1670 | v, |
| 1671 | Verdict::Deny { |
| 1672 | by: Stage::Presence, |
| 1673 | .. |
| 1674 | } |
| 1675 | ), |
| 1676 | "{v:?}" |
| 1677 | ); |
| 1678 | let v = run( |
| 1679 | "run_command", |
| 1680 | &cmd("cargo test"), |
| 1681 | &SafetyDecision::Allow, |
| 1682 | mode, |
| 1683 | Presence::Unattended, |
| 1684 | &pol, |
| 1685 | ); |
| 1686 | assert_eq!(v, Verdict::Allow { by: Stage::Clear }); |
| 1687 | } |
| 1688 | } |
| 1689 | |
| 1690 | #[test] |
| 1691 | fn allowlist_skips_the_question_not_a_floor() { |
| 1692 | let pol = policy(&[], &[r"^shutdown -h now$"]); |
| 1693 | let v = run( |
| 1694 | "run_command", |
| 1695 | &cmd("shutdown -h now"), |
| 1696 | &SafetyDecision::Allow, |
| 1697 | ApprovalMode::Manual, |
| 1698 | Presence::Unattended, |
| 1699 | &pol, |
| 1700 | ); |
| 1701 | assert_eq!( |
| 1702 | v, |
| 1703 | Verdict::Allow { |
| 1704 | by: Stage::Allowlist |
| 1705 | } |
| 1706 | ); |
| 1707 | let v = run( |
| 1708 | "run_command", |
| 1709 | &cmd("rm -rf /"), |
| 1710 | &SafetyDecision::Allow, |
| 1711 | ApprovalMode::Manual, |
| 1712 | Presence::Person, |
| 1713 | &policy(&[], &[r".*"]), |
| 1714 | ); |
| 1715 | assert!(matches!( |
| 1716 | v, |
| 1717 | Verdict::Deny { |
| 1718 | by: Stage::Floor(Floor::Hardline), |
| 1719 | .. |
| 1720 | } |
| 1721 | )); |
| 1722 | } |
| 1723 | |
| 1724 | #[test] |
| 1725 | fn guardian_answers_and_breaker() { |
| 1726 | assert_eq!(parse_guardian_reply("APPROVE"), GuardianAnswer::Approve); |
| 1727 | assert_eq!( |
| 1728 | parse_guardian_reply(" escalate: unsure"), |
| 1729 | GuardianAnswer::Escalate |
| 1730 | ); |
| 1731 | assert!(matches!( |
| 1732 | parse_guardian_reply("DENY wipes data"), |
| 1733 | GuardianAnswer::Deny(_) |
| 1734 | )); |
| 1735 | assert!(matches!( |
| 1736 | parse_guardian_reply("Sure, go ahead"), |
| 1737 | GuardianAnswer::Failed(_) |
| 1738 | )); |
| 1739 | |
| 1740 | assert_eq!( |
| 1741 | after_guardian(&GuardianAnswer::Approve, "r".into()), |
| 1742 | Verdict::AskPerson { reason: "r".into() } |
| 1743 | ); |
| 1744 | assert!(matches!( |
| 1745 | after_guardian(&GuardianAnswer::Deny("x".into()), "r".into()), |
| 1746 | Verdict::Deny { |
| 1747 | by: Stage::Guardian, |
| 1748 | .. |
| 1749 | } |
| 1750 | )); |
| 1751 | for a in [ |
| 1752 | GuardianAnswer::Approve, |
| 1753 | GuardianAnswer::Escalate, |
| 1754 | GuardianAnswer::Failed("t".into()), |
| 1755 | ] { |
| 1756 | assert_eq!( |
| 1757 | after_guardian(&a, "r".into()), |
| 1758 | Verdict::AskPerson { reason: "r".into() } |
| 1759 | ); |
| 1760 | } |
| 1761 | |
| 1762 | let mut b = GuardianBreaker::new(3); |
| 1763 | let fail = GuardianAnswer::Failed("timeout".into()); |
| 1764 | b.record(&fail); |
| 1765 | b.record(&fail); |
| 1766 | b.record(&GuardianAnswer::Escalate); // a real answer resets the count |
| 1767 | b.record(&fail); |
| 1768 | b.record(&fail); |
| 1769 | assert!(b.is_closed()); |
| 1770 | b.record(&fail); |
| 1771 | assert!(!b.is_closed()); |
| 1772 | b.record(&GuardianAnswer::Approve); // stays open for the session |
| 1773 | assert!(!b.is_closed()); |
| 1774 | |
| 1775 | // An open breaker sends smart mode to the person. |
| 1776 | let pol = policy(&[], &[]); |
| 1777 | let v = decide(&Gate { |
| 1778 | tool: "run_command", |
| 1779 | args: &cmd("make deploy"), |
| 1780 | base: &SafetyDecision::AskUser("q".into()), |
| 1781 | mode: ApprovalMode::Smart, |
| 1782 | presence: Presence::Person, |
| 1783 | policy: &pol, |
| 1784 | facts: &facts(), |
| 1785 | guardian_ready: b.is_closed(), |
| 1786 | }); |
| 1787 | assert_eq!(v, Verdict::AskPerson { reason: "q".into() }); |
| 1788 | } |
| 1789 | |
| 1790 | #[test] |
| 1791 | fn person_floor_holds_in_every_mode_including_yolo() { |
| 1792 | let pol = policy(&[], &[r".*"]); |
| 1793 | let cases = [ |
| 1794 | ("sandbox", json!({"action": "promote", "message": "ship"})), |
| 1795 | ("skill", json!({"action": "optimize", "name": "demo"})), |
| 1796 | ("skills", json!({"action": "optimize"})), |
| 1797 | ]; |
| 1798 | for mode in ALL_MODES { |
| 1799 | for (tool, args) in &cases { |
| 1800 | let v = run( |
| 1801 | tool, |
| 1802 | args, |
| 1803 | &SafetyDecision::Allow, |
| 1804 | mode, |
| 1805 | Presence::Person, |
| 1806 | &pol, |
| 1807 | ); |
| 1808 | assert!( |
| 1809 | matches!(v, Verdict::AskPerson { .. }), |
| 1810 | "{mode:?} {tool}: {v:?}" |
| 1811 | ); |
| 1812 | let unattended = run( |
| 1813 | tool, |
| 1814 | args, |
| 1815 | &SafetyDecision::Allow, |
| 1816 | mode, |
| 1817 | Presence::Unattended, |
| 1818 | &pol, |
| 1819 | ); |
| 1820 | assert!( |
| 1821 | matches!(unattended, Verdict::Deny { .. }), |
| 1822 | "{mode:?} unattended {tool}: {unattended:?}" |
| 1823 | ); |
| 1824 | } |
| 1825 | } |
| 1826 | } |
| 1827 | |
| 1828 | #[test] |
| 1829 | fn floors_precede_the_person_prompt() { |
| 1830 | let pol = policy(&[], &[r".*"]); |
| 1831 | let bypasses = [ |
| 1832 | "rm -rf / ; echo {} > ~/basecamp/approval-policy.json", |
| 1833 | "rm -rf / && echo {} > ~/basecamp/approval-policy.json", |
| 1834 | ]; |
| 1835 | for mode in ALL_MODES { |
| 1836 | for c in bypasses { |
| 1837 | let v = run( |
| 1838 | "run_command", |
| 1839 | &cmd(c), |
| 1840 | &SafetyDecision::Allow, |
| 1841 | mode, |
| 1842 | Presence::Person, |
| 1843 | &pol, |
| 1844 | ); |
| 1845 | assert!( |
| 1846 | matches!( |
| 1847 | v, |
| 1848 | Verdict::Deny { |
| 1849 | by: Stage::Floor(Floor::Hardline), |
| 1850 | .. |
| 1851 | } |
| 1852 | ), |
| 1853 | "{mode:?} {c}: {v:?}" |
| 1854 | ); |
| 1855 | } |
| 1856 | } |
| 1857 | } |
| 1858 | |
| 1859 | #[test] |
| 1860 | fn policy_write_variants_stay_on_the_runtime_floor() { |
| 1861 | let pol = policy(&[], &[r".*"]); |
| 1862 | let cases = [ |
| 1863 | "dd if=/dev/zero of=/home/op/basecamp/approval-policy.json", |
| 1864 | "python3 -c 'open(\"/home/op/basecamp/approval-policy.json\",\"w\").write(\"x\")'", |
| 1865 | "perl -pi -e s/a/b/ /home/op/basecamp/approval-policy.json", |
| 1866 | "echo x > /home/op/basecamp/*.json", |
| 1867 | ]; |
| 1868 | for mode in ALL_MODES { |
| 1869 | for c in cases { |
| 1870 | let v = run( |
| 1871 | "run_command", |
| 1872 | &cmd(c), |
| 1873 | &SafetyDecision::Allow, |
| 1874 | mode, |
| 1875 | Presence::Person, |
| 1876 | &pol, |
| 1877 | ); |
| 1878 | assert!( |
| 1879 | matches!( |
| 1880 | v, |
| 1881 | Verdict::Deny { |
| 1882 | by: Stage::Floor(Floor::RuntimeSelfDelete), |
| 1883 | .. |
| 1884 | } |
| 1885 | ), |
| 1886 | "{mode:?} {c}: {v:?}" |
| 1887 | ); |
| 1888 | } |
| 1889 | } |
| 1890 | let mut custom = facts(); |
| 1891 | custom |
| 1892 | .protected |
| 1893 | .push(PathBuf::from("/var/aien/custom-approval.json")); |
| 1894 | let v = decide(&Gate { |
| 1895 | tool: "run_command", |
| 1896 | args: &cmd("echo x > /var/aien/custom-approval.json"), |
| 1897 | base: &SafetyDecision::Allow, |
| 1898 | mode: ApprovalMode::Yolo, |
| 1899 | presence: Presence::Person, |
| 1900 | policy: &pol, |
| 1901 | facts: &custom, |
| 1902 | guardian_ready: false, |
| 1903 | }); |
| 1904 | assert!( |
| 1905 | matches!( |
| 1906 | v, |
| 1907 | Verdict::Deny { |
| 1908 | by: Stage::Floor(Floor::RuntimeSelfDelete), |
| 1909 | .. |
| 1910 | } |
| 1911 | ), |
| 1912 | "custom policy path: {v:?}" |
| 1913 | ); |
| 1914 | } |
| 1915 | |
| 1916 | #[test] |
| 1917 | fn reloaded_deny_rules_apply_and_startup_mode_does_not() { |
| 1918 | let dir = tempfile::tempdir().unwrap(); |
| 1919 | let file = dir.path().join("approval-policy.json"); |
| 1920 | std::fs::write(&file, r#"{"mode":"off"}"#).unwrap(); |
| 1921 | let first = GateContext::load_at(dir.path(), &file, ApprovalMode::Yolo); |
| 1922 | assert_eq!(first.mode, ApprovalMode::Yolo); |
| 1923 | std::fs::write(&file, r#"{"mode":"manual","deny":["echo hi"]}"#).unwrap(); |
| 1924 | let second = GateContext::load_at(dir.path(), &file, first.mode); |
| 1925 | assert_eq!(second.mode, ApprovalMode::Yolo); |
| 1926 | let v = run( |
| 1927 | "run_command", |
| 1928 | &cmd("echo hi"), |
| 1929 | &SafetyDecision::Allow, |
| 1930 | second.mode, |
| 1931 | Presence::Person, |
| 1932 | &second.policy, |
| 1933 | ); |
| 1934 | assert!( |
| 1935 | matches!( |
| 1936 | v, |
| 1937 | Verdict::Deny { |
| 1938 | by: Stage::Floor(Floor::OperatorDeny), |
| 1939 | .. |
| 1940 | } |
| 1941 | ), |
| 1942 | "{v:?}" |
| 1943 | ); |
| 1944 | } |
| 1945 | |
| 1946 | #[test] |
| 1947 | fn mode_ignores_the_policy_file_and_a_later_edit() { |
| 1948 | assert_eq!(mode_from_startup_inputs(None, None), ApprovalMode::Manual); |
| 1949 | assert_eq!( |
| 1950 | mode_from_startup_inputs(Some("yolo"), None), |
| 1951 | ApprovalMode::Yolo |
| 1952 | ); |
| 1953 | assert_eq!( |
| 1954 | mode_from_startup_inputs(Some("manual"), Some("off")), |
| 1955 | ApprovalMode::Off |
| 1956 | ); |
| 1957 | let dir = tempfile::tempdir().unwrap(); |
| 1958 | let file = dir.path().join("approval-policy.json"); |
| 1959 | std::fs::write(&file, r#"{"mode":"yolo"}"#).unwrap(); |
| 1960 | let ctx = GateContext::load_at(dir.path(), &file, ApprovalMode::Manual); |
| 1961 | assert_eq!(ctx.mode, ApprovalMode::Manual); |
| 1962 | std::fs::write(&file, r#"{"mode":"off","allow":[".*"]}"#).unwrap(); |
| 1963 | let v = run( |
| 1964 | "run_command", |
| 1965 | &cmd("true"), |
| 1966 | &SafetyDecision::AskUser("needs approval".into()), |
| 1967 | ctx.mode, |
| 1968 | Presence::Person, |
| 1969 | &ctx.policy, |
| 1970 | ); |
| 1971 | assert!( |
| 1972 | matches!(v, Verdict::AskPerson { .. }), |
| 1973 | "a rewritten policy file changed the loaded mode: {v:?}" |
| 1974 | ); |
| 1975 | } |
| 1976 | |
| 1977 | #[test] |
| 1978 | fn decide_is_deterministic() { |
| 1979 | let pol = policy(&["x"], &["y"]); |
| 1980 | let a = cmd("echo y"); |
| 1981 | let first = run( |
| 1982 | "run_command", |
| 1983 | &a, |
| 1984 | &SafetyDecision::Allow, |
| 1985 | ApprovalMode::Manual, |
| 1986 | Presence::Person, |
| 1987 | &pol, |
| 1988 | ); |
| 1989 | for _ in 0..10 { |
| 1990 | assert_eq!( |
| 1991 | run( |
| 1992 | "run_command", |
| 1993 | &a, |
| 1994 | &SafetyDecision::Allow, |
| 1995 | ApprovalMode::Manual, |
| 1996 | Presence::Person, |
| 1997 | &pol |
| 1998 | ), |
| 1999 | first |
| 2000 | ); |
| 2001 | } |
| 2002 | } |
| 2003 | |
| 2004 | // A glob, class or brace word resolves against the command's own cwd, |
| 2005 | // not the session cwd, and every write form names the protected file. |
| 2006 | #[test] |
| 2007 | fn protected_globs_resolve_against_the_command_cwd() { |
| 2008 | let f = facts(); |
| 2009 | let at = |c: &str, cwd: &str| json!({"command": c, "cwd": cwd}); |
| 2010 | for (c, cwd) in [ |
| 2011 | ("cp x *-policy.json", "/home/op/basecamp"), |
| 2012 | ("printf x > *.json", "/home/op/basecamp"), |
| 2013 | ("printf x >*.json", "/home/op/basecamp"), |
| 2014 | ("printf x > approval-polic[y].json", "/home/op/basecamp"), |
| 2015 | ( |
| 2016 | "echo x | tee approval-policy.{json,bak}", |
| 2017 | "/home/op/basecamp", |
| 2018 | ), |
| 2019 | ("printf x > ../basecamp/[a]*.json", "/home/op/work"), |
| 2020 | ("rm -rf ~/base*", "/home/op/work"), |
| 2021 | ("rm -rf ../ba?ecamp", "/home/op/work"), |
| 2022 | ] { |
| 2023 | assert!( |
| 2024 | runtime_self_delete("run_command", &at(c, cwd), &f).is_some(), |
| 2025 | "{c} in {cwd} must hit the runtime floor" |
| 2026 | ); |
| 2027 | } |
| 2028 | for (c, cwd) in [ |
| 2029 | ("ls *.json", "/home/op/basecamp"), |
| 2030 | ("cp a.txt b.txt", "/home/op/basecamp"), |
| 2031 | ("printf x > *.json", "/home/op/work"), |
| 2032 | ("cp notes.txt ~/", "/home/op/work"), |
| 2033 | ("touch ~/base*", "/home/op/work"), |
| 2034 | ] { |
| 2035 | assert!( |
| 2036 | runtime_self_delete("run_command", &at(c, cwd), &f).is_none(), |
| 2037 | "{c} in {cwd} is not a runtime write" |
| 2038 | ); |
| 2039 | } |
| 2040 | } |
| 2041 | |
| 2042 | #[test] |
| 2043 | fn brace_and_class_words_expand_like_bash() { |
| 2044 | assert_eq!(expand_braces("a{b,c}d"), ["abd", "acd"]); |
| 2045 | assert_eq!(expand_braces("x{1,{2,3}}"), ["x1", "x2", "x3"]); |
| 2046 | assert_eq!(expand_braces("{}"), ["{}"]); |
| 2047 | assert!(glob_match("polic[xy]", "policy")); |
| 2048 | assert!(!glob_match("polic[!y]", "policy")); |
| 2049 | assert!(glob_match("p[a-z]licy", "policy")); |
| 2050 | assert!(glob_match("[", "[")); |
| 2051 | } |
| 2052 | } |