Skip to main content

safe_chains/
lib.rs

1#[cfg(test)]
2macro_rules! safe {
3    ($($name:ident: $cmd:expr),* $(,)?) => {
4        $(#[test] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
5    };
6}
7
8#[cfg(test)]
9macro_rules! denied {
10    ($($name:ident: $cmd:expr),* $(,)?) => {
11        $(#[test] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
12    };
13}
14
15#[cfg(test)]
16macro_rules! inert {
17    ($($name:ident: $cmd:expr),* $(,)?) => {
18        $(#[test] fn $name() {
19            assert_eq!(
20                crate::command_verdict($cmd),
21                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::Inert),
22                "expected Inert: {}", $cmd,
23            );
24        })*
25    };
26}
27
28#[cfg(test)]
29macro_rules! safe_read {
30    ($($name:ident: $cmd:expr),* $(,)?) => {
31        $(#[test] fn $name() {
32            assert_eq!(
33                crate::command_verdict($cmd),
34                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
35                "expected SafeRead: {}", $cmd,
36            );
37        })*
38    };
39}
40
41#[cfg(test)]
42macro_rules! safe_write {
43    ($($name:ident: $cmd:expr),* $(,)?) => {
44        $(#[test] fn $name() {
45            assert_eq!(
46                crate::command_verdict($cmd),
47                crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite),
48                "expected SafeWrite: {}", $cmd,
49            );
50        })*
51    };
52}
53
54pub mod cli;
55#[cfg(test)]
56mod composition;
57pub mod cst;
58#[cfg(test)]
59mod handler_property_tests;
60pub mod docs;
61pub mod engine;
62mod handlers;
63pub mod parse;
64pub mod pathctx;
65pub mod pathgate;
66pub mod policy;
67pub mod registry;
68pub mod allowlist;
69pub mod targets;
70pub mod verdict;
71
72pub use verdict::{SafetyLevel, Verdict};
73
74pub fn is_safe_command(command: &str) -> bool {
75    command_verdict(command).is_allowed()
76}
77
78pub fn command_verdict(command: &str) -> Verdict {
79    cst::command_verdict(command)
80}
81
82/// Classify `command` against an UPPER-band level (`local-admin`/`network-admin`/`yolo`), which
83/// has no 3-value legacy ceiling. Every engine-resolved leaf is decided by `Level::admits`
84/// against `level` instead of the lower-band projection; a `Denied` on any segment dominates.
85/// Legacy (unresolved) leaves keep their local-safe `SafeWrite`-or-below verdict, which every
86/// upper level admits. The result is `Allowed(SafeWrite)` (accepted by the shared upper ceiling)
87/// or `Denied`.
88pub fn command_verdict_at_level(command: &str, level: &'static engine::level::Level) -> Verdict {
89    let _guard = engine::bridge::enter_eval_level(level);
90    cst::command_verdict(command)
91}
92
93/// The `&'static Level` for an UPPER-band level name, or `None` for the lower band (which the
94/// 3-value ceiling already handles) or an unknown name. The caller passes the CANONICAL name
95/// (legacy aliases already resolved).
96pub fn upper_level_by_name(name: &str) -> Option<&'static engine::level::Level> {
97    if !matches!(name, "local-admin" | "network-admin" | "yolo") {
98        return None;
99    }
100    engine::authoring::default_levels().iter().find(|l| l.name == name)
101}
102
103/// Resolve a level NAME to its `(3-band ceiling, engine level for admits)`, or `None` for an unknown
104/// name. The ceiling gates the projected verdict; the engine level (when present) classifies per-level
105/// via `admits`, exposing distinctions the 3-band projection flattens — `editor` (no destroy, no
106/// sibling write) vs `developer`, and the upper band (git push, bulk-object-read, sudo). `paranoid`/
107/// `reader` are pure ceilings (their read/inert bands need no `admits`), and `developer` IS the default
108/// band, so those carry no engine level. Legacy aliases (`safe-write`) canonicalize first.
109pub fn level_ceiling(name: &str) -> Option<(SafetyLevel, Option<&'static engine::level::Level>)> {
110    let (ceiling, legacy_of) = verdict::SafetyLevel::resolve_threshold(name)?;
111    let canonical = legacy_of.unwrap_or(name);
112    // Levels whose rule the 3-band projection can't express classify per-level via `admits`:
113    // `editor` (no destroy, no sibling write — distinct from developer) and the UPPER band (git push,
114    // bulk-object-read, sudo — above the band). `paranoid`/`reader` are pure ceilings (their
115    // inert/read bands need no `admits`; the `<= threshold` gate tightens), and `developer` IS the
116    // default band — those carry no engine level.
117    let engine_level = match canonical {
118        "editor" | "local-admin" | "network-admin" | "yolo" => {
119            engine::authoring::default_levels().iter().find(|l| l.name == canonical)
120        }
121        _ => None,
122    };
123    Some((ceiling, engine_level))
124}
125
126/// The ceilinged verdict: classify `command` at `(threshold, engine_level)`, gating the projected
127/// level `<= threshold`. The single seam both the CLI (`--level`) and the hook (configured `level`)
128/// funnel through. `engine_level = Some` classifies via `Level::admits` (the fine per-level model);
129/// `None` uses the 3-band projection. Either way the result is gated to `threshold`, so a legacy leaf
130/// that bypasses the engine (a redirect write → `SafeWrite`) is still held under a lower ceiling.
131pub fn command_verdict_ceilinged(
132    command: &str,
133    threshold: SafetyLevel,
134    engine_level: Option<&'static engine::level::Level>,
135) -> Verdict {
136    let verdict = match engine_level {
137        Some(level) => command_verdict_at_level(command, level),
138        None => command_verdict(command),
139    };
140    match verdict {
141        Verdict::Allowed(level) if level <= threshold => Verdict::Allowed(level),
142        _ => Verdict::Denied,
143    }
144}
145
146/// The coverage-fallback explanation (built-in classifier + the user's `permissions.allow` patterns),
147/// computed UNDER the configured engine level so a covered command honors that level's rule — a
148/// worktree destroy an `editor` plan forbids classifies as denied here too, not re-admitted. `None`
149/// engine level → the plain 3-band coverage (paranoid/reader/default). The caller still gates the
150/// result's `overall <= threshold`; running under the level closes the last path a lower plan's
151/// tighter rule could leak through.
152pub fn explain_with_coverage_at_level(
153    command: &str,
154    engine_level: Option<&'static engine::level::Level>,
155) -> cst::Explanation {
156    let patterns = allowlist::Matcher::load();
157    let _guard = engine_level.map(engine::bridge::enter_eval_level);
158    cst::explain_with_coverage(command, &patterns)
159}
160
161/// The auto-approve ceiling the HOOK evaluates at, from the write-protected user config
162/// (`~/.config/safe-chains.toml`, `level = "…"`). No config, or an unknown name → the default
163/// `developer` band (`SafeWrite`, no engine level) — fail-safe. Honored ONLY from the user config,
164/// never a repo `.safe-chains.toml`; the file is write-denied, so an agent cannot set its own ceiling.
165pub fn configured_hook_ceiling() -> (SafetyLevel, Option<&'static engine::level::Level>) {
166    registry::user_config_level()
167        .and_then(|name| level_ceiling(&name))
168        .unwrap_or((SafetyLevel::SafeWrite, None))
169}
170
171/// Classify `command` with the harness-supplied directory context installed (HP-19), so
172/// relative paths resolve against the real `cwd`/`root`. `command_verdict(cmd)` is the
173/// no-context form (`PathCtx::default()`), preserving every existing caller.
174pub fn command_verdict_in(command: &str, ctx: pathctx::PathCtx) -> Verdict {
175    let _guard = pathctx::enter(ctx);
176    cst::command_verdict(command)
177}
178
179/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
180/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
181/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
182/// "directory parsing is broken".
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum ReachReason {
185    /// A known credential store (`.ssh`, `.aws`, keychain…).
186    Credential,
187    /// A HIDDEN file inside a co-located peer project — the peer's ordinary source is readable as
188    /// `adjacent`, but its dotfiles/dotdirs are shielded.
189    HiddenPeer,
190    /// Genuinely above/outside the working directory.
191    OutsideWorkspace,
192}
193
194impl ReachReason {
195    /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
196    /// Callers add their own framing (block / please-confirm) and the docs link.
197    pub fn message(self, path: &str) -> String {
198        match self {
199            ReachReason::Credential => format!(
200                "it reaches `{path}`, a credential store the agent should almost certainly not touch. \
201                 If this was not intended, stop it"
202            ),
203            ReachReason::HiddenPeer => format!(
204                "it reaches `{path}`, a HIDDEN file inside a co-located peer project. The peer's \
205                 ordinary source is readable, but its hidden files (`.env`, `.git`, `.aws`, …) are \
206                 shielded — this is a deliberate guard, not a path error. To reach it, grant that \
207                 path in ~/.config/safe-chains.toml, or run the agent from the peer's parent \
208                 directory so the peer counts as in-workspace"
209            ),
210            ReachReason::OutsideWorkspace => match pathctx::cwd() {
211                Some(cwd) => format!(
212                    "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
213                     running from the wrong directory — an easy thing to forget — relaunch it where \
214                     you meant to be; to allow it from here, grant that path in \
215                     ~/.config/safe-chains.toml"
216                ),
217                None => format!(
218                    "it reaches `{path}`, outside the working directory. To allow it, grant that \
219                     path in ~/.config/safe-chains.toml"
220                ),
221            },
222        }
223    }
224}
225
226/// If a NOT-auto-approved command reaches a path OUTSIDE the workspace, return that path (its
227/// original spelling) and WHY, so the hook can nudge instead of silently prompting. Resolves against
228/// the ambient `cwd`/`root`: relative worktree paths, `/tmp`, and `/dev` streams are admitted and
229/// skipped; an absolute or home path that isn't admitted for read *or* write is the reach. A
230/// credential store outranks the hidden-peer wording; a hidden peer path outranks the generic
231/// outside-workspace reason.
232pub fn workspace_overreach(command: &str) -> Option<(String, ReachReason)> {
233    let tokens = shell_words::split(command).ok()?;
234    tokens.into_iter().find_map(|t| {
235        if !policy::looks_like_path(&t) {
236            return None;
237        }
238        let resolved = pathctx::resolve(&t).into_owned();
239        let outside = (resolved.starts_with('/') || resolved.starts_with('~'))
240            && (!engine::resolve::read_content_verdict(&resolved).is_allowed()
241                || !engine::resolve::write_target_verdict(&resolved).is_allowed());
242        if !outside {
243            return None;
244        }
245        let reason = if engine::resolve::reads_secret(&resolved) {
246            ReachReason::Credential
247        } else if engine::resolve::hidden_peer_reach(&t) {
248            ReachReason::HiddenPeer
249        } else {
250            ReachReason::OutsideWorkspace
251        };
252        Some((t, reason))
253    })
254}
255
256#[cfg(test)]
257mod tests;