Skip to main content

safe_chains/explain_fix/
gate.rs

1//! Which kind of refusal a gated command is: one safe-chains has not approved YET, or a boundary.
2//!
3//! A harness that can put a command to a person in the moment (Grok's `ask`) can let a person decide
4//! the first kind, since nothing about it is known to be dangerous: there is simply no entry or grant
5//! for it. The second kind stays a hard refusal whatever the harness can do, because it is what
6//! safe-chains exists to stop an agent from getting through by asking: credentials, raw devices,
7//! the files safe-chains and the system read their trust from, the places whose contents run later
8//! without anyone being asked, other AI agents, and safe-chains' own rule edits.
9//!
10//! `NotYet` is the narrow answer and `Boundary` the default. A command is `NotYet` only when every
11//! check below passes; anything the checks cannot read with confidence is a `Boundary`, which is
12//! today's deny:
13//!
14//! - The command text holds nothing that makes its words unknowable before the shell runs it: no
15//!   `$` expansion, backtick, glob or brace, `~user`, change of directory, or program that runs code
16//!   it was handed or names (a shell, `eval`, an interpreter, `xargs`, `env`, a package runner), and
17//!   no `-P` cluster keeping absolute names.
18//! - With quotes and backslashes removed, no word of the WHOLE command (approved segments, function
19//!   bodies and `-c` strings included, attached option values too) names a protected place, a place
20//!   outside the workspace but for a temporary folder, a project file that runs later (`.git`,
21//!   `.envrc`, an agent's or editor's project settings), an AI agent or its package, or safe-chains.
22//!   Removing them can only join or split words, so this finds every name the shell would see.
23//! - No place the whole command reaches, by `workspace_reaches`, is protected.
24//! - Each refused segment's [`fix_for`] answer is an entry, a grant, a level, or a read of a
25//!   runs-later place, never a credential, a device, a frozen file, an agent or an interpolation.
26
27use super::{Because, Fix, fix_for};
28use crate::ReachReason;
29
30/// The kind of a gated command. See the module docs.
31#[derive(Clone, Copy, PartialEq, Eq, Debug)]
32pub enum GateKind {
33    /// Nothing approves it yet, and nothing marks it as dangerous.
34    NotYet,
35    /// It touches something safe-chains never lets an agent through to by asking, or it cannot be
36    /// read well enough to say it does not.
37    Boundary,
38}
39
40/// The kind of the gated `command`, from its text and its explanation.
41///
42/// `approved` answers "is this segment approved?" at the caller's level; `approved_by_default`
43/// answers it at the default level.
44pub fn gate_kind(
45    command: &str,
46    explanation: &crate::cst::Explanation,
47    approved: &dyn Fn(&str) -> bool,
48    approved_by_default: &dyn Fn(&str) -> bool,
49) -> GateKind {
50    if text_is_opaque(command) || words_name_a_boundary(command) || reaches_a_boundary(command) {
51        return GateKind::Boundary;
52    }
53    let refused: Vec<&str> = explanation
54        .segments
55        .iter()
56        .map(|s| s.text.as_str())
57        .filter(|text| !explanation.parsed || !approved(text))
58        .collect();
59    if refused.is_empty() {
60        return GateKind::Boundary;
61    }
62    let any_boundary = refused.iter().any(|segment| {
63        text_is_opaque(segment)
64            || words_name_a_boundary(segment)
65            || segment_kind(segment, approved, approved_by_default(segment)) == GateKind::Boundary
66    });
67    if any_boundary { GateKind::Boundary } else { GateKind::NotYet }
68}
69
70/// The kind of one refused segment, from what [`fix_for`] says would approve it.
71pub fn segment_kind(segment: &str, approved: &dyn Fn(&str) -> bool, approved_by_default: bool) -> GateKind {
72    match fix_for(segment, approved, approved_by_default) {
73        Fix::Nothing(Because::ProtectedPath { reason, .. }) if is_boundary_reason(reason) => GateKind::Boundary,
74        Fix::Nothing(Because::RunsAnAgent { .. } | Because::Unconfined { .. }) => GateKind::Boundary,
75        Fix::Nothing(Because::RunsLater { path }) => {
76            if reads_only(segment, &path, approved) {
77                GateKind::NotYet
78            } else {
79                GateKind::Boundary
80            }
81        }
82        _ => GateKind::NotYet,
83    }
84}
85
86fn is_boundary_reason(reason: ReachReason) -> bool {
87    match reason {
88        ReachReason::Credential
89        | ReachReason::OtherUsersHome
90        | ReachReason::RawDevice
91        | ReachReason::FrozenTrustFile
92        | ReachReason::FrozenTrustRoot
93        | ReachReason::FrozenSystemIntegrity
94        | ReachReason::Unconfined => true,
95        ReachReason::RepositorySnapshot | ReachReason::OutsideWorkspace | ReachReason::ForeignTemp => false,
96    }
97}
98
99fn reaches_a_boundary(command: &str) -> bool {
100    crate::workspace_reaches(command).any(|(_, reason)| is_boundary_reason(reason))
101}
102
103/// Whether `word`, read from the working directory, passes through a link on disk and leads to a
104/// protected place or out of the workspace. The other checks read a path as written, and `key`
105/// committed as a link to `~/.ssh/id_rsa` is written like any file name. A link whose end cannot
106/// be found counts as leading out.
107fn leads_out_through_a_link(word: &str) -> bool {
108    let (Some(cwd), Some(root)) = (crate::pathctx::cwd(), crate::pathctx::root()) else {
109        return false;
110    };
111    let expanded = expand_home(word);
112    let root = std::path::Path::new(&root);
113    let full = std::path::Path::new(&cwd).join(&expanded);
114    // Walked as written, so a path that ends outside the workspace is left to the other checks,
115    // which judge it as written; only links met inside the workspace count. The root's own place
116    // on disk is the workspace by definition.
117    let mut at = std::path::PathBuf::from("/");
118    let mut crossed = false;
119    for part in full.components() {
120        match part {
121            std::path::Component::ParentDir => {
122                at.pop();
123            }
124            std::path::Component::Normal(name) => {
125                at.push(name);
126                crossed |=
127                    at.starts_with(root) && at != root && std::fs::symlink_metadata(&at).is_ok_and(|meta| meta.file_type().is_symlink());
128            }
129            _ => {}
130        }
131    }
132    if !crossed || !at.starts_with(root) {
133        return false;
134    }
135    let (Ok(real), Ok(workspace)) = (std::fs::canonicalize(&full), std::fs::canonicalize(root)) else {
136        return true;
137    };
138    let text = real.to_string_lossy();
139    names_a_protected_place(&text)
140        || !(real.starts_with(&workspace) || crate::pathctx::under_temp_root(&text) || crate::pathctx::in_session_scratchpad(&text))
141}
142
143/// Whether a READ grant on `path` alone would get `segment` approved: the segment only reads the
144/// runs-later place it reached, which is not a boundary. A write or an exec there needs more.
145fn reads_only(segment: &str, path: &str, approved: &dyn Fn(&str) -> bool) -> bool {
146    let resolved = crate::pathctx::resolve(path).into_owned();
147    crate::engine::resolve::regions::hypothetical::with_hypothetical_grant(&resolved, true, false, || approved(segment))
148}
149
150/// Characters after which the shell, not the text, decides what a word names.
151const OPAQUE: &[char] = &['$', '`', '*', '?', '[', ']', '{', '}'];
152
153/// Programs that change the directory later words are read against, run code handed to them, or
154/// run a program named by their input or by a package.
155const OPAQUE_PROGRAMS: &[&str] = &[
156    "cd", "pushd", "popd", "eval", "source", "exec", "sh", "bash", "zsh", "dash", "ksh", "mksh", "fish", "csh", "tcsh", "python",
157    "python3", "perl", "ruby", "node", "deno", "bun", "php", "lua", "osascript", "tclsh", "xargs", "env", "nohup", "timeout", "nice",
158    "awk", "gawk", "mawk", "nawk", "npx", "bunx", "pnpx", "uvx", "pipx", "dlx", "-exec", "-execdir", "-ok", "-okdir", "-P",
159    "--absolute-names",
160];
161
162/// Option prefixes, attached or not, that change the directory later words are read against.
163const DIRECTORY_PREFIXES: &[&str] = &["-C"];
164
165/// Options that change the directory later words are read against.
166const DIRECTORY_OPTIONS: &[&str] = &["-C", "--directory", "--chdir", "--cwd", "--work-tree", "--git-dir"];
167
168/// A cluster of short options holding `-P`, which makes `tar` (and others) keep absolute names.
169fn keeps_absolute_names(word: &str) -> bool {
170    word.strip_prefix('-')
171        .is_some_and(|flags| !flags.starts_with('-') && flags.chars().all(|c| c.is_ascii_alphabetic()) && flags.contains('P'))
172}
173
174/// Whether `text` holds anything that makes what its words name unknowable from the text alone.
175fn text_is_opaque(text: &str) -> bool {
176    text.contains(OPAQUE)
177        || words(text).any(|word| {
178            let name = word.rsplit('/').next().unwrap_or(&word);
179            (word.starts_with('~') && word != "~" && !word.starts_with("~/"))
180                || OPAQUE_PROGRAMS.contains(&name)
181                || DIRECTORY_OPTIONS.contains(&word.as_str())
182                || DIRECTORY_PREFIXES.iter().any(|prefix| word.starts_with(prefix))
183                || keeps_absolute_names(&word)
184        })
185}
186
187/// The words of `text` as the shell would see their names: quotes and backslashes removed, then
188/// split on whitespace and on the operators, redirections and separators that end a word.
189fn words(text: &str) -> impl Iterator<Item = String> + '_ {
190    let dequoted: String = text.chars().filter(|c| !matches!(c, '\'' | '"' | '\\')).collect();
191    dequoted
192        .split(|c: char| c.is_whitespace() || matches!(c, ';' | '|' | '&' | '(' | ')' | '<' | '>' | '=' | ',' | ':'))
193        .filter(|word| !word.is_empty())
194        .map(str::to_string)
195        .collect::<Vec<_>>()
196        .into_iter()
197}
198
199/// Whether any word of `text` names a protected place, a place outside the workspace, an AI agent
200/// (by its command or a package name holding it), or safe-chains itself.
201fn words_name_a_boundary(text: &str) -> bool {
202    words(text).any(|word| {
203        let name = word.rsplit('/').next().unwrap_or(&word);
204        name == "safe-chains"
205            || crate::userconfig::runs_an_agent(name)
206            || names_an_agent_package(&word)
207            || path_parts(&word).any(|path| names_a_protected_place(path) || leaves_the_workspace(path))
208            || path_parts(&word).any(names_a_place_that_runs_later_here)
209            || path_parts(&word).chain(option_cluster_suffixes(&word)).any(leads_out_through_a_link)
210    })
211}
212
213/// Names, as one part of a path, of what runs later from inside a project without anyone being
214/// asked: git's hooks and config, direnv, task runners' and agents' project settings.
215const RUNS_LATER_HERE: &[&str] = &[
216    ".git", ".envrc", ".env", ".claude", ".grok", ".gemini", ".codex", ".qwen", ".cursor", ".factory", ".agy", ".antigravity", ".opencode",
217    ".vscode", ".idea", ".husky", ".mise.toml", "mise.toml", ".tool-versions", ".github", ".devcontainer",
218];
219
220fn names_a_place_that_runs_later_here(path: &str) -> bool {
221    path.split('/').any(|part| RUNS_LATER_HERE.contains(&part))
222}
223
224/// Agent names long enough to look for inside a word (`@anthropic-ai/claude-code`, `aider-chat`).
225fn names_an_agent_package(word: &str) -> bool {
226    let word = word.to_ascii_lowercase();
227    crate::userconfig::agent_commands()
228        .iter()
229        .filter(|name| name.len() >= 5)
230        .any(|name| word.contains(name))
231}
232
233/// A short-option cluster's glued value can start at any letter after the first (`sort -orc`
234/// writes `rc`, `grep -fkey` reads `key`), so each such suffix is a name the command may open.
235fn option_cluster_suffixes(word: &str) -> impl Iterator<Item = &str> {
236    let cluster = word.strip_prefix('-').filter(|rest| !rest.starts_with('-')).unwrap_or("");
237    cluster.char_indices().skip(1).map(move |(at, _)| &cluster[at..])
238}
239
240/// The parts of a word that may be a path: the word; for an option with its value attached
241/// (`-o../x`, `-t/usr/bin`) the value, from its first `/`, `.` or `~`; and whatever follows each `@`,
242/// which curl, gcc and many others read as a file to open (`curl -d @key`).
243fn path_parts(word: &str) -> impl Iterator<Item = &str> {
244    let attached = word
245        .strip_prefix('-')
246        .filter(|rest| !rest.starts_with('-'))
247        .and_then(|rest| rest.find(['/', '.', '~']).map(|at| &rest[at..]));
248    // `pkg@~4.17` is a version range, not a home: nothing expands `~user` after an `@`.
249    let after_at = word
250        .match_indices('@')
251        .map(|(at, _)| &word[at + 1..])
252        .filter(|part| !part.starts_with('~') || part.starts_with("~/"));
253    std::iter::once(word).chain(attached).chain(after_at)
254}
255
256/// Whether `word`, read as a path, names somewhere outside the workspace other than a temporary
257/// folder. [`crate::pathctx::resolve`] returns a path inside the workspace relative to it.
258fn leaves_the_workspace(word: &str) -> bool {
259    if !(word.starts_with(['~', '/', '.']) || word.contains('/')) {
260        return false;
261    }
262    let expanded = expand_home(word);
263    let resolved = crate::pathctx::resolve(&expanded);
264    let outside = resolved.starts_with(['/', '~']) || resolved == ".." || resolved.starts_with("../");
265    outside && !crate::pathctx::under_temp_root(&resolved) && !crate::pathctx::in_session_scratchpad(&resolved)
266}
267
268/// `word` with a leading `~` or `~/` read as the home folder, as the shell reads it.
269fn expand_home(word: &str) -> String {
270    let home = std::env::var("HOME").unwrap_or_default();
271    match word.strip_prefix('~') {
272        Some(rest) if rest.is_empty() || rest.starts_with('/') => format!("{home}{rest}"),
273        _ => word.to_string(),
274    }
275}
276
277fn names_a_protected_place(word: &str) -> bool {
278    let path = if word.starts_with('~') || word.starts_with('/') {
279        word.to_string()
280    } else if word.contains('/') || word.starts_with('.') {
281        crate::pathctx::resolve(word).into_owned()
282    } else {
283        return false;
284    };
285    let home = std::env::var("HOME").unwrap_or_default();
286    let trimmed = path.trim_end_matches('/');
287    if trimmed.is_empty() || trimmed == "~" || (!home.is_empty() && trimmed == home.trim_end_matches('/')) {
288        return true;
289    }
290    matches!(crate::userconfig::grantable_path(&path), Err(crate::userconfig::EditError::Protected(_, _)))
291}
292
293#[cfg(test)]
294mod tests;