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