1mod edit;
17mod guard;
18mod list;
19mod surgery;
20
21use std::fs;
22use std::path::{Path, PathBuf};
23
24pub use edit::Access;
25pub use guard::Protected;
26pub use list::list;
27
28pub const SHOWN_PATH: &str = "~/.config/safe-chains.toml";
30
31#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum EditError {
35 NoHome,
36 Unreadable(String),
37 DoesNotLoad(String),
38 AlreadyApproved,
39 Unparseable,
40 BuiltIn(Vec<String>),
41 RunsAnAgent(String),
42 AlreadyHasEntry(String),
43 UnknownLevel(String),
44 NoAccess,
45 NotAbsolute(String),
46 Glob(String),
47 TooBroad(String),
48 Protected(String, Protected),
49 NotFound { kind: &'static str, key: String, present: Vec<String> },
50 WriteFailed(String),
51 CannotEditCleanly,
52 OddName(String),
53 PathSpelled(String),
54 SubAfterFlags(String, String),
55 LevelInCommand,
56}
57
58impl std::fmt::Display for EditError {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 let unchanged = "Nothing was changed.";
61 match self {
62 EditError::NoHome => write!(f, "HOME is not set, so safe-chains cannot find {SHOWN_PATH}. {unchanged}"),
63 EditError::Unreadable(why) => write!(f, "safe-chains could not read {SHOWN_PATH}: {why}. {unchanged}"),
64 EditError::DoesNotLoad(why) => write!(
65 f,
66 "{SHOWN_PATH} does not load ({why}), so safe-chains is ignoring the rules in it. Fix the \
67 file by hand first. {unchanged}"
68 ),
69 EditError::AlreadyApproved => write!(f, "safe-chains already approves this command, so it needs no entry. {unchanged}"),
70 EditError::Unparseable => write!(f, "safe-chains could not parse this command. Check its quoting. {unchanged}"),
71 EditError::BuiltIn(names) => write!(
72 f,
73 "{} built into safe-chains, and an entry cannot replace a built-in rule. If safe-chains \
74 did not approve this, a built-in rule refused one of its options or paths, and a person \
75 has to approve it when it runs. {unchanged}",
76 quoted_list(names, "is", "are")
77 ),
78 EditError::RunsAnAgent(name) => write!(
79 f,
80 "`{name}` runs an AI coding agent, which can change its own approval settings. safe-chains \
81 will not add an entry that approves it. {unchanged}"
82 ),
83 EditError::AlreadyHasEntry(name) => write!(
84 f,
85 "{SHOWN_PATH} already has an entry for `{name}`. To replace it, remove it first: {}. \
86 {unchanged}",
87 step(Step::RemoveCommand(name))
88 ),
89 EditError::UnknownLevel(level) => {
90 write!(f, "`{level}` is not a level an entry can have. Use inert, safe-read or safe-write. {unchanged}")
91 }
92 EditError::NoAccess => write!(f, "Say what to grant: --read, --write, or both. {unchanged}"),
93 EditError::NotAbsolute(path) => {
94 write!(f, "`{path}` is not a path safe-chains can grant. Give a full path or one starting with ~/. {unchanged}")
95 }
96 EditError::Glob(path) => write!(f, "`{path}` contains a wildcard. Grant a folder by its plain path. {unchanged}"),
97 EditError::TooBroad(path) => {
98 write!(f, "`{path}` covers too much to grant in one rule. Grant the folder you need inside it. {unchanged}")
99 }
100 EditError::Protected(path, why) => write!(f, "`{path}` {}. {unchanged}", why.explain()),
101 EditError::NotFound { kind, key, present } if present.is_empty() => {
102 write!(f, "{SHOWN_PATH} has no {kind} for `{key}`, and no {} at all. {unchanged}", plural(kind))
103 }
104 EditError::NotFound { kind, key, present } => write!(
105 f,
106 "{SHOWN_PATH} has no {kind} for `{key}`. The {} it has: {}. {unchanged}",
107 plural(kind),
108 present.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ")
109 ),
110 EditError::WriteFailed(why) => write!(f, "safe-chains could not write {SHOWN_PATH}: {why}. {unchanged}"),
111 EditError::OddName(name) => {
112 write!(f, "`{name}` is not a command name an entry can have. Give the program's plain name. {unchanged}")
113 }
114 EditError::PathSpelled(word) => write!(
115 f,
116 "`{word}` names a program by its path, and an entry would approve every program with that name, \
117 wherever it is. Add it by its plain name only if that program is installed where your shell finds \
118 it. {unchanged}"
119 ),
120 EditError::SubAfterFlags(name, sub) => write!(
121 f,
122 "A flag comes before `{sub}`, so safe-chains cannot tell whether `{sub}` is a subcommand, and the \
123 entry would approve `{name}` with any words in its place. Put the subcommand first, as in \
124 `{name} {sub} …`, and add that. {unchanged}"
125 ),
126 EditError::LevelInCommand => write!(
127 f,
128 "`--level` came after the command, so it would be read as one of the command's own flags. Put it \
129 first: safe-chains config add --level inert \"…\". {unchanged}"
130 ),
131 EditError::CannotEditCleanly => write!(
132 f,
133 "safe-chains could not make this change without rewriting other parts of {SHOWN_PATH}, so it \
134 left the file alone. Make the change by hand. {unchanged}"
135 ),
136 }
137 }
138}
139
140fn quoted_list(names: &[String], one: &str, many: &str) -> String {
141 let shown: Vec<String> = names.iter().map(|n| format!("`{n}`")).collect();
142 match shown.as_slice() {
143 [only] => format!("{only} {one}"),
144 _ => format!("{} {many}", shown.join(", ")),
145 }
146}
147
148pub enum Step<'a> {
154 Add(&'a str),
155 Grant(&'a str, Access),
156 RemoveCommand(&'a str),
157 RemoveGrant(&'a str),
158 Explain,
159}
160
161pub fn step(step: Step<'_>) -> String {
162 let mcp = std::env::var_os("SAFE_CHAINS_SURFACE").is_some_and(|v| v == "mcp");
163 let quote = |s: &str| crate::sanitize_display(&shell_words::quote(s));
164 let quote_path = |s: &str| match s.strip_prefix("~/") {
165 Some(rest) => format!("~/{}", quote(rest)),
166 None => quote(s),
167 };
168 let json = |s: &str| crate::sanitize_display(&serde_json::Value::from(s).to_string());
169 match (step, mcp) {
170 (Step::Add(command), false) => format!("safe-chains config add {}", quote(command)),
171 (Step::Add(command), true) => format!("call add_command_entry with command {}", json(command)),
172 (Step::Grant(path, access), false) => format!("safe-chains config grant {} {}", quote_path(path), access.flags()),
173 (Step::Grant(path, access), true) => format!("call grant_path with path {} and access \"{}\"", json(path), access.name()),
174 (Step::RemoveCommand(name), false) => format!("safe-chains config remove command {}", quote(name)),
175 (Step::RemoveCommand(name), true) => format!("call remove_rule with kind \"command\" and name {}", json(name)),
176 (Step::RemoveGrant(path), false) => format!("safe-chains config remove grant {}", quote_path(path)),
177 (Step::RemoveGrant(path), true) => format!("call remove_rule with kind \"grant\" and name {}", json(path)),
178 (Step::Explain, false) => "`safe-chains --explain` on it".to_string(),
179 (Step::Explain, true) => "check_command on it".to_string(),
180 }
181}
182
183pub fn runs_an_agent(name: &str) -> bool {
185 guard::check_entry_name(name).is_err()
186}
187
188pub fn agent_commands() -> &'static [&'static str] {
190 guard::AGENT_COMMANDS
191}
192
193pub fn grantable_path(path: &str) -> Result<String, EditError> {
195 let path = guard::normalize_path(path)?;
196 guard::check_grant_path(&path)?;
197 Ok(path)
198}
199
200pub fn entry_level(name: &str) -> Result<&'static str, EditError> {
202 match name.trim().to_ascii_lowercase().replace('_', "-").as_str() {
203 "inert" => Ok("Inert"),
204 "safe-read" | "saferead" => Ok("SafeRead"),
205 "safe-write" | "safewrite" | "" => Ok("SafeWrite"),
206 _ => Err(EditError::UnknownLevel(name.to_string())),
207 }
208}
209
210pub fn user_config_path() -> Result<PathBuf, EditError> {
212 Ok(home_dir()?.join(".config/safe-chains.toml"))
213}
214
215fn home_dir() -> Result<PathBuf, EditError> {
216 #[cfg(test)]
217 {
218 Ok(crate::registry::custom::config_home())
219 }
220 #[cfg(not(test))]
221 std::env::var_os("HOME").filter(|home| !home.is_empty()).map(PathBuf::from).ok_or(EditError::NoHome)
222}
223
224fn read_existing(path: &Path) -> Result<String, EditError> {
225 match fs::read_to_string(path) {
226 Ok(source) => Ok(source),
227 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
228 Err(e) => Err(EditError::Unreadable(e.to_string())),
229 }
230}
231
232fn write_atomically(path: &Path, contents: &str) -> Result<(), EditError> {
234 let fail = |e: std::io::Error| EditError::WriteFailed(e.to_string());
235 if let Some(dir) = path.parent() {
236 fs::create_dir_all(dir).map_err(fail)?;
237 }
238 let staging = path.with_extension(format!("toml.{}.tmp", std::process::id()));
239 fs::write(&staging, contents).map_err(fail)?;
240 if let Ok(meta) = fs::metadata(path) {
241 let _ = fs::set_permissions(&staging, meta.permissions());
242 }
243 fs::rename(&staging, path).map_err(|e| {
244 let _ = fs::remove_file(&staging);
245 fail(e)
246 })
247}
248
249fn update(change: impl FnOnce(&str) -> Result<(String, String), EditError>) -> Result<String, EditError> {
251 let path = user_config_path()?;
252 let existing = read_existing(&path)?;
253 edit::check_loads(&existing)?;
254 let (updated, message) = change(&existing)?;
255 edit::check_loads(&updated)?;
256 write_atomically(&path, &updated)?;
257 Ok(message)
258}
259
260pub fn add_entry(command: &str, level: &str) -> Result<String, EditError> {
263 let level = entry_level(level)?;
264 update(|existing| edit::add_entry(existing, command, level))
265}
266
267pub fn remove_command(name: &str) -> Result<String, EditError> {
269 update(|existing| edit::remove_command(existing, name.trim()))
270}
271
272pub fn remove_grant(path: &str) -> Result<String, EditError> {
274 let path = guard::normalize_path(path)?;
275 update(|existing| edit::remove_grant(existing, &path))
276}
277
278pub fn grant(path: &str, access: Access) -> Result<String, EditError> {
280 let path = guard::normalize_path(path)?;
281 guard::check_grant_path(&path)?;
282 update(|existing| edit::grant(existing, &path, access))
283}
284
285#[cfg(test)]
286mod tests;
287
288fn plural(kind: &str) -> String {
289 match kind.strip_suffix('y') {
290 Some(stem) => format!("{stem}ies"),
291 None => format!("{kind}s"),
292 }
293}
294
295#[doc(hidden)]
301pub mod fuzzing {
302 pub use super::edit::check_loads;
303
304 pub fn grant(existing: &str, path: &str, access: super::Access) -> Result<String, super::EditError> {
305 super::edit::grant(existing, path, access).map(|(text, _)| text)
306 }
307
308 pub fn remove_grant(existing: &str, path: &str) -> Result<String, super::EditError> {
309 super::edit::remove_grant(existing, path).map(|(text, _)| text)
310 }
311
312 pub fn add_entry(existing: &str, command: &str) -> Result<String, super::EditError> {
313 super::edit::add_entry(existing, command, "SafeRead").map(|(text, _)| text)
314 }
315
316 pub fn remove_command(existing: &str, name: &str) -> Result<String, super::EditError> {
317 super::edit::remove_command(existing, name).map(|(text, _)| text)
318 }
319}