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