Skip to main content

safe_chains/userconfig/
mod.rs

1//! `safe-chains config`: read and change `~/.config/safe-chains.toml` without opening it.
2//!
3//! The file decides what safe-chains approves, so changing it by hand is where things go wrong: a
4//! hand-written grant has let `head ~/.ssh/id_rsa` through. These operations change
5//! one rule at a time, keep the rest of the file exactly as it was, refuse anything a built-in rule
6//! protects, and refuse to write a file safe-chains could not load.
7//!
8//! Nothing here approves itself. The classifier treats `safe-chains config add`, `remove` and
9//! `grant` like any other write (see `commands/tools/safe-chains.toml`), so a person approves each
10//! one, and the MCP server marks the same operations destructive.
11//!
12//! Each operation reads the file afresh. The hook's registry and grants are loaded once per process,
13//! which is right for a process that classifies one command and exits, and wrong for a long-lived
14//! MCP server, so the server runs these through the CLI rather than calling them in-process.
15
16mod edit;
17mod guard;
18mod list;
19mod surgery;
20
21use std::fs;
22use std::path::{Path, PathBuf};
23
24pub use edit::Access;
25pub(crate) use guard::AGENT_COMMANDS;
26pub use guard::Protected;
27pub use list::list;
28
29/// Where the user config lives, written the way every message shows it.
30pub const SHOWN_PATH: &str = "~/.config/safe-chains.toml";
31
32/// What a `config` operation could not do. Every message says what was wrong, what would work
33/// instead, and that nothing changed.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum EditError {
36    NoHome,
37    Unreadable(String),
38    DoesNotLoad(String),
39    AlreadyApproved,
40    Unparseable,
41    BuiltIn(Vec<String>),
42    RunsAnAgent(String),
43    AlreadyHasEntry(String),
44    UnknownLevel(String),
45    NoAccess,
46    NotAbsolute(String),
47    Glob(String),
48    TooBroad(String),
49    Protected(String, Protected),
50    NotFound { kind: &'static str, key: String, present: Vec<String> },
51    WriteFailed(String),
52    CannotEditCleanly,
53    OddName(String),
54    PathSpelled(String),
55    SubAfterFlags(String, String),
56    LevelInCommand,
57}
58
59impl std::fmt::Display for EditError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let unchanged = "Nothing was changed.";
62        match self {
63            EditError::NoHome => write!(f, "HOME is not set, so safe-chains cannot find {SHOWN_PATH}. {unchanged}"),
64            EditError::Unreadable(why) => write!(f, "safe-chains could not read {SHOWN_PATH}: {why}. {unchanged}"),
65            EditError::DoesNotLoad(why) => write!(
66                f,
67                "{SHOWN_PATH} does not load ({why}), so safe-chains is ignoring the rules in it. Fix the \
68                 file by hand first. {unchanged}"
69            ),
70            EditError::AlreadyApproved => write!(f, "safe-chains already approves this command, so it needs no entry. {unchanged}"),
71            EditError::Unparseable => write!(f, "safe-chains could not parse this command. Check its quoting. {unchanged}"),
72            EditError::BuiltIn(names) => write!(
73                f,
74                "{} built into safe-chains, and an entry cannot replace a built-in rule. If safe-chains \
75                 did not approve this, a built-in rule refused one of its options or paths, and a person \
76                 has to approve it when it runs. {unchanged}",
77                quoted_list(names, "is", "are")
78            ),
79            EditError::RunsAnAgent(name) => write!(
80                f,
81                "`{name}` runs an AI coding agent, which can change its own approval settings. safe-chains \
82                 will not add an entry that approves it. {unchanged}"
83            ),
84            EditError::AlreadyHasEntry(name) => write!(
85                f,
86                "{SHOWN_PATH} already has an entry for `{name}`. To replace it, remove it first: {}. \
87                 {unchanged}",
88                step(Step::RemoveCommand(name))
89            ),
90            EditError::UnknownLevel(level) => {
91                write!(f, "`{level}` is not a level an entry can have. Use inert, safe-read or safe-write. {unchanged}")
92            }
93            EditError::NoAccess => write!(f, "Say what to grant: --read, --write, or both. {unchanged}"),
94            EditError::NotAbsolute(path) => {
95                write!(f, "`{path}` is not a path safe-chains can grant. Give a full path or one starting with ~/. {unchanged}")
96            }
97            EditError::Glob(path) => write!(f, "`{path}` contains a wildcard. Grant a folder by its plain path. {unchanged}"),
98            EditError::TooBroad(path) => {
99                write!(f, "`{path}` covers too much to grant in one rule. Grant the folder you need inside it. {unchanged}")
100            }
101            EditError::Protected(path, why) => write!(f, "`{path}` {}. {unchanged}", why.explain()),
102            EditError::NotFound { kind, key, present } if present.is_empty() => {
103                write!(f, "{SHOWN_PATH} has no {kind} for `{key}`, and no {} at all. {unchanged}", plural(kind))
104            }
105            EditError::NotFound { kind, key, present } => write!(
106                f,
107                "{SHOWN_PATH} has no {kind} for `{key}`. The {} it has: {}. {unchanged}",
108                plural(kind),
109                present.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ")
110            ),
111            EditError::WriteFailed(why) => write!(f, "safe-chains could not write {SHOWN_PATH}: {why}. {unchanged}"),
112            EditError::OddName(name) => {
113                write!(f, "`{name}` is not a command name an entry can have. Give the program's plain name. {unchanged}")
114            }
115            EditError::PathSpelled(word) => write!(
116                f,
117                "`{word}` names a program by its path, and an entry would approve every program with that name, \
118                 wherever it is. Add it by its plain name only if that program is installed where your shell finds \
119                 it. {unchanged}"
120            ),
121            EditError::SubAfterFlags(name, sub) => write!(
122                f,
123                "A flag comes before `{sub}`, so safe-chains cannot tell whether `{sub}` is a subcommand, and the \
124                 entry would approve `{name}` with any words in its place. Put the subcommand first, as in \
125                 `{name} {sub} …`, and add that. {unchanged}"
126            ),
127            EditError::LevelInCommand => write!(
128                f,
129                "`--level` came after the command, so it would be read as one of the command's own flags. Put it \
130                 first: safe-chains config add --level inert \"…\". {unchanged}"
131            ),
132            EditError::CannotEditCleanly => write!(
133                f,
134                "safe-chains could not make this change without rewriting other parts of {SHOWN_PATH}, so it \
135                 left the file alone. Make the change by hand. {unchanged}"
136            ),
137        }
138    }
139}
140
141fn quoted_list(names: &[String], one: &str, many: &str) -> String {
142    let shown: Vec<String> = names.iter().map(|n| format!("`{n}`")).collect();
143    match shown.as_slice() {
144        [only] => format!("{only} {one}"),
145        _ => format!("{} {many}", shown.join(", ")),
146    }
147}
148
149/// Something the reader can do next, named the way the surface they are using spells it.
150///
151/// The MCP server runs these operations through the CLI and sets `SAFE_CHAINS_SURFACE=mcp`, so
152/// a model calling tools is told which tool to call rather than a command it may have no shell for.
153/// The variable changes wording only.
154pub enum Step<'a> {
155    Add(&'a str),
156    Grant(&'a str, Access),
157    RemoveCommand(&'a str),
158    RemoveGrant(&'a str),
159    Explain,
160}
161
162pub fn step(step: Step<'_>) -> String {
163    let mcp = std::env::var_os("SAFE_CHAINS_SURFACE").is_some_and(|v| v == "mcp");
164    let quote = |s: &str| crate::sanitize_display(&shell_words::quote(s));
165    let quote_path = |s: &str| match s.strip_prefix("~/") {
166        Some(rest) => format!("~/{}", quote(rest)),
167        None => quote(s),
168    };
169    let json = |s: &str| crate::sanitize_display(&serde_json::Value::from(s).to_string());
170    match (step, mcp) {
171        (Step::Add(command), false) => format!("safe-chains config add {}", quote(command)),
172        (Step::Add(command), true) => format!("call add_command_entry with command {}", json(command)),
173        (Step::Grant(path, access), false) => format!("safe-chains config grant {} {}", quote_path(path), access.flags()),
174        (Step::Grant(path, access), true) => format!("call grant_path with path {} and access \"{}\"", json(path), access.name()),
175        (Step::RemoveCommand(name), false) => format!("safe-chains config remove command {}", quote(name)),
176        (Step::RemoveCommand(name), true) => format!("call remove_rule with kind \"command\" and name {}", json(name)),
177        (Step::RemoveGrant(path), false) => format!("safe-chains config remove grant {}", quote_path(path)),
178        (Step::RemoveGrant(path), true) => format!("call remove_rule with kind \"grant\" and name {}", json(path)),
179        (Step::Explain, false) => "`safe-chains --explain` on it".to_string(),
180        (Step::Explain, true) => "check_command on it".to_string(),
181    }
182}
183
184/// Whether `name` runs an AI coding agent, which no entry may approve.
185pub fn runs_an_agent(name: &str) -> bool {
186    guard::check_entry_name(name).is_err()
187}
188
189/// The commands that run an AI coding agent.
190pub fn agent_commands() -> &'static [&'static str] {
191    guard::AGENT_COMMANDS
192}
193
194/// `path` as `safe-chains config grant` would write it, or why that command would refuse it.
195pub fn grantable_path(path: &str) -> Result<String, EditError> {
196    let path = guard::normalize_path(path)?;
197    guard::check_grant_path(&path)?;
198    Ok(path)
199}
200
201/// Whether `safe-chains config grant` would refuse absolute `path`.
202#[cfg(feature = "test-home")]
203pub(crate) fn grant_refused(path: &str) -> bool {
204    guard::check_grant_path(path).is_err()
205}
206
207/// The level an added entry gets, as the CLI spells it and as the file spells it.
208pub fn entry_level(name: &str) -> Result<&'static str, EditError> {
209    match name.trim().to_ascii_lowercase().replace('_', "-").as_str() {
210        "inert" => Ok("Inert"),
211        "safe-read" | "saferead" => Ok("SafeRead"),
212        "safe-write" | "safewrite" | "" => Ok("SafeWrite"),
213        _ => Err(EditError::UnknownLevel(name.to_string())),
214    }
215}
216
217/// `~/.config/safe-chains.toml` under `$HOME`. The same rule as the loader: never `XDG_CONFIG_HOME`.
218pub fn user_config_path() -> Result<PathBuf, EditError> {
219    Ok(home_dir()?.join(".config/safe-chains.toml"))
220}
221
222fn home_dir() -> Result<PathBuf, EditError> {
223    #[cfg(test)]
224    {
225        Ok(crate::registry::custom::config_home())
226    }
227    #[cfg(not(test))]
228    crate::process_home::var_os()
229        .filter(|home| !home.is_empty())
230        .map(PathBuf::from)
231        .ok_or(EditError::NoHome)
232}
233
234fn read_existing(path: &Path) -> Result<String, EditError> {
235    match fs::read_to_string(path) {
236        Ok(source) => Ok(source),
237        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
238        Err(e) => Err(EditError::Unreadable(e.to_string())),
239    }
240}
241
242/// Replace the file's contents in one step, so a reader never sees half of it.
243fn write_atomically(path: &Path, contents: &str) -> Result<(), EditError> {
244    let fail = |e: std::io::Error| EditError::WriteFailed(e.to_string());
245    if let Some(dir) = path.parent() {
246        fs::create_dir_all(dir).map_err(fail)?;
247    }
248    let staging = path.with_extension(format!("toml.{}.tmp", std::process::id()));
249    fs::write(&staging, contents).map_err(fail)?;
250    if let Ok(meta) = fs::metadata(path) {
251        let _ = fs::set_permissions(&staging, meta.permissions());
252    }
253    fs::rename(&staging, path).map_err(|e| {
254        let _ = fs::remove_file(&staging);
255        fail(e)
256    })
257}
258
259/// Apply `change` to the user config and write the result, or change nothing.
260fn update(change: impl FnOnce(&str) -> Result<(String, String), EditError>) -> Result<String, EditError> {
261    let path = user_config_path()?;
262    let existing = read_existing(&path)?;
263    edit::check_loads(&existing)?;
264    let (updated, message) = change(&existing)?;
265    edit::check_loads(&updated)?;
266    write_atomically(&path, &updated)?;
267    Ok(message)
268}
269
270/// Add an entry that approves `command` as it was written, at `level` (`inert`, `safe-read`,
271/// `safe-write`). Returns what to tell the person.
272pub fn add_entry(command: &str, level: &str) -> Result<String, EditError> {
273    let level = entry_level(level)?;
274    update(|existing| edit::add_entry(existing, command, level))
275}
276
277/// Remove the command entry named `name`.
278pub fn remove_command(name: &str) -> Result<String, EditError> {
279    update(|existing| edit::remove_command(existing, name.trim()))
280}
281
282/// Remove the grant on `path`.
283pub fn remove_grant(path: &str) -> Result<String, EditError> {
284    let path = guard::normalize_path(path)?;
285    update(|existing| edit::remove_grant(existing, &path))
286}
287
288/// Grant `access` to `path`, merging with a grant already on that path.
289pub fn grant(path: &str, access: Access) -> Result<String, EditError> {
290    let path = guard::normalize_path(path)?;
291    guard::check_grant_path(&path)?;
292    update(|existing| edit::grant(existing, &path, access))
293}
294
295#[cfg(test)]
296mod tests;
297
298fn plural(kind: &str) -> String {
299    match kind.strip_suffix('y') {
300        Some(stem) => format!("{stem}ies"),
301        None => format!("{kind}s"),
302    }
303}
304
305/// Fuzz seam onto the edits, which are otherwise private: the text in, the text out, no files.
306///
307/// The user's own file is the input these edits do not control. It may be anything a person or a
308/// tool once wrote, and an edit that panicked on it, or wrote back something that no longer loads,
309/// would switch off every rule in it.
310#[doc(hidden)]
311pub mod fuzzing {
312    pub use super::edit::check_loads;
313
314    pub fn grant(existing: &str, path: &str, access: super::Access) -> Result<String, super::EditError> {
315        super::edit::grant(existing, path, access).map(|(text, _)| text)
316    }
317
318    pub fn remove_grant(existing: &str, path: &str) -> Result<String, super::EditError> {
319        super::edit::remove_grant(existing, path).map(|(text, _)| text)
320    }
321
322    pub fn add_entry(existing: &str, command: &str) -> Result<String, super::EditError> {
323        super::edit::add_entry(existing, command, "SafeRead").map(|(text, _)| text)
324    }
325
326    pub fn remove_command(existing: &str, name: &str) -> Result<String, super::EditError> {
327        super::edit::remove_command(existing, name).map(|(text, _)| text)
328    }
329}