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 = listed_home();
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 listed_home() -> String {
49 #[cfg(test)]
50 {
51 crate::registry::custom::config_home().to_string_lossy().into_owned()
52 }
53 #[cfg(not(test))]
54 crate::process_home::var().unwrap_or_default()
55}
56
57fn tilde(path: &str, home: &str) -> String {
58 match path.strip_prefix(home) {
59 Some(rest) if !home.is_empty() && rest.starts_with('/') => format!("~{rest}"),
60 _ => path.to_string(),
61 }
62}
63
64fn user_rules(source: &str) -> String {
65 let Ok(doc) = toml::from_str::<toml::Value>(source) else {
66 return if source.trim().is_empty() {
67 " (no file, so no rules)\n".to_string()
68 } else {
69 " (does not load as TOML, so safe-chains ignores every rule in it)\n".to_string()
70 };
71 };
72 let mut out = String::new();
73 if let Some(level) = doc.get("level").and_then(toml::Value::as_str) {
74 let _ = writeln!(out, " level {}", crate::sanitize_display(level));
75 }
76 out.push_str(&command_rules(source));
77 for grant in tables(&doc, "grant") {
78 let path = grant.get("path").and_then(toml::Value::as_str).unwrap_or("(no path)");
79 let flag = |k: &str| grant.get(k).and_then(toml::Value::as_bool).unwrap_or(false);
80 let faces = match (flag("read"), flag("write")) {
81 (true, true) => "read and write",
82 (true, false) => "read",
83 (false, true) => "write",
84 (false, false) => "nothing (neither read nor write is set)",
85 };
86 let _ = writeln!(out, " grant {}: {faces}", crate::sanitize_display(path));
87 }
88 for trusted in tables(&doc, "trusted") {
89 let path = trusted.get("path").and_then(toml::Value::as_str).unwrap_or("(no path)");
90 let _ = writeln!(out, " trusted {} (its .safe-chains.toml, at the pinned hash)", crate::sanitize_display(path));
91 }
92 if out.is_empty() {
93 out.push_str(" (no rules)\n");
94 }
95 out
96}
97
98fn tables<'a>(doc: &'a toml::Value, key: &str) -> impl Iterator<Item = &'a toml::Value> {
99 doc.get(key).and_then(toml::Value::as_array).into_iter().flatten()
100}
101
102fn command_rules(source: &str) -> String {
103 let Ok(doc) = toml::from_str::<toml::Value>(source) else {
104 return String::new();
105 };
106 let mut out = String::new();
107 for command in tables(&doc, "command") {
108 let name = crate::sanitize_display(command.get("name").and_then(toml::Value::as_str).unwrap_or("(no name)"));
109 if command.get("deny").and_then(toml::Value::as_bool) == Some(true) {
110 let _ = writeln!(out, " command {name}: never approved (deny = true)");
111 continue;
112 }
113 let level = command.get("level").and_then(toml::Value::as_str).unwrap_or("SafeRead");
114 let subs: Vec<String> = tables(command, "sub")
115 .filter_map(|s| s.get("name").and_then(toml::Value::as_str))
116 .map(crate::sanitize_display)
117 .collect();
118 match subs.as_slice() {
119 [] => {
120 let _ = writeln!(out, " command {name}: {}", crate::sanitize_display(level));
121 }
122 subs => {
123 let _ = writeln!(out, " command {name}: subcommands {}", subs.join(", "));
124 }
125 }
126 }
127 out
128}
129
130fn claude_rules(settings: &str) -> String {
131 let Ok(value) = serde_json::from_str::<serde_json::Value>(settings) else {
132 return String::new();
133 };
134 let mut out = String::new();
135 let lists = [value.get("approved_commands"), value.get("permissions").and_then(|p| p.get("allow"))];
136 for entry in lists
137 .into_iter()
138 .flatten()
139 .filter_map(serde_json::Value::as_array)
140 .flatten()
141 .filter_map(serde_json::Value::as_str)
142 {
143 if entry.starts_with("Bash(") {
144 let _ = writeln!(out, " allow {}", crate::sanitize_display(entry));
145 }
146 }
147 for path in crate::engine::resolve::regions::hypothetical::claude_read_grants(settings) {
148 let _ = writeln!(out, " grant {}: read (from a Read rule)", crate::sanitize_display(&path));
149 }
150 out
151}