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