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
19/// What would change the verdict on one refused command.
20#[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/// Why nothing in the config can change the verdict.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum Because {
31    /// A known command, refused for an option, a subcommand or the way it is used.
32    BuiltInRule {
33        names: Vec<String>,
34    },
35    /// A path a built-in rule protects, with the reason `ReachReason` gives.
36    ProtectedPath {
37        path: String,
38        reason: ReachReason,
39    },
40    /// A path built by an interpolation, which names nowhere in particular.
41    Unconfined {
42        path: String,
43    },
44    /// A path too wide to grant in one rule (`/`, the home folder), or one with a wildcard.
45    TooWide {
46        path: String,
47    },
48    /// A path that holds settings or programs that run later (agents' settings, startup files, PATH).
49    RunsLater {
50        path: String,
51    },
52    /// A command that runs an AI coding agent.
53    RunsAnAgent {
54        name: String,
55    },
56    Unparseable,
57}
58
59/// The fix for one refused command (a segment of a chain, or the whole command).
60///
61/// `approved` answers "would this command be approved?" the way the caller's verdict does, at the
62/// caller's level. It is asked again with a hypothetical grant in place, and with the default level.
63pub 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
113/// The folder holding `path`, when `path` looks like a file (its last part has an extension). A
114/// grant is offered on the folder first, so writing a second file there needs no second grant.
115fn 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
121/// The narrowest grant on `path` that would get `command` approved, if any would.
122fn 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    /// The fix as `--explain` prints it. Command-derived text is neutralized, since this is read by
143    /// the agent that wrote the command.
144    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;