1use crate::userconfig::{Access, Step, step};
17use crate::{ReachReason, sanitize_display, suggest};
18
19pub mod gate;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Fix {
24 AddEntry { names: Vec<String>, command: String },
25 Grant { path: String, access: Access },
26 RaiseLevel,
27 Nothing(Because),
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Because {
33 BuiltInRule {
35 names: Vec<String>,
36 },
37 ProtectedPath {
39 path: String,
40 reason: ReachReason,
41 },
42 Unconfined {
44 path: String,
45 },
46 TooWide {
48 path: String,
49 },
50 RunsLater {
52 path: String,
53 },
54 RunsAnAgent {
56 name: String,
57 },
58 Unparseable,
59}
60
61pub fn in_segment_scope<T>(command: &str, mut per_segment: impl FnMut(usize, &str) -> T) -> Option<Vec<T>> {
69 let script = crate::cst::parse(command)?;
70 let mut index = 0;
71 Some(crate::cst::check::walk_with_scope(&script, |stmt| {
72 let fix = per_segment(index, &stmt.pipeline.to_string());
73 index += 1;
74 fix
75 }))
76}
77
78pub fn fix_for(command: &str, approved: &dyn Fn(&str) -> bool, approved_by_default: bool) -> Fix {
83 if crate::cst::parse(command).is_none() {
84 return Fix::Nothing(Because::Unparseable);
85 }
86 if approved_by_default {
87 return Fix::RaiseLevel;
88 }
89 match suggest::analyze(command) {
90 suggest::Outcome::Unparseable => return Fix::Nothing(Because::Unparseable),
91 suggest::Outcome::Generated { entries, .. } => {
92 let names: Vec<String> = entries.into_iter().map(|e| e.name).collect();
93 if let Some(name) = names.iter().find(|n| crate::userconfig::runs_an_agent(n)) {
94 return Fix::Nothing(Because::RunsAnAgent { name: name.clone() });
95 }
96 return Fix::AddEntry { names, command: command.trim().to_string() };
97 }
98 suggest::Outcome::AlreadyAllowed | suggest::Outcome::RecognizedButDenied { .. } => {}
99 }
100 let names = command_names(command);
101 let Some((path, reason)) = crate::workspace_overreach(command) else {
102 return Fix::Nothing(Because::BuiltInRule { names });
103 };
104 let reason = reason.settled(command, approved);
105 match reason {
106 ReachReason::OutsideWorkspace | ReachReason::ForeignTemp => {
107 let resolved = crate::pathctx::resolve(&path).into_owned();
108 let candidates = [folder_of(&resolved), Some(resolved.clone())];
109 let grantable: Vec<String> = candidates
110 .into_iter()
111 .flatten()
112 .filter_map(|p| crate::userconfig::grantable_path(&p).ok())
113 .collect();
114 if grantable.is_empty() {
115 return match crate::userconfig::grantable_path(&resolved) {
116 Err(crate::userconfig::EditError::TooBroad(_) | crate::userconfig::EditError::Glob(_)) => {
117 Fix::Nothing(Because::TooWide { path })
118 }
119 Err(crate::userconfig::EditError::Protected(_, _)) => Fix::Nothing(Because::RunsLater { path }),
120 _ => Fix::Nothing(Because::BuiltInRule { names }),
121 };
122 }
123 grantable
124 .into_iter()
125 .find_map(|p| grant_that_works(command, &p, approved).map(|access| Fix::Grant { path: p, access }))
126 .unwrap_or(Fix::Nothing(Because::BuiltInRule { names }))
127 }
128 ReachReason::Unconfined => Fix::Nothing(Because::Unconfined { path }),
129 reason => Fix::Nothing(Because::ProtectedPath { path, reason }),
130 }
131}
132
133fn folder_of(path: &str) -> Option<String> {
136 let (folder, last) = path.trim_end_matches('/').rsplit_once('/')?;
137 let looks_like_a_file = last.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && !ext.is_empty());
138 (looks_like_a_file && !folder.is_empty()).then(|| folder.to_string())
139}
140
141fn grant_that_works(command: &str, path: &str, approved: &dyn Fn(&str) -> bool) -> Option<Access> {
143 [Access::Read, Access::Write, Access::ReadWrite].into_iter().find(|access| {
144 let (read, write) = (matches!(access, Access::Read | Access::ReadWrite), matches!(access, Access::Write | Access::ReadWrite));
145 crate::engine::resolve::regions::hypothetical::with_hypothetical_grant(path, read, write, || approved(command))
146 })
147}
148
149fn command_names(command: &str) -> Vec<String> {
150 let mut names: Vec<String> = crate::cst::explain(command).segments.iter().filter_map(|s| s.culprit.clone()).collect();
151 if names.is_empty()
152 && let suggest::Outcome::RecognizedButDenied { names: known } = suggest::analyze(command)
153 {
154 names = known;
155 }
156 names
157}
158
159const PERSON_APPROVES: &str = "safe-chains never approves a change to its own config, so a person approves that step.";
160
161impl Fix {
162 pub fn render(&self) -> String {
165 match self {
166 Fix::AddEntry { names, command } => format!(
167 "Fix: add an entry for {}:\n {}\nThe entry approves the command used the way it is \
168 here, with the same subcommand and flags. {PERSON_APPROVES}\n",
169 code_list(names),
170 step(Step::Add(command))
171 ),
172 Fix::Grant { path, access } => format!(
173 "Fix: grant {} access to `{}`:\n {}\n{PERSON_APPROVES}\n",
174 access.faces(),
175 sanitize_display(path),
176 step(Step::Grant(path, *access))
177 ),
178 Fix::RaiseLevel => "Fix: none in the rules. safe-chains approves this at its default level, and the \
179 level in force is stricter. The `level` setting in ~/.config/safe-chains.toml, or \
180 the --level you passed, decides that.\n"
181 .to_string(),
182 Fix::Nothing(because) => {
183 let by_hand = matches!(
184 because,
185 Because::ProtectedPath { reason: ReachReason::Credential | ReachReason::OtherUsersHome | ReachReason::RawDevice, .. }
186 | Because::RunsLater { .. }
187 );
188 let rewrite = matches!(because, Because::ProtectedPath { reason: ReachReason::RepositorySnapshot, .. });
189 let (lead, close) = if rewrite {
190 ("Fix:", "Otherwise a person approves the command each time it runs.")
191 } else if by_hand {
192 ("Fix: none that safe-chains will make.", "Otherwise a person approves the command each time it runs.")
193 } else {
194 ("Fix: none in safe-chains' config.", "A person approves the command each time it runs.")
195 };
196 format!("{lead} {} {close}\n", because.render())
197 }
198 }
199 }
200}
201
202impl Because {
203 fn render(&self) -> String {
204 match self {
205 Because::BuiltInRule { names } if names.is_empty() => {
206 "A built-in rule refused an option or a subcommand used here, and no entry or grant can change that.".to_string()
207 }
208 Because::BuiltInRule { names } => format!(
209 "{} built in, and a built-in rule refused an option or a subcommand used here. No entry or grant \
210 can change that.",
211 code_list(names) + if names.len() == 1 { " is" } else { " are" }
212 ),
213 Because::ProtectedPath { path, reason } => {
214 let shown = sanitize_display(path);
215 match reason {
216 ReachReason::Credential => format!(
217 "`{shown}` holds credentials, so neither `safe-chains config` nor its MCP tools will grant it. \
218 A grant you write into ~/.config/safe-chains.toml by hand would. That is the user's decision, not an agent's."
219 ),
220 ReachReason::OtherUsersHome => format!(
221 "`{shown}` is in another user's home folder, so neither `safe-chains config` nor its MCP tools will grant it. \
222 A grant you write into ~/.config/safe-chains.toml by hand would. That is the user's decision, not an agent's."
223 ),
224 ReachReason::RawDevice => format!(
225 "`{shown}` is a raw device, so neither `safe-chains config` nor its MCP tools will grant it. \
226 A read grant you write into ~/.config/safe-chains.toml by hand would allow reading it. That is the user's decision, not an agent's."
227 ),
228 ReachReason::RepositorySnapshot => format!("add --ignore-working-copy after `jj`. No grant covers `{shown}`."),
229 _ => format!("A built-in rule protects `{shown}`, and no grant can cover it."),
230 }
231 }
232 Because::Unconfined { path } => format!(
233 "The path `{}` is built by an interpolation, so it could name anywhere, and a grant cannot cover anywhere.",
234 sanitize_display(path)
235 ),
236 Because::RunsLater { path } => format!(
237 "`{}` holds settings or programs that run later without anyone asking, so neither `safe-chains \
238 config` nor its MCP tools will grant it. A grant you write into ~/.config/safe-chains.toml by hand \
239 would. That is the user's decision, not an agent's.",
240 sanitize_display(path)
241 ),
242 Because::TooWide { path } => format!(
243 "The command reaches `{}`, which is too wide to grant in one rule, and a narrower grant would not \
244 cover it.",
245 sanitize_display(path)
246 ),
247 Because::RunsAnAgent { name } => format!(
248 "`{}` runs an AI coding agent, which can change its own approval settings, so safe-chains will \
249 not add an entry that approves it.",
250 sanitize_display(name)
251 ),
252 Because::Unparseable => "safe-chains could not parse the command, so no entry or grant applies. Check its quoting.".to_string(),
253 }
254 }
255}
256
257fn code_list(names: &[String]) -> String {
258 let shown: Vec<String> = names.iter().map(|n| format!("`{}`", sanitize_display(n))).collect();
259 match shown.as_slice() {
260 [] => "the command".to_string(),
261 [one] => one.clone(),
262 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
263 }
264}
265
266#[cfg(test)]
267mod tests;