safe_chains/lib.rs
1// Generated test names keep the flag case they spell (`-D` and `-d` differ), so they opt out of non_snake_case.
2#[cfg(test)]
3macro_rules! safe {
4 ($($name:ident: $cmd:expr),* $(,)?) => {
5 $(#[test] #[allow(non_snake_case)] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
6 };
7}
8
9#[cfg(test)]
10macro_rules! denied {
11 ($($name:ident: $cmd:expr),* $(,)?) => {
12 $(#[test] #[allow(non_snake_case)] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
13 };
14}
15
16#[cfg(test)]
17macro_rules! inert {
18 ($($name:ident: $cmd:expr),* $(,)?) => {
19 $(#[test] #[allow(non_snake_case)] fn $name() {
20 assert_eq!(
21 crate::command_verdict($cmd),
22 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::Inert),
23 "expected Inert: {}", $cmd,
24 );
25 })*
26 };
27}
28
29#[cfg(test)]
30macro_rules! safe_read {
31 ($($name:ident: $cmd:expr),* $(,)?) => {
32 $(#[test] #[allow(non_snake_case)] fn $name() {
33 assert_eq!(
34 crate::command_verdict($cmd),
35 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
36 "expected SafeRead: {}", $cmd,
37 );
38 })*
39 };
40}
41
42#[cfg(test)]
43macro_rules! safe_write {
44 ($($name:ident: $cmd:expr),* $(,)?) => {
45 $(#[test] #[allow(non_snake_case)] fn $name() {
46 assert_eq!(
47 crate::command_verdict($cmd),
48 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite),
49 "expected SafeWrite: {}", $cmd,
50 );
51 })*
52 };
53}
54
55pub mod allowlist;
56pub mod cli;
57#[cfg(test)]
58mod composition;
59pub mod cst;
60pub mod decisionlog;
61pub mod docs;
62pub mod engine;
63mod envvars;
64pub mod explain_fix;
65#[cfg(test)]
66mod handler_property_tests;
67mod handlers;
68pub mod mcp;
69pub mod netloc;
70#[cfg(test)]
71mod overreach_property_tests;
72pub mod parse;
73#[cfg(test)]
74mod path_placement_tests;
75pub mod pathctx;
76pub mod pathgate;
77pub mod policy;
78pub mod refusal;
79pub mod registry;
80#[cfg(test)]
81mod substitution_property_tests;
82pub mod suggest;
83pub mod targets;
84pub mod userconfig;
85pub mod verdict;
86
87pub use verdict::{SafetyLevel, Verdict};
88
89/// The facet profile behind a verdict, rendered for `--explain`.
90///
91/// Answers the question the boolean cannot: not "is this allowed" but "on which axis was it
92/// refused". Empty when no resolver claims the command — that is the answer too, since it means the
93/// legacy classifier decided and there are no facets to show.
94pub fn facet_breakdown(command: &str) -> String {
95 // One simple command only. `shell_words` has no idea what `&&` means, so on a chain it hands
96 // back one flat token list and the resolver reads the SECOND command's arguments as flags of
97 // the first — `aws dynamodb scan --table-name t && rm -rf /` produced a single worst-case
98 // profile belonging to neither segment. A diagnostic that invents a capability set no resolver
99 // emitted is worse than silence, and `render()` above already breaks the chain down per segment.
100 if cst::explain(command).segments.len() != 1 {
101 return "\n (facet breakdown covers one command at a time; run --explain on a single segment)\n".to_string();
102 }
103 // A COMPOUND is one segment, so it reaches here — but the flat split cannot see into it.
104 // `(cat ~/.ssh/id_rsa)` tokenises to `["(cat", "~/.ssh/id_rsa)"]`, no resolver recognises
105 // `(cat`, and the refusal rendered with no reason at all. The command the caller has to change
106 // is INSIDE the construct, so describe that one and say so.
107 let inner = cst::denied_inner_words(command);
108 let words = match inner {
109 Some(ref w) => w.clone(),
110 None => match shell_words::split(command) {
111 Ok(w) => w,
112 Err(_) => return String::new(),
113 },
114 };
115 if words.is_empty() {
116 return String::new();
117 }
118 let tokens: Vec<parse::Token> = words.into_iter().map(parse::Token::from_raw).collect();
119 let Some(ex) = engine::bridge::explain_profile(&tokens) else {
120 return String::new();
121 };
122 let mut out = String::from("\n resolved profile:\n");
123 if let Some(w) = &inner {
124 out.push_str(&format!(" (the refused command inside it: `{}`)\n", w.join(" ")));
125 }
126 out.push_str(&engine::plain::render(&ex));
127 out
128}
129
130pub fn is_safe_command(command: &str) -> bool {
131 command_verdict(command).is_allowed()
132}
133
134pub fn command_verdict(command: &str) -> Verdict {
135 cst::command_verdict(command)
136}
137
138/// Classify `command` against a named level. Every engine-resolved leaf is decided by
139/// `Level::admits` against `level` rather than by walking the band; a `Denied` on any segment
140/// dominates. Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict.
141///
142/// A pass returns the band the PROFILE earns (`to_legacy`), so the caller's `<= ceiling` gate
143/// still tightens — that is what lets `reader` (SafeRead) and `paranoid` (Inert) use this path at
144/// all. Upper-band levels have no legacy equivalent and keep the shared `SafeWrite`.
145pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
146 let _guard = engine::bridge::enter_eval_level(level);
147 cst::command_verdict(command)
148}
149
150/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
151/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
152/// (legacy aliases already resolved).
153pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
154 if !matches!(name, "local-admin" | "network-admin" | "yolo") {
155 return None;
156 }
157 engine::authoring::default_levels().iter().find(|l| l.name == name)
158}
159
160/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
161/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
162/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
163/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
164/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
165/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
166pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
167 let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
168 let canonical = legacy_of.unwrap_or(name);
169 // EVERY named level classifies through `admits`. The levels are `extends`-chained
170 // (paranoid ⊂ reader ⊂ editor ⊂ developer ⊂ admin ⊂ yolo), so one mechanism across the whole
171 // ladder makes it monotone BY CONSTRUCTION: whatever a level admits, every looser level
172 // inherits.
173 //
174 // Only `editor` and the upper band used to, for a reason that turned out to be a bug rather
175 // than a design: `project` stamped every pass `SafeWrite`, which the `<= threshold` gate then
176 // refused at any lower ceiling, so handing `reader` an engine level denied its entire band
177 // (measured: 157 commands, `cat ./notes.txt` among them). With `project` returning the band
178 // the profile actually earns, that is gone.
179 //
180 // The mixture was itself the `level_monotonic` fuzz failure — `editor` decided by `admits`
181 // while `reader` and `developer` decided by projection, and nothing made two mechanisms
182 // adjacent in one ordered ladder agree.
183 let engine_level = match canonical {
184 "paranoid" | "reader" | "editor" | "developer" | "local-admin" | "network-admin" | "yolo" => {
185 engine::authoring::default_levels().iter().find(|l| l.name == canonical)
186 }
187 _ => None,
188 };
189 Some((ceiling, engine_level))
190}
191
192/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
193/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
194/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
195/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
196/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
197pub fn command_verdict_ceilinged(command: &str, threshold: SafetyLevel, engine_level: Option<&'static engine::level::Level>) -> Verdict {
198 let verdict = match engine_level {
199 Some(level) => command_verdict_at_level(command, level),
200 None => command_verdict(command),
201 };
202 match verdict {
203 Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
204 _ => Verdict::Denied,
205 }
206}
207
208/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
209/// computed UNDER the configured engine level so a covered command honors that level's rule — a
210/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
211/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
212/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
213/// tighter rule could leak through.
214/// Whether Claude Code's OWN permission files may contribute trust to this run.
215///
216/// safe-chains reads two things out of `~/.claude/settings.json`: `permissions.allow` command
217/// patterns (the coverage bridge, `allowlist.rs`) and `Read(...)` path approvals (the grant bridge,
218/// `regions.rs`). Both were loaded unconditionally, on every harness — so a file that exists purely
219/// to configure Claude Code was silently granting permissions under Codex, Cursor, Grok and agy.
220///
221/// On Codex that is not academic. Codex has no interactive approval, which is why safe-chains
222/// DENIES a gated command there; with a `Bash(curl:*)` rule sitting in the Claude file,
223/// `curl … | sh` went from denied to abstain, and abstain on Codex means it simply runs.
224///
225/// Defaults to FALSE, so a harness safe-chains does not recognize never inherits another tool's
226/// grants. Only the Claude target turns it on.
227static CLAUDE_CONFIG_TRUSTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
228
229/// Honor `~/.claude/settings.json` as a source of trust for the rest of this process.
230pub fn trust_claude_config() {
231 CLAUDE_CONFIG_TRUSTED.store(true, std::sync::atomic::Ordering::Relaxed);
232}
233
234pub(crate) fn claude_config_trusted() -> bool {
235 CLAUDE_CONFIG_TRUSTED.load(std::sync::atomic::Ordering::Relaxed)
236}
237
238pub fn explain_with_coverage_at_level(command: &str, engine_level: Option<&'static engine::level::Level>) -> cst::Explanation {
239 let patterns = allowlist::Matcher::load();
240 let _guard = engine_level.map(engine::bridge::enter_eval_level);
241 cst::explain_with_coverage(command, &patterns)
242}
243
244/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
245/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
246/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
247/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
248pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
249 registry::user_config_level()
250 .and_then(|name| level_ceiling(&name))
251 .unwrap_or((SafetyLevel::SafeWrite, None))
252}
253
254/// Classify `command` with the harness-supplied directory context installed (HP-19), so
255/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
256/// no-context form (`PathCtx::default()`), preserving every existing caller.
257pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
258 let _guard = pathctx::enter(ctx);
259 cst::command_verdict(command)
260}
261
262/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
263/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
264/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
265/// "directory parsing is broken".
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum ReachReason {
268 /// A known credential store (`.ssh`, `.aws`, keychain…).
269 Credential,
270 /// A file safe-chains reads its OWN permissions from (`~/.config/safe-chains.toml`,
271 /// `~/.claude/settings.json`). Distinct from `OutsideWorkspace` because the generic remedy
272 /// there — grant the path — is not merely unhelpful but FALSE: the write face is frozen, so
273 /// following the advice changes nothing. For safe-chains' own config it is also circular,
274 /// telling the user to edit the file they are being stopped from editing.
275 FrozenTrustFile,
276 /// The DIRECTORY a trust file lives in. Distinct from `FrozenTrustFile` because only HALF of
277 /// it is refused: writing a file into `~/.config` is ordinary and stays allowed, and only
278 /// removing or replacing the directory is not. Copy that said "this is refused" flatly would
279 /// misdescribe a directory the user explicitly granted.
280 FrozenTrustRoot,
281 /// One of the files that decide who may log in (`/etc/passwd`, `/etc/sudoers`, `/etc/pam.d`,
282 /// the loader and boot). Same false-remedy problem as `FrozenTrustFile`.
283 FrozenSystemIntegrity,
284 /// A raw block or character device (`/dev/mem`, `/dev/rdisk0`, `/dev/sda`). Distinct from
285 /// `FrozenSystemIntegrity` because the `device` rung outranks `system-integrity`, so without
286 /// its own arm every device was explained as a file that "decides who may log in" — which is
287 /// both false and unhelpful about the thing that actually makes a device dangerous.
288 RawDevice,
289 /// Genuinely above/outside the working directory.
290 OutsideWorkspace,
291 /// A path built by an interpolation that nothing confines (`./out/$i`, `> $(cmd)`). It is not
292 /// outside anything — it names WHATEVER the value turns out to be, which is why it cannot be
293 /// admitted — so the remedy is to constrain the spelling, not to grant a directory.
294 Unconfined,
295 /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
296 /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
297 /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
298 /// how to bless it rather than implying the agent did something wrong.
299 ForeignTemp,
300}
301
302/// Render command-derived text safely INSIDE one of our messages.
303///
304/// The explanation is read by a human deciding whether to approve, and on the Claude and Qwen
305/// targets it is injected into the model's context as `additionalContext`. Command text is not
306/// trustworthy input for either job: a command routinely carries data the agent picked up from a
307/// file, an issue title, a downloaded manifest. Echoed raw, a newline in it forged a whole extra
308/// line of our OWN output —
309///
310/// ```text
311/// ✗ cat "/etc/x
312/// ✓ ls safe-chains: auto-approves.
313/// ```
314///
315/// — so the reader saw an approval that never happened, in our voice. Escaping the control
316/// characters keeps any echoed text to a single line of literal content, which is the property
317/// that makes forging a second line impossible. Bidi controls go too: they reorder what is
318/// DISPLAYED without changing the bytes, which is the same forgery by other means.
319///
320/// This neutralizes our own OUTPUT. It is not a check on the command and decides nothing.
321/// Render our INTERNAL substitution markers back as `$(…)` before any of them reach a human.
322///
323/// A path carrying a substitution is classified through a sentinel, and the operand the nudge
324/// reports is the expanded form — so the reader of `cat ~/p/out/$(seq 1 1)` was being shown
325/// `~/p/out/__SAFE_CHAINS_CMDSUB_ATOM__`, a path they never wrote. On the Claude and Qwen targets
326/// this text is injected into the MODEL's context, where an internal marker is worse than noise:
327/// it is a magic string the model can learn and start emitting, and a nudge that describes a path
328/// the user cannot find in their own command is one they have no reason to trust.
329///
330/// Covers every sentinel spelling at once — opaque, atom, and the locus-tagged forms — by keying
331/// on the shared prefix and consuming through the terminating `__`, so a sentinel added later is
332/// rendered without touching this. Text that merely LOOKS like a sentinel keeps its tail — only
333/// the marker itself is replaced — because what follows a bare prefix is the user's path, not our
334/// internals, and dropping it handed a crafted filename control over how much of the path the
335/// reader saw.
336fn render_sentinels(s: &str) -> std::borrow::Cow<'_, str> {
337 let prefix = cst::eval::TAGGED_PREFIX;
338 if !s.contains(prefix) {
339 return std::borrow::Cow::Borrowed(s);
340 }
341 let mut out = String::with_capacity(s.len());
342 let mut rest = s;
343 while let Some(at) = rest.find(prefix) {
344 out.push_str(&rest[..at]);
345 out.push_str("$(…)");
346 let after = &rest[at + prefix.len()..];
347 rest = if let Some(tail) = after.strip_prefix('_') {
348 // The opaque marker is the prefix plus a single `_`.
349 tail
350 } else if let Some(i) = after.find("__") {
351 // Atom and locus-tagged markers are the prefix, a term, then `__`.
352 &after[i + 2..]
353 } else {
354 // Not one of ours. Keep the text: dropping it let a CRAFTED filename decide how much
355 // of the path a human was shown — `cat ~/__SAFE_CHAINS_CMDSUB_.ssh/id_rsa` reported
356 // reaching `~/$(…)`, hiding `.ssh/id_rsa` from the one message used to decide.
357 after
358 };
359 }
360 out.push_str(rest);
361 std::borrow::Cow::Owned(out)
362}
363
364pub fn sanitize_display(s: &str) -> String {
365 let s = &render_sentinels(s);
366 let mut out = String::with_capacity(s.len());
367 for c in s.chars() {
368 match c {
369 '\n' => out.push_str("\\n"),
370 '\r' => out.push_str("\\r"),
371 '\t' => out.push_str("\\t"),
372 // C0/C1 controls, and the bidi overrides/isolates/marks.
373 c if c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}') => {
374 out.push_str(&format!("\\u{{{:04x}}}", c as u32));
375 }
376 c => out.push(c),
377 }
378 }
379 out
380}
381
382impl ReachReason {
383 /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
384 /// Callers add their own framing (block / please-confirm) and the docs link.
385 /// Whether naming this path in `~/.config/safe-chains.toml` actually changes the verdict.
386 ///
387 /// The refusal copy offers a grant, or explains that granting will not help, and the two must
388 /// not diverge: advice that does nothing costs more than silence, because the reader follows
389 /// it, sees no change, and stops believing the rest. `a_refusal_offers_a_grant_only_when_one_
390 /// would_work` runs the verdict twice — once with the grant applied — and holds this to it.
391 ///
392 /// `Credential` is `true` as of 2026-09-01 and was `false` before it. A grant naming a store
393 /// used to move the locus and leave `reads_secret` set, so the message's "name that path"
394 /// advice was FALSE while reading exactly right. That is the failure this pairing exists to
395 /// catch, and it went unnoticed because nothing compared the sentence to the behaviour.
396 pub fn grant_helps(self) -> bool {
397 match self {
398 // A grant that NAMES the store clears the shield for reading it.
399 ReachReason::Credential | ReachReason::RawDevice => true,
400 // "That IS my working directory" is the usual answer here.
401 ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
402 // Frozen faces stay frozen however specifically they are named: an agent that can edit
403 // the trust file decides what is approved next, and one that can write `/etc/sudoers`
404 // owns the machine's authorization substrate.
405 ReachReason::FrozenTrustFile | ReachReason::FrozenTrustRoot | ReachReason::FrozenSystemIntegrity => false,
406 // There is no path to grant. The remedy is to constrain the spelling.
407 ReachReason::Unconfined => false,
408 }
409 }
410
411 pub fn message(self, path: &str) -> String {
412 let path = &sanitize_display(path);
413 match self {
414 ReachReason::Credential => format!(
415 "it reaches `{path}`, a credential store. The agent has no ordinary reason to touch \
416 one. If that was not intended, stop it. If you do want to allow it, name that path \
417 in ~/.config/safe-chains.toml. A grant on a parent directory does not reach a \
418 credential store"
419 ),
420 ReachReason::RawDevice => format!(
421 "it reaches `{path}`, a raw device. Reading one is not reading a file — a disk \
422 device hands over every file on it and memory hands over every secret in it — and \
423 writing one goes underneath the filesystem entirely. If you do want the read, \
424 name that path in ~/.config/safe-chains.toml; the write stays refused"
425 ),
426 ReachReason::FrozenTrustFile => format!(
427 "it reaches `{path}`. safe-chains reads its own permissions from that file, so a \
428 write there is never auto-approved. Granting the path does not change that, \
429 because an agent that can edit this file can decide what gets approved next. Edit \
430 it yourself if you meant to change it"
431 ),
432 ReachReason::FrozenTrustRoot => format!(
433 "it reaches `{path}`. safe-chains reads its own permissions from a file in that \
434 directory, so removing or replacing the directory itself is never auto-approved: \
435 doing that would point the trust root somewhere else. Writing files into it is \
436 fine, and granting the path does not change either half. Move or delete it \
437 yourself if you meant to"
438 ),
439 ReachReason::FrozenSystemIntegrity => format!(
440 "it reaches `{path}`. That file decides who may log in and what they may do, so a \
441 write there is never auto-approved. Granting the path does not change that. Edit \
442 it yourself if you meant to change it"
443 ),
444 ReachReason::ForeignTemp => format!(
445 "it runs code from `{path}`, a temporary directory that is not this session's \
446 scratchpad. Reading and writing temp files is fine. Running code from there is \
447 not, because a downloaded script lands in the same place. If this is a working \
448 directory you trust, grant it in ~/.config/safe-chains.toml. A scratchpad the \
449 harness reports for this session is recognized on its own and needs no grant"
450 ),
451 ReachReason::Unconfined => format!(
452 "the path `{path}` is built by an interpolation, so what it names depends on a \
453 value the command does not show. It could be anywhere, which is why it cannot be \
454 auto-approved. If the interpolated part cannot contain a `/`, put literal text \
455 beside it in the same path component. `out/dx_$i.txt` is approved where `out/$i` \
456 is not: the first is a filename whatever `$i` holds, and the second could be `..`"
457 ),
458 ReachReason::OutsideWorkspace => match pathctx::cwd().map(|c| sanitize_display(&c)) {
459 Some(cwd) => format!(
460 "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
461 running from the wrong directory, relaunch it where you meant to be. To allow \
462 it from here, grant that path in ~/.config/safe-chains.toml"
463 ),
464 None => format!(
465 "it reaches `{path}`, outside the working directory. To allow it, grant that \
466 path in ~/.config/safe-chains.toml"
467 ),
468 },
469 }
470 }
471}
472
473/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path (its
474/// original spelling) and WHY, so the hook can nudge instead of silently prompting. Resolves against
475/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
476/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
477/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
478/// outside-workspace reason.
479pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
480 let tokens = operand_words(command)?;
481 tokens.into_iter().find_map(|t| {
482 if !policy::looks_like_path(&t) {
483 return None;
484 }
485 let resolved = pathctx::resolve(&t).into_owned();
486 // A temp path is READ/WRITE admitted, so the outside-test below never fires on it — but it
487 // is not EXECUTABLE unless it is this session's scratchpad. When the command was denied,
488 // that is the likely reason, and it is the one case where the fix is a grant rather than a
489 // correction, so surface it with those instructions.
490 if pathctx::under_temp_root(&resolved) && !pathctx::in_session_scratchpad(&resolved) {
491 return Some((t, ReachReason::ForeignTemp));
492 }
493 // The REBIND face is consulted too, or a granted trust-root directory denies in silence:
494 // the grant opens read and write, so `rm -rf ~/.config` looked ordinary here while the
495 // engine refused it. Only the trust-root directories can make this term true, since every
496 // other role's rebind face equals its write face.
497 let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
498 && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
499 || !engine::resolve::write_target_verdict(&resolved).is_allowed()
500 || engine::resolve::rebind_is_stricter_than_write(&resolved));
501 if !outside {
502 return None;
503 }
504 // Asked on the LITERAL structure, so an interpolated component cannot strip the credential
505 // warning off a path that plainly names one. `cat ~/.ssh/$(id)` was reported as merely
506 // "built by an interpolation" — offering to flank it, which can never help, while dropping
507 // the one sentence that matters — and the CONFINED spelling fell through to
508 // "outside the working directory", whose remedy is to GRANT the path.
509 //
510 // Granting a credential store IS possible now (a grant covers what it names), so the
511 // objection is no longer "that remedy cannot work". It is that the generic wording says
512 // "grant that path" while meaning the ordinary parent-directory grant, which is exactly
513 // the form a credential store does not accept. The Credential arm spells out the
514 // difference instead.
515 let reason = if engine::resolve::names_credential_store(&resolved) {
516 ReachReason::Credential
517 } else if let Some(kind) = engine::resolve::frozen_write_kind(&resolved) {
518 // Ahead of Unconfined and OutsideWorkspace for the same reason Credential is: both of
519 // those end in "grant that path", which for a frozen write face is FALSE rather than
520 // merely vague, and for safe-chains' own config it is circular as well.
521 match kind {
522 engine::resolve::FrozenWrite::TrustFile => ReachReason::FrozenTrustFile,
523 engine::resolve::FrozenWrite::TrustRootDir => ReachReason::FrozenTrustRoot,
524 engine::resolve::FrozenWrite::SystemIntegrity => ReachReason::FrozenSystemIntegrity,
525 engine::resolve::FrozenWrite::RawDevice => ReachReason::RawDevice,
526 }
527 } else if engine::resolve::anchoring_of(&resolved) == crate::engine::facet::Anchoring::Opaque {
528 // Ahead of OutsideWorkspace because it is the more specific diagnosis of the SAME
529 // refusal, and the generic wording actively misleads here: it names a working-directory
530 // problem the user does not have and a remedy (grant the path) that cannot work,
531 // since the path is not a fixed path at all.
532 ReachReason::Unconfined
533 } else {
534 ReachReason::OutsideWorkspace
535 };
536 Some((t, reason))
537 })
538}
539
540/// The words a command actually RUNS with, for explaining a denial.
541///
542/// This must agree with the parse the verdict came from, so it walks the CST. Splitting the raw
543/// string instead (`shell_words::split`) tokenizes text the shell never treats as an argument —
544/// above all a heredoc BODY, which is data. `git commit -m "$(cat <<'EOF' … EOF)"` whose message
545/// merely MENTIONS `/etc/hosts` was reported as "reaches /etc/hosts", naming a false reason for the
546/// denial and advising the reader to grant that path — a config widening the command never needed.
547///
548/// Falls back to the raw split only when the command does not parse, where a best-effort nudge on
549/// approximate tokens still beats none.
550fn operand_words(command: &str) -> Option<Vec<String>> {
551 let Some(script) = cst::parse(command) else {
552 return shell_words::split(command).ok();
553 };
554 let mut out = Vec::new();
555 collect_script_words(&script, &mut out);
556 Some(out)
557}
558
559/// A word contributes its own expansions AND the words of any command substitution inside it: the
560/// inner command runs, so `notacommand $(cat /etc/shadow)` really does read the file, even though
561/// `expand()` renders the substitution as an opaque stand-in and hides the path.
562fn collect_word(word: &cst::Word, out: &mut Vec<String>) {
563 out.extend(word.expand());
564 for part in &word.0 {
565 collect_part_subs(part, out);
566 }
567}
568
569/// The words of any command SUBSTITUTION inside a word part, and nothing else — the part's own
570/// literal text is the caller's business, because whether it counts as an operand depends on where
571/// the word came from (a heredoc body's literal text never does).
572fn collect_part_subs(part: &cst::WordPart, out: &mut Vec<String>) {
573 use cst::WordPart;
574 match part {
575 WordPart::CmdSub(script) | WordPart::ProcSub(script) => collect_script_words(script, out),
576 WordPart::DQuote(inner) => collect_word(inner, out),
577 // Arithmetic contributes no operand of its own — its value is a number — but a `$( )`
578 // inside it runs, and that command's words are operands the verdict layer classifies.
579 WordPart::Arith(inner) => collect_word(inner, out),
580 WordPart::Lit(_) | WordPart::Escape(_) | WordPart::SQuote(_) | WordPart::AnsiC(_) | WordPart::Backtick(_) => {}
581 }
582}
583
584fn collect_script_words(script: &cst::Script, out: &mut Vec<String>) {
585 for stmt in &script.0 {
586 for cmd in &stmt.pipeline.commands {
587 collect_cmd_words(cmd, out);
588 }
589 }
590}
591
592/// A redirect TARGET is a path the command opens, so it is a reach and must be reported —
593/// `notacommand > /etc/passwd` names `/etc/passwd`. A heredoc DELIMITER is not a path at all, and
594/// its body never appears in the CST, which is the whole point.
595fn collect_redir_words(redirs: &[cst::Redir], out: &mut Vec<String>) {
596 use cst::Redir;
597 for redir in redirs {
598 match redir {
599 Redir::Write { target, .. } | Redir::Read { target, .. } | Redir::ReadWrite { target, .. } | Redir::HereStr(target) => {
600 collect_word(target, out)
601 }
602 // Only the body's SUBSTITUTIONS, never its literal text. Behind a bare delimiter a
603 // `$(cat /etc/shadow)` in the body really runs, so it is a reach worth naming; the
604 // prose around it is data and naming it would state a false reason for the denial.
605 Redir::HereDoc { body, .. } => {
606 for part in &body.0 {
607 collect_part_subs(part, out);
608 }
609 }
610 Redir::DupFd { .. } => {}
611 }
612 }
613}
614
615fn collect_cmd_words(cmd: &cst::Cmd, out: &mut Vec<String>) {
616 use cst::Cmd;
617 let words = |ws: &[cst::Word], out: &mut Vec<String>| {
618 for w in ws {
619 collect_word(w, out);
620 }
621 };
622 match cmd {
623 Cmd::Simple(s) => {
624 words(&s.words, out);
625 collect_redir_words(&s.redirs, out);
626 }
627 Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
628 collect_script_words(body, out);
629 collect_redir_words(redirs, out);
630 }
631 Cmd::For { items, body, redirs, .. } => {
632 words(items, out);
633 collect_script_words(body, out);
634 collect_redir_words(redirs, out);
635 }
636 Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
637 collect_script_words(cond, out);
638 collect_script_words(body, out);
639 collect_redir_words(redirs, out);
640 }
641 Cmd::If { branches, else_body, redirs } => {
642 collect_redir_words(redirs, out);
643 for branch in branches {
644 collect_script_words(&branch.cond, out);
645 collect_script_words(&branch.body, out);
646 }
647 if let Some(body) = else_body {
648 collect_script_words(body, out);
649 }
650 }
651 Cmd::DoubleBracket { words: ws, redirs } => {
652 words(ws, out);
653 collect_redir_words(redirs, out);
654 }
655 Cmd::Case { subject, arms, redirs } => {
656 collect_word(subject, out);
657 for arm in arms {
658 collect_script_words(&arm.body, out);
659 }
660 collect_redir_words(redirs, out);
661 }
662 Cmd::FunctionDef { body, .. } => collect_script_words(body, out),
663 }
664}
665
666#[cfg(test)]
667mod tests;