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