1use super::{Because, Fix, fix_for};
28use crate::ReachReason;
29
30#[derive(Clone, Copy, PartialEq, Eq, Debug)]
32pub enum GateKind {
33 NotYet,
35 Boundary,
38 TooLarge,
42}
43
44pub 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
83pub 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
120fn leads_out_through_a_link(word: &str) -> bool {
125 let Some(cwd) = crate::pathctx::folder_on_disk() else {
128 return false;
129 };
130 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 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
167fn 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
174const OPAQUE: &[char] = &['$', '`', '*', '?', '[', ']', '{', '}'];
176
177const 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
186const DIRECTORY_PREFIXES: &[&str] = &["-C"];
188
189const DIRECTORY_OPTIONS: &[&str] = &["-C", "--directory", "--chdir", "--cwd", "--work-tree", "--git-dir"];
191
192fn 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
198fn 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
211fn 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
223fn 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
237const 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
248fn 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
257fn 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
264fn 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 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
280fn 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
292fn 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;