Skip to main content

safe_chains/
explain_fix.rs

1//! The last thing `--explain` says about a refused command: what would change the answer.
2//!
3//! There are three answers, and saying which one applies is the point. An agent told only "no
4//! opinion" read safe-chains' source code for most of an hour to find out what it needed.
5//!
6//! - **Add an entry**: safe-chains has no entry for the command. `safe-chains config add` writes one.
7//! - **Grant a path**: a known command reached a path outside the places approved by default, and a
8//!   grant would change that. It is offered only after asking the classifier with the grant in place,
9//!   so it is never advice that changes nothing.
10//! - **Nothing in the config**: a built-in rule refused an option, a subcommand or a protected path.
11//!   No entry or grant changes it, and a person has to approve the command when it runs.
12//!
13//! One more case is not a rule at all: the level in force is stricter than the default, and the
14//! default approves the command. Saying "a built-in rule refused it" there would be false.
15
16use crate::userconfig::{Access, Step, step};
17use crate::{ReachReason, sanitize_display, suggest};
18
19pub mod gate;
20
21/// What would change the verdict on one refused command.
22#[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/// Why nothing in the config can change the verdict.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Because {
33    /// A known command, refused for an option, a subcommand or the way it is used.
34    BuiltInRule {
35        names: Vec<String>,
36    },
37    /// A path a built-in rule protects, with the reason `ReachReason` gives.
38    ProtectedPath {
39        path: String,
40        reason: ReachReason,
41    },
42    /// A path built by an interpolation, which names nowhere in particular.
43    Unconfined {
44        path: String,
45    },
46    /// A path too wide to grant in one rule (`/`, the home folder), or one with a wildcard.
47    TooWide {
48        path: String,
49    },
50    /// A path that holds settings or programs that run later (agents' settings, startup files, PATH).
51    RunsLater {
52        path: String,
53    },
54    /// A command that runs an AI coding agent.
55    RunsAnAgent {
56        name: String,
57    },
58    Unparseable,
59}
60
61/// Runs `per_segment` on each segment of `command` (its index and text) with the scope the segments
62/// before it leave in force: their `cd`, their `VAR=` bindings and their function definitions.
63///
64/// A segment's fix has to be worked out there. Alone, `git -C $M status` names no place, and every
65/// grant asked about it fails, so `M=/elsewhere; git -C $M status` was told nothing in safe-chains'
66/// config would help, though a grant on `/elsewhere` approves it. `None` when `command` does not
67/// parse.
68pub 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
78/// The fix for one refused command (a segment of a chain, or the whole command).
79///
80/// `approved` answers "would this command be approved?" the way the caller's verdict does, at the
81/// caller's level. It is asked again with a hypothetical grant in place, and with the default level.
82pub 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
133/// The folder holding `path`, when `path` looks like a file (its last part has an extension). A
134/// grant is offered on the folder first, so writing a second file there needs no second grant.
135fn 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
141/// The narrowest grant on `path` that would get `command` approved, if any would.
142fn 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    /// The fix as `--explain` prints it. Command-derived text is neutralized, since this is read by
163    /// the agent that wrote the command.
164    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;