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