1use toml_edit::{ArrayOfTables, DocumentMut, Item, Table, value};
7
8use super::{EditError, SHOWN_PATH, Step, guard, step, surgery};
9use crate::suggest::{self, GeneratedEntry, Outcome};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Access {
14 Read,
15 Write,
16 ReadWrite,
17}
18
19impl Access {
20 pub fn from_flags(read: bool, write: bool) -> Result<Self, EditError> {
21 match (read, write) {
22 (true, true) => Ok(Access::ReadWrite),
23 (true, false) => Ok(Access::Read),
24 (false, true) => Ok(Access::Write),
25 (false, false) => Err(EditError::NoAccess),
26 }
27 }
28
29 pub fn name(self) -> &'static str {
31 match self {
32 Access::Read => "read",
33 Access::Write => "write",
34 Access::ReadWrite => "read_write",
35 }
36 }
37
38 pub fn from_name(name: &str) -> Option<Self> {
39 [Access::Read, Access::Write, Access::ReadWrite].into_iter().find(|a| a.name() == name)
40 }
41
42 pub fn flags(self) -> &'static str {
44 match self {
45 Access::Read => "--read",
46 Access::Write => "--write",
47 Access::ReadWrite => "--read --write",
48 }
49 }
50
51 pub fn faces(self) -> &'static str {
53 Access::describe(self.read(), self.write())
54 }
55
56 fn read(self) -> bool {
57 matches!(self, Access::Read | Access::ReadWrite)
58 }
59
60 fn write(self) -> bool {
61 matches!(self, Access::Write | Access::ReadWrite)
62 }
63
64 fn describe(read: bool, write: bool) -> &'static str {
65 match (read, write) {
66 (true, true) => "read and write",
67 (false, true) => "write",
68 _ => "read",
69 }
70 }
71}
72
73pub fn check_loads(source: &str) -> Result<(), EditError> {
76 if source.trim().is_empty() {
77 return Ok(());
78 }
79 let parsed: toml::Value = toml::from_str(source).map_err(|e| EditError::DoesNotLoad(first_line(&e.to_string())))?;
80 crate::registry::load_toml(source, "custom-user").map_err(|e| EditError::DoesNotLoad(first_line(&e)))?;
81 let grants = match parsed.get("grant") {
82 None => return Ok(()),
83 Some(toml::Value::Array(grants)) => grants,
84 Some(_) => return Err(EditError::DoesNotLoad("`grant` must be a list of [[grant]] tables".into())),
85 };
86 for grant in grants {
87 let has_path = grant.get("path").is_some_and(toml::Value::is_str);
88 let flags_ok = ["read", "write"].iter().all(|k| grant.get(k).is_none_or(toml::Value::is_bool));
89 if !has_path || !flags_ok {
90 return Err(EditError::DoesNotLoad("every [[grant]] needs a path, and read and write must be true or false".into()));
91 }
92 }
93 Ok(())
94}
95
96fn first_line(text: &str) -> String {
97 text.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("unknown error").to_string()
98}
99
100fn document(source: &str) -> Result<DocumentMut, EditError> {
101 source.parse::<DocumentMut>().map_err(|e| EditError::DoesNotLoad(first_line(&e.to_string())))
102}
103
104fn names_in(doc: &DocumentMut, key: &str, field: &str) -> Vec<String> {
105 doc.get(key)
106 .and_then(Item::as_array_of_tables)
107 .map(|tables| tables.iter().filter_map(|t| t.get(field).and_then(Item::as_str)).map(String::from).collect())
108 .unwrap_or_default()
109}
110
111pub(super) fn add_entry(existing: &str, command: &str, level: &str) -> Result<(String, String), EditError> {
113 if command.trim().is_empty() {
114 return Err(EditError::Unparseable);
115 }
116 let (mut entries, also_recognized) = match suggest::analyze(command) {
117 Outcome::AlreadyAllowed => return Err(EditError::AlreadyApproved),
118 Outcome::Unparseable => return Err(EditError::Unparseable),
119 Outcome::RecognizedButDenied { names } => return Err(EditError::BuiltIn(names)),
120 Outcome::Generated { entries, also_recognized } => (entries, also_recognized),
121 };
122 let present = names_in(&document(existing)?, "command", "name");
123 for entry in &mut entries {
124 guard::check_entry_name(&entry.name)?;
125 guard::check_spelling(command, entry)?;
126 if present.contains(&entry.name) {
127 return Err(EditError::AlreadyHasEntry(entry.name.clone()));
128 }
129 entry.level = level.to_string();
130 }
131 let updated = surgery::append(existing, &suggest::render_toml(&entries));
132 let mut message = format!("Added to {SHOWN_PATH}:\n\n{}\n", suggest::render_toml(&entries));
133 for entry in &entries {
134 message.push_str(&format!("{}\n", describe(entry)));
135 }
136 message.push_str(if entries.len() == 1 {
137 "safe-chains approves it from the next command on."
138 } else {
139 "safe-chains approves them from the next command on."
140 });
141 if !also_recognized.is_empty() {
142 message.push_str(&format!(
143 " The command also runs {}, which safe-chains already knows. If it is still not approved, \
144 run {} to see why.",
145 also_recognized.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
146 step(Step::Explain)
147 ));
148 }
149 for entry in &entries {
150 message.push_str(&format!("\nTo undo it: {}", step(Step::RemoveCommand(&entry.name))));
151 }
152 Ok((updated, message))
153}
154
155fn describe(entry: &GeneratedEntry) -> String {
157 let shape = |flags: &[String], max: usize| {
158 let flags = match flags {
159 [] => "no flags".to_string(),
160 [one] => format!("the flag {one}"),
161 many => format!("the flags {}", many.join(" ")),
162 };
163 let args = match max {
164 0 => "no other arguments".to_string(),
165 1 => "one other argument of any value".to_string(),
166 n => format!("up to {n} other arguments of any value"),
167 };
168 format!("{flags} and {args}")
169 };
170 if entry.subs.is_empty() {
171 return format!("It approves `{}` with {}.", entry.name, shape(&entry.standalone, entry.max_positional));
172 }
173 let subs: Vec<String> = entry
174 .subs
175 .iter()
176 .map(|s| format!("`{} {}` with {}", entry.name, s.name, shape(&s.standalone, s.max_positional)))
177 .collect();
178 format!("It approves {}.", subs.join(", and "))
179}
180
181pub(super) fn remove_command(existing: &str, name: &str) -> Result<(String, String), EditError> {
182 let mut doc = document(existing)?;
183 let present = names_in(&doc, "command", "name");
184 if !present.iter().any(|p| p == name) {
185 return Err(EditError::NotFound { kind: "command entry", key: name.to_string(), present });
186 }
187 let keep = |t: &Table| t.get("name").and_then(Item::as_str) != Some(name);
188 let doomed = doomed(&doc, "command", &keep);
189 retain(&mut doc, "command", keep);
190 let updated = cut_elements(existing, "command", &doomed, &doc)?;
191 let message = format!("Removed the entry for `{name}` from {SHOWN_PATH}. safe-chains stops approving it from the next command on.");
192 Ok((updated, message))
193}
194
195pub(super) fn remove_grant(existing: &str, path: &str) -> Result<(String, String), EditError> {
196 let mut doc = document(existing)?;
197 let present = names_in(&doc, "grant", "path");
198 if !present.iter().any(|p| same_path(p, path)) {
199 return Err(EditError::NotFound { kind: "grant", key: path.to_string(), present });
200 }
201 let keep = |t: &Table| !t.get("path").and_then(Item::as_str).is_some_and(|p| same_path(p, path));
202 let doomed = doomed(&doc, "grant", &keep);
203 retain(&mut doc, "grant", keep);
204 let updated = cut_elements(existing, "grant", &doomed, &doc)?;
205 let message = format!("Removed the grant on `{path}` from {SHOWN_PATH}. It stops applying from the next command on.");
206 Ok((updated, message))
207}
208
209fn doomed(doc: &DocumentMut, key: &str, keep: &impl Fn(&Table) -> bool) -> Vec<usize> {
211 doc.get(key)
212 .and_then(Item::as_array_of_tables)
213 .map(|tables| tables.iter().enumerate().filter(|(_, t)| !keep(t)).map(|(i, _)| i).collect())
214 .unwrap_or_default()
215}
216
217fn retain(doc: &mut DocumentMut, key: &str, keep: impl Fn(&Table) -> bool) {
218 let emptied = match doc.get_mut(key).and_then(Item::as_array_of_tables_mut) {
219 Some(tables) => {
220 tables.retain(|t| keep(t));
221 tables.is_empty()
222 }
223 None => false,
224 };
225 if emptied {
226 doc.remove(key);
227 }
228}
229
230fn cut_elements(existing: &str, key: &str, doomed: &[usize], expected: &DocumentMut) -> Result<String, EditError> {
233 let ranges = surgery::elements(existing, key).ok_or(EditError::CannotEditCleanly)?;
234 let chosen: Vec<_> = doomed.iter().filter_map(|&i| ranges.get(i).cloned()).collect();
235 if chosen.len() != doomed.len() {
236 return Err(EditError::CannotEditCleanly);
237 }
238 same_meaning(surgery::cut(existing, &chosen), expected)
239}
240
241fn same_meaning(text: String, expected: &DocumentMut) -> Result<String, EditError> {
242 let got = toml::from_str::<toml::Value>(&text).map_err(|_| EditError::CannotEditCleanly)?;
243 let want = toml::from_str::<toml::Value>(&expected.to_string()).map_err(|_| EditError::CannotEditCleanly)?;
244 if toml::to_string(&got).ok() == toml::to_string(&want).ok() { Ok(text) } else { Err(EditError::CannotEditCleanly) }
247}
248
249fn same_path(written: &str, normalized: &str) -> bool {
250 guard::normalize_path(written).is_ok_and(|w| w == normalized)
251}
252
253pub(super) fn grant(existing: &str, path: &str, access: Access) -> Result<(String, String), EditError> {
254 let mut doc = document(existing)?;
255 if doc.get("grant").is_none() {
256 doc.insert("grant", Item::ArrayOfTables(ArrayOfTables::new()));
257 }
258 let Some(grants) = doc.get_mut("grant").and_then(Item::as_array_of_tables_mut) else {
259 return Err(EditError::CannotEditCleanly);
260 };
261 let found = grants
262 .iter_mut()
263 .enumerate()
264 .find(|(_, t)| t.get("path").and_then(Item::as_str).is_some_and(|p| same_path(p, path)));
265 let (read, write, before, text) = match found {
266 Some((index, table)) => {
267 let flag = |t: &Table, k: &str| t.get(k).and_then(Item::as_bool).unwrap_or(false);
268 let before = (flag(table, "read"), flag(table, "write"));
269 let now = (before.0 || access.read(), before.1 || access.write());
270 table["read"] = value(now.0);
271 table["write"] = value(now.1);
272 let text = if now == before {
273 existing.to_string()
274 } else {
275 surgery::set_flags(existing, "grant", index, &[("read", now.0), ("write", now.1)]).ok_or(EditError::CannotEditCleanly)?
276 };
277 (now.0, now.1, Some(before), text)
278 }
279 None => {
280 let mut table = Table::new();
281 table["path"] = value(path);
282 table["read"] = value(access.read());
283 table["write"] = value(access.write());
284 grants.push(table);
285 let block =
286 format!("[[grant]]\npath = {}\nread = {}\nwrite = {}\n", crate::suggest::toml_str(path), access.read(), access.write());
287 (access.read(), access.write(), None, surgery::append(existing, &block))
288 }
289 };
290 if doc.get("grant").and_then(Item::as_array_of_tables).is_some_and(ArrayOfTables::is_empty) {
291 doc.remove("grant");
292 }
293 let text = same_meaning(text, &doc)?;
294 let faces = Access::describe(read, write);
295 let message = match before {
296 Some(before) if before == (read, write) => {
297 format!("{SHOWN_PATH} already grants {faces} access to `{path}`. Nothing needed changing.")
298 }
299 _ => format!(
300 "Granted {faces} access to `{path}` in {SHOWN_PATH}. It applies from the next command on. Anywhere it does not cover still asks.\n\
301 To undo it: {}",
302 step(Step::RemoveGrant(path))
303 ),
304 };
305 Ok((text, message))
306}