safe_chains/lib.rs
1// The generated test names spell the command and its flags verbatim, and FLAG CASE IS MEANINGFUL:
2// find takes both `-D` and `-d`, `-P` and `-p`, `-L` and `-l`, and commands like `asn1Decoding` and
3// `checkLocalKDC` are camel-case upstream. Lowercasing to satisfy `non_snake_case` would erase the
4// distinction the test exists to pin, so the generated items opt out instead.
5#[cfg(test)]
6macro_rules! safe {
7 ($($name:ident: $cmd:expr),* $(,)?) => {
8 $(#[test] #[allow(non_snake_case)] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
9 };
10}
11
12#[cfg(test)]
13macro_rules! denied {
14 ($($name:ident: $cmd:expr),* $(,)?) => {
15 $(#[test] #[allow(non_snake_case)] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
16 };
17}
18
19#[cfg(test)]
20macro_rules! inert {
21 ($($name:ident: $cmd:expr),* $(,)?) => {
22 $(#[test] #[allow(non_snake_case)] fn $name() {
23 assert_eq!(
24 crate::command_verdict($cmd),
25 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::Inert),
26 "expected Inert: {}", $cmd,
27 );
28 })*
29 };
30}
31
32#[cfg(test)]
33macro_rules! safe_read {
34 ($($name:ident: $cmd:expr),* $(,)?) => {
35 $(#[test] #[allow(non_snake_case)] fn $name() {
36 assert_eq!(
37 crate::command_verdict($cmd),
38 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
39 "expected SafeRead: {}", $cmd,
40 );
41 })*
42 };
43}
44
45#[cfg(test)]
46macro_rules! safe_write {
47 ($($name:ident: $cmd:expr),* $(,)?) => {
48 $(#[test] #[allow(non_snake_case)] fn $name() {
49 assert_eq!(
50 crate::command_verdict($cmd),
51 crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite),
52 "expected SafeWrite: {}", $cmd,
53 );
54 })*
55 };
56}
57
58pub mod cli;
59#[cfg(test)]
60mod composition;
61pub mod cst;
62#[cfg(test)]
63mod handler_property_tests;
64pub mod docs;
65pub mod engine;
66mod envvars;
67mod handlers;
68pub mod netloc;
69pub mod parse;
70pub mod pathctx;
71pub mod pathgate;
72pub mod policy;
73pub mod registry;
74pub mod suggest;
75pub mod allowlist;
76pub mod targets;
77pub mod verdict;
78
79pub use verdict::{SafetyLevel, Verdict};
80
81/// The facet profile behind a verdict, rendered for `--explain`.
82///
83/// Answers the question the boolean cannot: not "is this allowed" but "on which axis was it
84/// refused". Empty when no resolver claims the command — that is the answer too, since it means the
85/// legacy classifier decided and there are no facets to show.
86pub fn facet_breakdown(command: &str) -> String {
87 // One simple command only. `shell_words` has no idea what `&&` means, so on a chain it hands
88 // back one flat token list and the resolver reads the SECOND command's arguments as flags of
89 // the first — `aws dynamodb scan --table-name t && rm -rf /` produced a single worst-case
90 // profile belonging to neither segment. A diagnostic that invents a capability set no resolver
91 // emitted is worse than silence, and `render()` above already breaks the chain down per segment.
92 if cst::explain(command).segments.len() != 1 {
93 return "\n (facet breakdown covers one command at a time; run --explain on a single segment)\n"
94 .to_string();
95 }
96 let Ok(words) = shell_words::split(command) else {
97 return String::new();
98 };
99 if words.is_empty() {
100 return String::new();
101 }
102 let tokens: Vec<parse::Token> = words.into_iter().map(parse::Token::from_raw).collect();
103 let Some(ex) = engine::bridge::explain_profile(&tokens) else {
104 return String::new();
105 };
106 let mut out = String::from("\n resolved profile:\n");
107 for (because, facets) in &ex.capabilities {
108 out.push_str(&format!(" · {because}\n"));
109 for (name, term) in facets {
110 out.push_str(&format!(" {name:<28} {term}\n"));
111 }
112 }
113 match &ex.blocked_by {
114 Some((level, mismatch)) => {
115 out.push_str(&format!(
116 "\n refused by `{level}` (the most permissive auto-approving level):\n {mismatch}\n",
117 ));
118 }
119 None => out.push_str("\n admitted by the auto-approve band.\n"),
120 }
121 out
122}
123
124pub fn is_safe_command(command: &str) -> bool {
125 command_verdict(command).is_allowed()
126}
127
128pub fn command_verdict(command: &str) -> Verdict {
129 cst::command_verdict(command)
130}
131
132/// Classify `command` against an UPPER-band level (`local-admin`/`network-admin`/`yolo`), which
133/// has no 3-value legacy ceiling. Every engine-resolved leaf is decided by `Level::admits`
134/// against `level` instead of the lower-band projection; a `Denied` on any segment dominates.
135/// Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict, which every
136/// upper level admits. The result is `Allowed(SafeWrite)` (accepted by the shared upper ceiling)
137/// or `Denied`.
138pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
139 let _guard = engine::bridge::enter_eval_level(level);
140 cst::command_verdict(command)
141}
142
143/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
144/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
145/// (legacy aliases already resolved).
146pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
147 if !matches!(name, "local-admin" | "network-admin" | "yolo") {
148 return None;
149 }
150 engine::authoring::default_levels().iter().find(|l| l.name == name)
151}
152
153/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
154/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
155/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
156/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
157/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
158/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
159pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
160 let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
161 let canonical = legacy_of.unwrap_or(name);
162 // Levels whose rule the 3-band projection can't express classify per-level via `admits`:
163 // `editor` (no destroy, no sibling write — distinct from developer) and the UPPER band (git push,
164 // bulk-object-read, sudo — above the band). `paranoid`/`reader` are pure ceilings (their
165 // inert/read bands need no `admits`; the `<= threshold` gate tightens), and `developer` IS the
166 // default band — those carry no engine level.
167 let engine_level = match canonical {
168 "editor" | "local-admin" | "network-admin" | "yolo" => {
169 engine::authoring::default_levels().iter().find(|l| l.name == canonical)
170 }
171 _ => None,
172 };
173 Some((ceiling, engine_level))
174}
175
176/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
177/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
178/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
179/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
180/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
181pub fn command_verdict_ceilinged(
182 command: &str,
183 threshold: SafetyLevel,
184 engine_level: Option<&'static engine::level::Level>,
185) -> Verdict {
186 let verdict = match engine_level {
187 Some(level) => command_verdict_at_level(command, level),
188 None => command_verdict(command),
189 };
190 match verdict {
191 Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
192 _ => Verdict::Denied,
193 }
194}
195
196/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
197/// computed UNDER the configured engine level so a covered command honors that level's rule — a
198/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
199/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
200/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
201/// tighter rule could leak through.
202pub fn explain_with_coverage_at_level(
203 command: &str,
204 engine_level: Option<&'static engine::level::Level>,
205) -> cst::Explanation {
206 let patterns = allowlist::Matcher::load();
207 let _guard = engine_level.map(engine::bridge::enter_eval_level);
208 cst::explain_with_coverage(command, &patterns)
209}
210
211/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
212/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
213/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
214/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
215pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
216 registry::user_config_level()
217 .and_then(|name| level_ceiling(&name))
218 .unwrap_or((SafetyLevel::SafeWrite, None))
219}
220
221/// Classify `command` with the harness-supplied directory context installed (HP-19), so
222/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
223/// no-context form (`PathCtx::default()`), preserving every existing caller.
224pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
225 let _guard = pathctx::enter(ctx);
226 cst::command_verdict(command)
227}
228
229/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
230/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
231/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
232/// "directory parsing is broken".
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum ReachReason {
235 /// A known credential store (`.ssh`, `.aws`, keychain…).
236 Credential,
237 /// A HIDDEN file inside a co-located peer project — the peer's ordinary source is readable as
238 /// `adjacent`, but its dotfiles/dotdirs are shielded.
239 HiddenPeer,
240 /// Genuinely above/outside the working directory.
241 OutsideWorkspace,
242 /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
243 /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
244 /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
245 /// how to bless it rather than implying the agent did something wrong.
246 ForeignTemp,
247}
248
249impl ReachReason {
250 /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
251 /// Callers add their own framing (block / please-confirm) and the docs link.
252 pub fn message(self, path: &str) -> String {
253 match self {
254 ReachReason::Credential => format!(
255 "it reaches `{path}`, a credential store the agent should almost certainly not touch. \
256 If this was not intended, stop it"
257 ),
258 ReachReason::HiddenPeer => format!(
259 "it reaches `{path}`, a HIDDEN file inside a co-located peer project. The peer's \
260 ordinary source is readable, but its hidden files (`.env`, `.git`, `.aws`, …) are \
261 shielded — this is a deliberate guard, not a path error. To reach it, grant that \
262 path in ~/.config/safe-chains.toml, or run the agent from the peer's parent \
263 directory so the peer counts as in-workspace"
264 ),
265 ReachReason::ForeignTemp => format!(
266 "it runs code from `{path}`, a temporary directory that is not this session's \
267 scratchpad. Temp files can be read and written freely, but code there is treated \
268 as FOREIGN (a downloaded script lands in the same place), so running it is not \
269 auto-approved. If this is a working directory you trust, grant it in \
270 ~/.config/safe-chains.toml; a scratchpad the harness reports for this session is \
271 recognized automatically and needs no grant"
272 ),
273 ReachReason::OutsideWorkspace => match pathctx::cwd() {
274 Some(cwd) => format!(
275 "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
276 running from the wrong directory — an easy thing to forget — relaunch it where \
277 you meant to be; to allow it from here, grant that path in \
278 ~/.config/safe-chains.toml"
279 ),
280 None => format!(
281 "it reaches `{path}`, outside the working directory. To allow it, grant that \
282 path in ~/.config/safe-chains.toml"
283 ),
284 },
285 }
286 }
287}
288
289/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path (its
290/// original spelling) and WHY, so the hook can nudge instead of silently prompting. Resolves against
291/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
292/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
293/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
294/// outside-workspace reason.
295pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
296 let tokens = shell_words::split(command).ok()?;
297 tokens.into_iter().find_map(|t| {
298 if !policy::looks_like_path(&t) {
299 return None;
300 }
301 let resolved = pathctx::resolve(&t).into_owned();
302 // A temp path is READ/WRITE admitted, so the outside-test below never fires on it — but it
303 // is not EXECUTABLE unless it is this session's scratchpad. When the command was denied,
304 // that is the likely reason, and it is the one case where the fix is a grant rather than a
305 // correction, so surface it with those instructions.
306 if pathctx::under_temp_root(&resolved) && !pathctx::in_session_scratchpad(&resolved) {
307 return Some((t, ReachReason::ForeignTemp));
308 }
309 let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
310 && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
311 || !engine::resolve::write_target_verdict(&resolved).is_allowed());
312 if !outside {
313 return None;
314 }
315 let reason = if engine::resolve::reads_secret(&resolved) {
316 ReachReason::Credential
317 } else if engine::resolve::hidden_peer_reach(&t) {
318 ReachReason::HiddenPeer
319 } else {
320 ReachReason::OutsideWorkspace
321 };
322 Some((t, reason))
323 })
324}
325
326#[cfg(test)]
327mod tests;