Skip to main content

safe_chains/
suggest.rs

1//! `--suggest`: generate the minimal custom-command TOML that would let safe-chains recognize a
2//! command it currently denies because the command NAME is unknown.
3//!
4//! OPT-IN only. Nothing here is ever referenced by the deny/hook output — a user reaches it solely by
5//! running `safe-chains --suggest "<cmd>"`. It rides the existing trust rails (`registry::custom`):
6//! the generated `[[command]]` block goes in a project `.safe-chains.toml`, which is inert until the
7//! user hand-pins its SHA-256 in the write-protected `~/.config/safe-chains.toml`. This module never
8//! touches `~/`, so it cannot self-approve.
9//!
10//! Scope (v1): the "I don't recognize this tool" case. For each simple command whose name safe-chains
11//! doesn't know, emit a `[[command]]` scoped to exactly the observed flags and positional count.
12//! Commands safe-chains DOES recognize are never overridden — a recognized command that is denied is
13//! a deliberate classification (a flag, subcommand, or path), not an unknown, so `--suggest` reports
14//! that rather than generating a bypass.
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::sync::OnceLock;
18
19use sha2::{Digest, Sha256};
20
21use crate::cst::{self, Cmd, Script, SimpleCmd, Word, WordPart};
22use crate::registry;
23
24/// safe-chains cannot infer an unknown tool's real risk, so the generated entry defaults to the
25/// developer band's ceiling — it auto-approves at the default level and the user narrows it (to
26/// `SafeRead`/`Inert`) if the tool is lighter. The `~/` hash-pin review is the backstop.
27const DEFAULT_LEVEL: &str = "SafeWrite";
28
29/// A scoped custom-command entry for one unknown command name.
30///
31/// When every observed use starts with a plain word (`mytool sync`), that word is a SUBCOMMAND and
32/// the entry lists each one as a `[[command.sub]]` with its own flags and count. Otherwise the
33/// entry is flat. Flat is what this always was, and it read `deploytool status` as "deploytool with
34/// any one argument", which also admits `deploytool destroy`. Naming the word keeps an entry to
35/// what was actually run.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct GeneratedEntry {
38    pub name: String,
39    /// Observed flags, sorted and de-duplicated (every `-`-prefixed argument, verbatim). Empty
40    /// when `subs` is not.
41    pub standalone: Vec<String>,
42    /// The largest positional-argument count observed across occurrences. Zero when `subs` is not
43    /// empty.
44    pub max_positional: usize,
45    pub level: String,
46    /// The subcommands observed, sorted by name. Empty for a flat entry.
47    pub subs: Vec<GeneratedSub>,
48}
49
50/// One observed subcommand: its flags and the most positionals seen after it.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct GeneratedSub {
53    pub name: String,
54    pub standalone: Vec<String>,
55    pub max_positional: usize,
56}
57
58/// What `analyze` concluded about a command.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Outcome {
61    /// Already auto-approves — nothing to suggest.
62    AlreadyAllowed,
63    /// Could not parse; a command definition can't fix a structural parse failure.
64    Unparseable,
65    /// Denied, but every command in it is one safe-chains RECOGNIZES — the block is a classification
66    /// decision, not an unknown command. `--suggest` will not generate an override.
67    RecognizedButDenied { names: Vec<String> },
68    /// One or more unknown commands can be supported by the generated entries. `also_recognized`
69    /// lists any recognized commands that also appear (informational).
70    Generated { entries: Vec<GeneratedEntry>, also_recognized: Vec<String> },
71}
72
73/// Analyze `command` and decide what, if anything, `--suggest` can generate. Pure — no I/O.
74pub fn analyze(command: &str) -> Outcome {
75    if cst::command_verdict(command).is_allowed() {
76        return Outcome::AlreadyAllowed;
77    }
78    let Some(script) = cst::parse(command) else {
79        return Outcome::Unparseable;
80    };
81
82    let mut simples: Vec<&SimpleCmd> = Vec::new();
83    collect_script(&script, &mut simples);
84
85    let mut unknown: BTreeMap<String, Vec<Observed>> = BTreeMap::new();
86    let mut recognized: BTreeSet<String> = BTreeSet::new();
87    for sc in simples {
88        let Some(name) = command_basename(sc) else {
89            continue;
90        };
91        if is_known(&name) {
92            recognized.insert(name);
93            continue;
94        }
95        unknown.entry(name).or_default().push(observed_shape(sc));
96    }
97
98    if unknown.is_empty() {
99        return Outcome::RecognizedButDenied { names: recognized.into_iter().collect() };
100    }
101    let entries = unknown.into_iter().map(|(name, uses)| entry_for(name, &uses)).collect();
102    Outcome::Generated { entries, also_recognized: recognized.into_iter().collect() }
103}
104
105/// One observed use of a command: its flags, and its positionals in order.
106struct Observed {
107    flags: Vec<String>,
108    positionals: Vec<String>,
109    /// The first argument is a plain word, so it is in the subcommand position.
110    leads_with_word: bool,
111}
112
113fn entry_for(name: String, uses: &[Observed]) -> GeneratedEntry {
114    let level = DEFAULT_LEVEL.to_string();
115    let every_use_starts_with_a_word = uses.iter().all(|u| u.leads_with_word);
116    if !every_use_starts_with_a_word {
117        let standalone: BTreeSet<String> = uses.iter().flat_map(|u| u.flags.iter().cloned()).collect();
118        let max_positional = uses.iter().map(|u| u.positionals.len()).max().unwrap_or(0);
119        return GeneratedEntry { name, standalone: standalone.into_iter().collect(), max_positional, level, subs: Vec::new() };
120    }
121    let mut subs: BTreeMap<String, (BTreeSet<String>, usize)> = BTreeMap::new();
122    for u in uses {
123        let Some((sub, rest)) = u.positionals.split_first() else { continue };
124        let shape = subs.entry(sub.clone()).or_default();
125        shape.0.extend(u.flags.iter().cloned());
126        shape.1 = shape.1.max(rest.len());
127    }
128    let subs = subs
129        .into_iter()
130        .map(|(name, (flags, max_positional))| GeneratedSub { name, standalone: flags.into_iter().collect(), max_positional })
131        .collect();
132    GeneratedEntry { name, standalone: Vec::new(), max_positional: 0, level, subs }
133}
134
135/// A word that reads as a subcommand name: lower-case letters, digits, `-`, `_` and `:`, starting
136/// with a letter. A path, a number, a URL, or anything with a dot or a space is an argument.
137pub(crate) fn is_sub_word(word: &str) -> bool {
138    word.len() <= 40
139        && word.starts_with(|c: char| c.is_ascii_lowercase())
140        && word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | ':'))
141}
142
143/// The basename of a simple command's name word (`/usr/bin/foo` → `foo`), or `None` for an env-only
144/// command with no name word.
145fn command_basename(sc: &SimpleCmd) -> Option<String> {
146    let raw = sc.words.first()?.eval();
147    if raw.is_empty() {
148        return None;
149    }
150    Some(crate::parse::Token::from_raw(raw).command_name().to_string())
151}
152
153/// The observed flags (each `-`-prefixed argument, but not a lone `-`) and the count of positional
154/// arguments. A valued flag's value counts as a positional, which is fine: the generated grammar
155/// still admits the observed invocation, just classified as flag + positional.
156fn observed_shape(sc: &SimpleCmd) -> Observed {
157    let mut flags = Vec::new();
158    let mut positionals = Vec::new();
159    for word in sc.words.iter().skip(1) {
160        let s = word.eval();
161        if s.starts_with('-') && s != "-" {
162            flags.push(s);
163        } else {
164            positionals.push(s);
165        }
166    }
167    let leads_with_word = sc.words.get(1).is_some_and(|w| is_sub_word(&w.eval()));
168    Observed { flags, positionals, leads_with_word }
169}
170
171fn collect_script<'a>(script: &'a Script, out: &mut Vec<&'a SimpleCmd>) {
172    for stmt in &script.0 {
173        for cmd in &stmt.pipeline.commands {
174            collect_cmd(cmd, out);
175        }
176    }
177}
178
179fn collect_cmd<'a>(cmd: &'a Cmd, out: &mut Vec<&'a SimpleCmd>) {
180    match cmd {
181        Cmd::Simple(sc) => {
182            out.push(sc);
183            for word in &sc.words {
184                collect_word(word, out);
185            }
186        }
187        Cmd::Subshell { body, .. } | Cmd::BraceGroup { body, .. } => collect_script(body, out),
188        Cmd::For { items, body, .. } => {
189            for word in items {
190                collect_word(word, out);
191            }
192            collect_script(body, out);
193        }
194        Cmd::While { cond, body, .. } | Cmd::Until { cond, body, .. } => {
195            collect_script(cond, out);
196            collect_script(body, out);
197        }
198        Cmd::If { branches, else_body, .. } => {
199            for branch in branches {
200                collect_script(&branch.cond, out);
201                collect_script(&branch.body, out);
202            }
203            if let Some(body) = else_body {
204                collect_script(body, out);
205            }
206        }
207        Cmd::DoubleBracket { words, .. } => {
208            for word in words {
209                collect_word(word, out);
210            }
211        }
212        Cmd::Case { subject, arms, .. } => {
213            collect_word(subject, out);
214            for arm in arms {
215                collect_script(&arm.body, out);
216            }
217        }
218        Cmd::FunctionDef { body, .. } => collect_script(body, out),
219    }
220}
221
222/// Recurse into command/process substitutions nested inside a word (`$(foo)`, `<(bar)`, and the same
223/// inside double quotes), so an unknown command hidden in a substitution is surfaced too. Backticks
224/// (`WordPart::Backtick`) hold an UNPARSED string, so an unknown command inside one is not surfaced —
225/// harmless: the classifier still denies an unsafe backtick, so the command stays blocked (a coverage
226/// gap, never a bypass). The user can `--suggest` the inner command directly.
227fn collect_word<'a>(word: &'a Word, out: &mut Vec<&'a SimpleCmd>) {
228    for part in &word.0 {
229        match part {
230            WordPart::CmdSub(s) | WordPart::ProcSub(s) => collect_script(s, out),
231            WordPart::DQuote(w) => collect_word(w, out),
232            _ => {}
233        }
234    }
235}
236
237/// Whether safe-chains recognizes `name` (built-in handler or registry command, via its canonical
238/// spelling). Custom user commands that already ALLOW an invocation are caught earlier by the
239/// `AlreadyAllowed` check, so they need not be enumerated here.
240pub(crate) fn is_known(name: &str) -> bool {
241    known_names().contains(registry::canonical_name(name)) || crate::handlers::is_built_in(name)
242}
243
244fn known_names() -> &'static BTreeSet<String> {
245    static KNOWN: OnceLock<BTreeSet<String>> = OnceLock::new();
246    KNOWN.get_or_init(|| {
247        let mut set: BTreeSet<String> = crate::docs::all_command_docs().into_iter().map(|d| d.name).collect();
248        for name in registry::toml_command_names() {
249            set.insert(name.to_string());
250        }
251        set
252    })
253}
254
255/// Render the generated entries as `[[command]]` TOML blocks. Minimal and always valid — this is
256/// exactly the text written to `.safe-chains.toml` and fed to the SHA-256 pin, so it must be stable.
257pub fn render_toml(entries: &[GeneratedEntry]) -> String {
258    let mut out = String::new();
259    for (i, entry) in entries.iter().enumerate() {
260        if i > 0 {
261            out.push('\n');
262        }
263        out.push_str("[[command]]\n");
264        out.push_str(&format!("name = {}\n", toml_str(&entry.name)));
265        if entry.subs.is_empty() {
266            push_shape(&mut out, &entry.standalone, entry.max_positional, &entry.level);
267        }
268        for sub in &entry.subs {
269            out.push_str("\n[[command.sub]]\n");
270            out.push_str(&format!("name = {}\n", toml_str(&sub.name)));
271            push_shape(&mut out, &sub.standalone, sub.max_positional, &entry.level);
272        }
273    }
274    out
275}
276
277fn push_shape(out: &mut String, standalone: &[String], max_positional: usize, level: &str) {
278    if !standalone.is_empty() {
279        let items: Vec<String> = standalone.iter().map(|f| toml_str(f)).collect();
280        out.push_str(&format!("standalone = [{}]\n", items.join(", ")));
281    }
282    out.push_str(&format!("max_positional = {max_positional}\n"));
283    out.push_str(&format!("level = {}\n", toml_str(level)));
284}
285
286/// A TOML basic (double-quoted) string with the control/quote/backslash escapes TOML requires, so
287/// even an odd flag spelling produces valid TOML.
288pub(crate) fn toml_str(s: &str) -> String {
289    let mut out = String::from("\"");
290    for c in s.chars() {
291        match c {
292            '"' => out.push_str("\\\""),
293            '\\' => out.push_str("\\\\"),
294            '\n' => out.push_str("\\n"),
295            '\r' => out.push_str("\\r"),
296            '\t' => out.push_str("\\t"),
297            c if (c as u32) < 0x20 || c == '\u{7f}' => {
298                out.push_str(&format!("\\u{:04X}", c as u32));
299            }
300            c => out.push(c),
301        }
302    }
303    out.push('"');
304    out
305}
306
307/// SHA-256 of `bytes` as lowercase hex — the exact hash `registry::custom::repo_is_trusted` computes
308/// over a `.safe-chains.toml`, so the printed pin matches what the trust check will require.
309pub fn config_hash(bytes: &[u8]) -> String {
310    Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
311}
312
313/// The new `.safe-chains.toml` content: the existing file (empty if none) with the generated blocks
314/// appended, separated by a blank line.
315pub fn merged_content(existing: &str, entries: &[GeneratedEntry]) -> String {
316    let block = render_toml(entries);
317    if existing.trim().is_empty() {
318        return block;
319    }
320    let mut content = existing.to_string();
321    if !content.ends_with('\n') {
322        content.push('\n');
323    }
324    content.push('\n');
325    content.push_str(&block);
326    content
327}
328
329/// The `[[trusted]]` pin the user pastes into `~/.config/safe-chains.toml` to approve the file.
330pub fn pin_block(canonical_dir: &str, hash: &str) -> String {
331    format!("[[trusted]]\npath = {}\nsha256 = {}\n", toml_str(canonical_dir), toml_str(hash),)
332}
333
334#[cfg(test)]
335mod tests;