Skip to main content

surjection_core/scan/
mod.rs

1//! The built-in offline scanner (SPEC 17, #25): Surjection's own rules,
2//! shipped as data (`rules.toml`), run locally on every skill install and
3//! update and on every MCP server drafted from a Git repository or folder.
4//! Nothing leaves the machine.
5//!
6//! A scan gives findings (severity, rule, file and line, message) and a
7//! verdict, the worst finding: `clean` (none, or `info` only), `warning`
8//! or `dangerous`. [`gate`] refuses `dangerous` content with
9//! `scan_blocked` unless the user explicitly chose to install anyway.
10//! Trusting a source never skips the scan. Results are cached by content
11//! hash ([`Scanner::new`]).
12//!
13//! The scanner is a second opinion, not a guarantee: a clean verdict means
14//! no rule matched, not that the content is safe.
15
16mod cache;
17mod engine;
18pub mod external;
19pub mod rules;
20#[cfg(test)]
21mod tests;
22
23use std::borrow::Cow;
24use std::path::Path;
25
26use serde::{Deserialize, Serialize};
27
28use crate::error::{CoreError, ErrorCode};
29use crate::fs::Fs;
30use crate::paths::SurjectionHome;
31use crate::skills::{SkillFiles, content_hash};
32
33pub use cache::CACHE_DIR;
34use cache::Cache;
35pub use rules::{Rule, Rules, Target};
36
37/// The `scanner` of the built-in scanner's findings.
38pub const SCANNER: &str = "builtin";
39/// A custom rules file below `<SURJECTION_HOME>/state`, merged into the
40/// built-in rules ([`Rules::with_custom`]: add rules or raise severities).
41pub const RULES_OVERRIDE_FILE: &str = "scan-rules.toml";
42
43/// How bad one finding is.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum Severity {
47    Info,
48    Warning,
49    Dangerous,
50}
51
52impl Severity {
53    pub const fn as_str(self) -> &'static str {
54        match self {
55            Severity::Info => "info",
56            Severity::Warning => "warning",
57            Severity::Dangerous => "dangerous",
58        }
59    }
60}
61
62/// The worst finding of a scan (`info` findings leave it `clean`).
63#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
64#[serde(rename_all = "snake_case")]
65pub enum Verdict {
66    Clean,
67    Warning,
68    Dangerous,
69}
70
71impl Verdict {
72    pub const fn as_str(self) -> &'static str {
73        match self {
74            Verdict::Clean => "clean",
75            Verdict::Warning => "warning",
76            Verdict::Dangerous => "dangerous",
77        }
78    }
79
80    pub fn of(findings: &[Finding]) -> Self {
81        match findings.iter().map(|finding| finding.severity).max() {
82            Some(Severity::Dangerous) => Verdict::Dangerous,
83            Some(Severity::Warning) => Verdict::Warning,
84            Some(Severity::Info) | None => Verdict::Clean,
85        }
86    }
87}
88
89/// One thing a rule matched.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Finding {
92    /// [`SCANNER`] for the built-in scanner.
93    pub scanner: String,
94    /// The rule's id.
95    pub rule: String,
96    pub severity: Severity,
97    /// The file, relative to the skill (or repository) root,
98    /// `/`-separated; `None` for a command line.
99    pub file: Option<String>,
100    /// 1-based line of the match; `None` for a path rule and a command
101    /// line.
102    pub line: Option<u32>,
103    pub message: String,
104    /// The matched text, shortened, with secret-shaped tokens masked and
105    /// invisible characters spelled out (`\u{200B}`, `[hidden: ...]`).
106    pub excerpt: Option<String>,
107}
108
109impl Finding {
110    /// `rule (file:line)`, for messages.
111    pub fn label(&self) -> String {
112        match (&self.file, self.line) {
113            (Some(file), Some(line)) => format!("{} ({file}:{line})", self.rule),
114            (Some(file), None) => format!("{} ({file})", self.rule),
115            _ => self.rule.clone(),
116        }
117    }
118}
119
120/// What a scan found.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct ScanReport {
123    pub verdict: Verdict,
124    /// Sorted by file, line and rule.
125    pub findings: Vec<Finding>,
126    /// `version` of the rules that ran.
127    pub rules_version: u32,
128    /// [`content_hash`] of the scanned files; `None` for a command line or
129    /// a merged report of different content.
130    pub content_hash: Option<String>,
131    /// Taken from the cache, not scanned now.
132    #[serde(default, skip_serializing)]
133    pub cached: bool,
134    /// A custom rules file (`state/scan-rules.toml`) was merged into the
135    /// built-in rules for this scan.
136    #[serde(default, skip_serializing)]
137    pub custom_rules: bool,
138    /// Problems loading the rules (a custom rules file not used, or an
139    /// entry of it skipped); the built-in rules always ran.
140    #[serde(default, skip_serializing)]
141    pub warnings: Vec<String>,
142}
143
144impl ScanReport {
145    fn new(rules_version: u32, content_hash: Option<String>, mut findings: Vec<Finding>) -> Self {
146        findings.sort_by(|a, b| (&a.file, a.line, &a.rule).cmp(&(&b.file, b.line, &b.rule)));
147        Self {
148            verdict: Verdict::of(&findings),
149            findings,
150            rules_version,
151            content_hash,
152            cached: false,
153            custom_rules: false,
154            warnings: Vec::new(),
155        }
156    }
157
158    /// Adds another scan of the same item (an MCP draft's repository
159    /// files and its command line): findings together, the worse verdict.
160    pub fn merge(&mut self, other: ScanReport) {
161        let content_hash = match (self.content_hash.take(), other.content_hash) {
162            (Some(a), Some(b)) if a == b => Some(a),
163            (Some(hash), None) | (None, Some(hash)) => Some(hash),
164            _ => None,
165        };
166        let mut findings = std::mem::take(&mut self.findings);
167        findings.extend(other.findings);
168        let cached = self.cached && other.cached;
169        let custom_rules = self.custom_rules || other.custom_rules;
170        let mut warnings = std::mem::take(&mut self.warnings);
171        for warning in other.warnings {
172            if !warnings.contains(&warning) {
173                warnings.push(warning);
174            }
175        }
176        *self = ScanReport::new(
177            self.rules_version.max(other.rules_version),
178            content_hash,
179            findings,
180        );
181        self.cached = cached;
182        self.custom_rules = custom_rules;
183        self.warnings = warnings;
184    }
185
186    /// The findings that make the verdict `dangerous`.
187    pub fn dangerous(&self) -> impl Iterator<Item = &Finding> {
188        self.findings
189            .iter()
190            .filter(|finding| finding.severity == Severity::Dangerous)
191    }
192}
193
194/// Refuses content whose verdict is `dangerous` (`scan_blocked`) unless
195/// the user explicitly chose to install it anyway.
196pub fn gate(report: &ScanReport, allow_dangerous: bool) -> Result<(), CoreError> {
197    if allow_dangerous || report.verdict != Verdict::Dangerous {
198        return Ok(());
199    }
200    let labels: Vec<String> = report.dangerous().map(Finding::label).collect();
201    let mut shown = labels
202        .iter()
203        .take(3)
204        .cloned()
205        .collect::<Vec<_>>()
206        .join(", ");
207    if labels.len() > 3 {
208        shown.push_str(&format!(" and {} more", labels.len() - 3));
209    }
210    let plural = if labels.len() == 1 { "" } else { "s" };
211    Err(CoreError::new(
212        ErrorCode::ScanBlocked,
213        format!(
214            "the built-in scan found {} dangerous finding{plural}: {shown}; review them, and install anyway only if you trust this content",
215            labels.len()
216        ),
217    ))
218}
219
220/// Runs the rules, with the cache when made by [`Scanner::new`].
221pub struct Scanner<'a> {
222    rules: Cow<'static, Rules>,
223    cache: Option<Cache<'a>>,
224    warnings: Vec<String>,
225}
226
227impl<'a> Scanner<'a> {
228    /// The scanner installs and updates use: the built-in rules, with a
229    /// custom `state/scan-rules.toml` merged in (it may add rules or
230    /// raise severities only; one that does not load is a warning),
231    /// results cached in `cache/scan`.
232    pub fn new(fs: &'a dyn Fs, home: &SurjectionHome) -> Self {
233        let (rules, warnings) = load_rules(fs, &home.state_dir().join(RULES_OVERRIDE_FILE));
234        Self {
235            rules,
236            cache: Some(Cache::new(fs, home.cache_dir().join(CACHE_DIR))),
237            warnings,
238        }
239    }
240
241    pub fn rules(&self) -> &Rules {
242        &self.rules
243    }
244
245    /// Problems loading the rules; every report carries them too.
246    pub fn warnings(&self) -> &[String] {
247        &self.warnings
248    }
249
250    fn finish(&self, mut report: ScanReport) -> ScanReport {
251        report.custom_rules = self.rules.is_custom();
252        report.warnings.clone_from(&self.warnings);
253        report
254    }
255
256    /// Scans files (a skill folder, a repository's files) by relative
257    /// `/`-separated path.
258    pub fn scan_files(&self, files: &SkillFiles) -> ScanReport {
259        let hash = content_hash(files);
260        let key = self.cache.as_ref().map(|_| Cache::key(&self.rules, &hash));
261        if let (Some(cache), Some(key)) = (&self.cache, &key)
262            && let Some(report) = cache.get(key)
263        {
264            return self.finish(report);
265        }
266        let report = ScanReport::new(
267            self.rules.version(),
268            Some(hash),
269            engine::scan_files(&self.rules, files),
270        );
271        if let (Some(cache), Some(key)) = (&self.cache, &key) {
272            cache.put(key, &report);
273        }
274        self.finish(report)
275    }
276
277    /// Scans an MCP server's command line: `command` and `args` joined by
278    /// spaces, as the `command` rules expect.
279    pub fn scan_command(&self, command: &str, args: &[String]) -> ScanReport {
280        let mut line = command.to_owned();
281        for arg in args {
282            line.push(' ');
283            line.push_str(arg);
284        }
285        self.finish(ScanReport::new(
286            self.rules.version(),
287            None,
288            engine::scan_command(&self.rules, &line),
289        ))
290    }
291}
292
293impl Scanner<'static> {
294    /// The built-in rules, without a cache.
295    pub fn builtin() -> Self {
296        Self::with_rules(Cow::Borrowed(Rules::builtin()))
297    }
298
299    /// Other rules (tests, a rules file being checked), without a cache.
300    pub fn with_rules(rules: Cow<'static, Rules>) -> Self {
301        Self {
302            rules,
303            cache: None,
304            warnings: Vec::new(),
305        }
306    }
307}
308
309/// The built-in rules, with the custom rules file merged in when there is
310/// one that loads. The built-in rules always run.
311fn load_rules(fs: &dyn Fs, path: &Path) -> (Cow<'static, Rules>, Vec<String>) {
312    let builtin = Rules::builtin();
313    if !fs.exists(path) {
314        return (Cow::Borrowed(builtin), Vec::new());
315    }
316    let merged = fs
317        .read_to_string(path)
318        .map_err(|err| CoreError::new(ErrorCode::IoError, err.to_string()))
319        .and_then(|text| builtin.with_custom(&text));
320    match merged {
321        Ok((rules, warnings)) => (Cow::Owned(rules), warnings),
322        Err(err) => (
323            Cow::Borrowed(builtin),
324            vec![format!(
325                "state/{RULES_OVERRIDE_FILE} is not used, only the built-in scan rules ran: {}",
326                err.message()
327            )],
328        ),
329    }
330}