safe_chains/userconfig/
list.rs1use std::fmt::Write as _;
4use std::path::Path;
5
6use super::SHOWN_PATH;
7
8pub fn list() -> String {
10 let home = std::env::var("HOME").unwrap_or_default();
11 let mut out = String::new();
12 if std::env::var_os("SAFE_CHAINS_NO_LOCAL").is_some() {
13 out.push_str("SAFE_CHAINS_NO_LOCAL is set, so safe-chains is ignoring every file below and using only its built-in rules.\n\n");
14 }
15 let user = std::fs::read_to_string(Path::new(&home).join(".config/safe-chains.toml")).unwrap_or_default();
16 out.push_str(SHOWN_PATH);
17 out.push('\n');
18 out.push_str(&user_rules(&user));
19
20 if let Some((path, trusted)) = crate::registry::custom::project_config() {
21 let shown = crate::sanitize_display(&tilde(&path.to_string_lossy(), &home));
22 let status = if trusted {
23 "trusted, so its rules apply here"
24 } else {
25 "not trusted, so safe-chains ignores it. A [[trusted]] pin in ~/.config/safe-chains.toml with its current hash would trust it"
26 };
27 let _ = writeln!(out, "\n{shown} ({status})");
28 out.push_str(&command_rules(&std::fs::read_to_string(&path).unwrap_or_default()));
29 }
30
31 let claude = std::fs::read_to_string(Path::new(&home).join(".claude/settings.json")).unwrap_or_default();
32 let borrowed = claude_rules(&claude);
33 if !borrowed.is_empty() {
34 out.push_str("\n~/.claude/settings.json (used only when Claude Code runs safe-chains)\n");
35 out.push_str(&borrowed);
36 }
37
38 let _ = writeln!(out, "\nBuilt in: {} commands. `safe-chains --list-commands` lists them.", crate::docs::all_command_docs().len());
39 let _ = writeln!(
40 out,
41 "To remove a rule from {SHOWN_PATH}: {}, or {}.",
42 super::step(super::Step::RemoveCommand("NAME")),
43 super::step(super::Step::RemoveGrant("PATH"))
44 );
45 out
46}
47
48fn tilde(path: &str, home: &str) -> String {
49 match path.strip_prefix(home) {
50 Some(rest) if !home.is_empty() && rest.starts_with('/') => format!("~{rest}"),
51 _ => path.to_string(),
52 }
53}
54
55fn user_rules(source: &str) -> String {
56 let Ok(doc) = toml::from_str::<toml::Value>(source) else {
57 return if source.trim().is_empty() {
58 " (no file, so no rules)\n".to_string()
59 } else {
60 " (does not load as TOML, so safe-chains ignores every rule in it)\n".to_string()
61 };
62 };
63 let mut out = String::new();
64 if let Some(level) = doc.get("level").and_then(toml::Value::as_str) {
65 let _ = writeln!(out, " level {}", crate::sanitize_display(level));
66 }
67 out.push_str(&command_rules(source));
68 for grant in tables(&doc, "grant") {
69 let path = grant.get("path").and_then(toml::Value::as_str).unwrap_or("(no path)");
70 let flag = |k: &str| grant.get(k).and_then(toml::Value::as_bool).unwrap_or(false);
71 let faces = match (flag("read"), flag("write")) {
72 (true, true) => "read and write",
73 (true, false) => "read",
74 (false, true) => "write",
75 (false, false) => "nothing (neither read nor write is set)",
76 };
77 let _ = writeln!(out, " grant {}: {faces}", crate::sanitize_display(path));
78 }
79 for trusted in tables(&doc, "trusted") {
80 let path = trusted.get("path").and_then(toml::Value::as_str).unwrap_or("(no path)");
81 let _ = writeln!(out, " trusted {} (its .safe-chains.toml, at the pinned hash)", crate::sanitize_display(path));
82 }
83 if out.is_empty() {
84 out.push_str(" (no rules)\n");
85 }
86 out
87}
88
89fn tables<'a>(doc: &'a toml::Value, key: &str) -> impl Iterator<Item = &'a toml::Value> {
90 doc.get(key).and_then(toml::Value::as_array).into_iter().flatten()
91}
92
93fn command_rules(source: &str) -> String {
94 let Ok(doc) = toml::from_str::<toml::Value>(source) else {
95 return String::new();
96 };
97 let mut out = String::new();
98 for command in tables(&doc, "command") {
99 let name = crate::sanitize_display(command.get("name").and_then(toml::Value::as_str).unwrap_or("(no name)"));
100 if command.get("deny").and_then(toml::Value::as_bool) == Some(true) {
101 let _ = writeln!(out, " command {name}: never approved (deny = true)");
102 continue;
103 }
104 let level = command.get("level").and_then(toml::Value::as_str).unwrap_or("SafeRead");
105 let subs: Vec<String> = tables(command, "sub")
106 .filter_map(|s| s.get("name").and_then(toml::Value::as_str))
107 .map(crate::sanitize_display)
108 .collect();
109 match subs.as_slice() {
110 [] => {
111 let _ = writeln!(out, " command {name}: {}", crate::sanitize_display(level));
112 }
113 subs => {
114 let _ = writeln!(out, " command {name}: subcommands {}", subs.join(", "));
115 }
116 }
117 }
118 out
119}
120
121fn claude_rules(settings: &str) -> String {
122 let Ok(value) = serde_json::from_str::<serde_json::Value>(settings) else {
123 return String::new();
124 };
125 let mut out = String::new();
126 let lists = [value.get("approved_commands"), value.get("permissions").and_then(|p| p.get("allow"))];
127 for entry in lists
128 .into_iter()
129 .flatten()
130 .filter_map(serde_json::Value::as_array)
131 .flatten()
132 .filter_map(serde_json::Value::as_str)
133 {
134 if entry.starts_with("Bash(") {
135 let _ = writeln!(out, " allow {}", crate::sanitize_display(entry));
136 }
137 }
138 for path in crate::engine::resolve::regions::hypothetical::claude_read_grants(settings) {
139 let _ = writeln!(out, " grant {}: read (from a Read rule)", crate::sanitize_display(&path));
140 }
141 out
142}