1mod 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
29pub const SHOWN_PATH: &str = "~/.config/safe-chains.toml";
31
32#[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
149pub 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
184pub fn runs_an_agent(name: &str) -> bool {
186 guard::check_entry_name(name).is_err()
187}
188
189pub fn agent_commands() -> &'static [&'static str] {
191 guard::AGENT_COMMANDS
192}
193
194pub 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
201pub fn entry_level(name: &str) -> Result<&'static str, EditError> {
203 match name.trim().to_ascii_lowercase().replace('_', "-").as_str() {
204 "inert" => Ok("Inert"),
205 "safe-read" | "saferead" => Ok("SafeRead"),
206 "safe-write" | "safewrite" | "" => Ok("SafeWrite"),
207 _ => Err(EditError::UnknownLevel(name.to_string())),
208 }
209}
210
211pub fn user_config_path() -> Result<PathBuf, EditError> {
213 Ok(home_dir()?.join(".config/safe-chains.toml"))
214}
215
216fn home_dir() -> Result<PathBuf, EditError> {
217 #[cfg(test)]
218 {
219 Ok(crate::registry::custom::config_home())
220 }
221 #[cfg(not(test))]
222 std::env::var_os("HOME").filter(|home| !home.is_empty()).map(PathBuf::from).ok_or(EditError::NoHome)
223}
224
225fn read_existing(path: &Path) -> Result<String, EditError> {
226 match fs::read_to_string(path) {
227 Ok(source) => Ok(source),
228 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
229 Err(e) => Err(EditError::Unreadable(e.to_string())),
230 }
231}
232
233fn write_atomically(path: &Path, contents: &str) -> Result<(), EditError> {
235 let fail = |e: std::io::Error| EditError::WriteFailed(e.to_string());
236 if let Some(dir) = path.parent() {
237 fs::create_dir_all(dir).map_err(fail)?;
238 }
239 let staging = path.with_extension(format!("toml.{}.tmp", std::process::id()));
240 fs::write(&staging, contents).map_err(fail)?;
241 if let Ok(meta) = fs::metadata(path) {
242 let _ = fs::set_permissions(&staging, meta.permissions());
243 }
244 fs::rename(&staging, path).map_err(|e| {
245 let _ = fs::remove_file(&staging);
246 fail(e)
247 })
248}
249
250fn update(change: impl FnOnce(&str) -> Result<(String, String), EditError>) -> Result<String, EditError> {
252 let path = user_config_path()?;
253 let existing = read_existing(&path)?;
254 edit::check_loads(&existing)?;
255 let (updated, message) = change(&existing)?;
256 edit::check_loads(&updated)?;
257 write_atomically(&path, &updated)?;
258 Ok(message)
259}
260
261pub fn add_entry(command: &str, level: &str) -> Result<String, EditError> {
264 let level = entry_level(level)?;
265 update(|existing| edit::add_entry(existing, command, level))
266}
267
268pub fn remove_command(name: &str) -> Result<String, EditError> {
270 update(|existing| edit::remove_command(existing, name.trim()))
271}
272
273pub fn remove_grant(path: &str) -> Result<String, EditError> {
275 let path = guard::normalize_path(path)?;
276 update(|existing| edit::remove_grant(existing, &path))
277}
278
279pub fn grant(path: &str, access: Access) -> Result<String, EditError> {
281 let path = guard::normalize_path(path)?;
282 guard::check_grant_path(&path)?;
283 update(|existing| edit::grant(existing, &path, access))
284}
285
286#[cfg(test)]
287mod tests;
288
289fn plural(kind: &str) -> String {
290 match kind.strip_suffix('y') {
291 Some(stem) => format!("{stem}ies"),
292 None => format!("{kind}s"),
293 }
294}
295
296#[doc(hidden)]
302pub mod fuzzing {
303 pub use super::edit::check_loads;
304
305 pub fn grant(existing: &str, path: &str, access: super::Access) -> Result<String, super::EditError> {
306 super::edit::grant(existing, path, access).map(|(text, _)| text)
307 }
308
309 pub fn remove_grant(existing: &str, path: &str) -> Result<String, super::EditError> {
310 super::edit::remove_grant(existing, path).map(|(text, _)| text)
311 }
312
313 pub fn add_entry(existing: &str, command: &str) -> Result<String, super::EditError> {
314 super::edit::add_entry(existing, command, "SafeRead").map(|(text, _)| text)
315 }
316
317 pub fn remove_command(existing: &str, name: &str) -> Result<String, super::EditError> {
318 super::edit::remove_command(existing, name).map(|(text, _)| text)
319 }
320}