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}
39
40pub 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
70pub 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
103fn 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 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
143fn 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
150const OPAQUE: &[char] = &['$', '`', '*', '?', '[', ']', '{', '}'];
152
153const 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
162const DIRECTORY_PREFIXES: &[&str] = &["-C"];
164
165const DIRECTORY_OPTIONS: &[&str] = &["-C", "--directory", "--chdir", "--cwd", "--work-tree", "--git-dir"];
167
168fn 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
174fn 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
187fn 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
199fn 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
213const 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
224fn 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
233fn 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
240fn 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 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
256fn 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
268fn 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;