Skip to main content

surjection_core/scan/
rules.rs

1//! The scanner's rules: data (`rules.toml`, built in, or a newer copy in
2//! `<SURJECTION_HOME>/state/scan-rules.toml`), checked and compiled once.
3//! The file format is described at the top of `rules.toml`.
4
5use std::collections::BTreeSet;
6use std::sync::LazyLock;
7
8use regex::Regex;
9use serde::Deserialize;
10use sha2::{Digest, Sha256};
11
12use super::Severity;
13use crate::error::{CoreError, ErrorCode};
14
15/// The rules file format this build reads.
16pub const SCHEMA: u32 = 1;
17
18const BUILTIN_TEXT: &str = include_str!("rules.toml");
19
20/// A unit test loads the built-in file; a build that ships broken rules
21/// must not scan with none.
22static BUILTIN: LazyLock<Rules> = LazyLock::new(|| match Rules::parse(BUILTIN_TEXT) {
23    Ok(rules) => rules,
24    Err(err) => panic!("the built-in scan rules do not load: {err:?}"),
25});
26
27/// What a content pattern runs on.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum Target {
31    /// Prose: `.md`, `.markdown`, `.mdx`, `.txt`, `.rst`, `.adoc`, and
32    /// files without an extension that do not start with `#!`.
33    Markdown,
34    /// Every other text file.
35    Code,
36    /// An MCP server's command line.
37    Command,
38}
39
40/// One compiled rule.
41#[derive(Debug, Clone)]
42pub struct Rule {
43    pub id: String,
44    pub severity: Severity,
45    pub message: String,
46    /// Severity of a match in Markdown prose (outside fenced code
47    /// blocks): talking about a command is not running it.
48    pub(super) prose: Option<Severity>,
49    pub(super) targets: Vec<Target>,
50    pub(super) path: Option<Regex>,
51    pub(super) pattern: Option<Regex>,
52    pub(super) unless: Option<Regex>,
53    pub(super) requires: Vec<Regex>,
54}
55
56impl Rule {
57    pub fn applies_to(&self, target: Target) -> bool {
58        self.targets.contains(&target)
59    }
60}
61
62/// A checked rules file, or the built-in rules with a custom file merged
63/// in ([`Rules::with_custom`]).
64#[derive(Debug, Clone)]
65pub struct Rules {
66    version: u32,
67    fingerprint: String,
68    rules: Vec<Rule>,
69    custom: bool,
70}
71
72#[derive(Deserialize)]
73#[serde(deny_unknown_fields)]
74struct RawRules {
75    #[allow(dead_code)]
76    schema: u32,
77    version: u32,
78    #[serde(default, rename = "rule")]
79    rules: Vec<RawRule>,
80}
81
82#[derive(Deserialize)]
83#[serde(deny_unknown_fields)]
84struct RawRule {
85    id: String,
86    severity: Severity,
87    message: String,
88    targets: Option<Vec<Target>>,
89    path: Option<String>,
90    pattern: Option<String>,
91    unless: Option<String>,
92    #[serde(default)]
93    requires: Vec<String>,
94    prose: Option<Severity>,
95}
96
97fn invalid(code: ErrorCode, message: String) -> CoreError {
98    CoreError::new(code, format!("scan rules: {message}"))
99}
100
101fn is_rule_id(id: &str) -> bool {
102    !id.is_empty()
103        && id.split('-').all(|part| {
104            !part.is_empty()
105                && part
106                    .bytes()
107                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
108        })
109}
110
111/// `\b` as an ASCII word boundary (`(?-u:\b)`) outside character
112/// classes: a Unicode `\b` makes `regex` fall back to its slow engine on
113/// any non-ASCII text (minutes for a large hostile file).
114fn ascii_word_boundaries(pattern: &str) -> String {
115    let mut out = String::with_capacity(pattern.len() + 16);
116    let mut chars = pattern.chars();
117    let mut class = 0usize;
118    while let Some(c) = chars.next() {
119        match c {
120            '\\' => match chars.next() {
121                Some('b') if class == 0 => out.push_str("(?-u:\\b)"),
122                Some(next) => {
123                    out.push('\\');
124                    out.push(next);
125                }
126                None => out.push('\\'),
127            },
128            '[' => {
129                class += 1;
130                out.push(c);
131            }
132            ']' if class > 0 => {
133                class -= 1;
134                out.push(c);
135            }
136            _ => out.push(c),
137        }
138    }
139    out
140}
141
142fn compile(id: &str, field: &str, pattern: &str) -> Result<Regex, CoreError> {
143    Regex::new(&ascii_word_boundaries(pattern)).map_err(|err| {
144        invalid(
145            ErrorCode::ParseError,
146            format!("rule {id:?}: `{field}`: {err}"),
147        )
148    })
149}
150
151fn fingerprint_of(text: &str) -> String {
152    Sha256::digest(text.as_bytes())
153        .iter()
154        .map(|byte| format!("{byte:02x}"))
155        .collect()
156}
157
158impl Rules {
159    /// The rules this build ships.
160    pub fn builtin() -> &'static Rules {
161        &BUILTIN
162    }
163
164    /// Reads and checks a rules file: `unsupported_schema` for another
165    /// `schema`, `parse_error` for bad TOML or a pattern that does not
166    /// compile, `invalid_value`/`missing_field`/`field_not_allowed` for a
167    /// rule that breaks the format.
168    pub fn parse(text: &str) -> Result<Rules, CoreError> {
169        let table: toml::Table = toml::from_str(text)
170            .map_err(|err| invalid(ErrorCode::ParseError, err.message().to_owned()))?;
171        match table.get("schema").and_then(toml::Value::as_integer) {
172            Some(schema) if schema == i64::from(SCHEMA) => {}
173            Some(schema) => {
174                return Err(invalid(
175                    ErrorCode::UnsupportedSchema,
176                    format!("schema {schema} is not supported (this build reads {SCHEMA})"),
177                ));
178            }
179            None => return Err(invalid(ErrorCode::MissingField, "no `schema`".to_owned())),
180        }
181        let raw: RawRules =
182            toml::Value::Table(table)
183                .try_into()
184                .map_err(|err: toml::de::Error| {
185                    invalid(ErrorCode::ParseError, err.message().to_owned())
186                })?;
187        if raw.version == 0 {
188            return Err(invalid(
189                ErrorCode::InvalidValue,
190                "`version` must be 1 or more".to_owned(),
191            ));
192        }
193        let mut seen = BTreeSet::new();
194        let mut rules = Vec::with_capacity(raw.rules.len());
195        for rule in raw.rules {
196            rules.push(check(rule, &mut seen)?);
197        }
198        Ok(Rules {
199            version: raw.version,
200            fingerprint: fingerprint_of(text),
201            rules,
202            custom: false,
203        })
204    }
205
206    /// These rules with a custom rules file merged in: a rule with a new
207    /// id is added; a rule with a built-in id may only raise that rule's
208    /// severity (its pattern is ignored, the built-in one keeps running).
209    /// A built-in rule is never removed or lowered: such an entry is
210    /// skipped with a warning (the returned messages).
211    pub fn with_custom(&self, text: &str) -> Result<(Rules, Vec<String>), CoreError> {
212        let custom = Rules::parse(text)?;
213        let mut rules = self.rules.clone();
214        let mut warnings = Vec::new();
215        for rule in custom.rules {
216            match rules.iter_mut().find(|known| known.id == rule.id) {
217                Some(known) if rule.severity >= known.severity => {
218                    known.severity = rule.severity;
219                }
220                Some(known) => warnings.push(format!(
221                    "custom scan rule {:?} would lower a built-in rule from {} to {}; the built-in severity is kept",
222                    rule.id,
223                    known.severity.as_str(),
224                    rule.severity.as_str()
225                )),
226                None => rules.push(rule),
227            }
228        }
229        Ok((
230            Rules {
231                version: self.version,
232                fingerprint: fingerprint_of(&format!(
233                    "{}\0{}",
234                    self.fingerprint, custom.fingerprint
235                )),
236                rules,
237                custom: true,
238            },
239            warnings,
240        ))
241    }
242
243    /// The rules file's `version` (the built-in one for merged rules).
244    pub fn version(&self) -> u32 {
245        self.version
246    }
247
248    /// SHA-256 (hex) of the rules text: part of the cache key.
249    pub fn fingerprint(&self) -> &str {
250        &self.fingerprint
251    }
252
253    /// A custom rules file is merged in.
254    pub fn is_custom(&self) -> bool {
255        self.custom
256    }
257
258    pub fn rules(&self) -> &[Rule] {
259        &self.rules
260    }
261}
262
263fn check(raw: RawRule, seen: &mut BTreeSet<String>) -> Result<Rule, CoreError> {
264    let id = raw.id;
265    if !is_rule_id(&id) {
266        return Err(invalid(
267            ErrorCode::InvalidId,
268            format!("rule id {id:?} is not kebab-case (a-z, 0-9, -)"),
269        ));
270    }
271    if !seen.insert(id.clone()) {
272        return Err(invalid(
273            ErrorCode::AlreadyExists,
274            format!("rule {id:?} is defined twice"),
275        ));
276    }
277    let message = raw.message.trim().to_owned();
278    if message.is_empty() {
279        return Err(invalid(
280            ErrorCode::MissingField,
281            format!("rule {id:?} has no message"),
282        ));
283    }
284    let not_allowed =
285        |what: &str| invalid(ErrorCode::FieldNotAllowed, format!("rule {id:?}: {what}"));
286    let targets = match (&raw.pattern, raw.targets) {
287        (None, None) if raw.path.is_none() => {
288            return Err(invalid(
289                ErrorCode::MissingField,
290                format!("rule {id:?} has neither `pattern` nor `path`"),
291            ));
292        }
293        (None, None) => Vec::new(),
294        (None, Some(_)) => {
295            return Err(not_allowed(
296                "`targets` needs a `pattern` (a path rule matches files)",
297            ));
298        }
299        (Some(_), None) => vec![Target::Markdown, Target::Code],
300        (Some(_), Some(targets)) if targets.is_empty() => {
301            return Err(invalid(
302                ErrorCode::InvalidValue,
303                format!("rule {id:?} has empty `targets`"),
304            ));
305        }
306        (Some(_), Some(targets)) => targets,
307    };
308    if raw.pattern.is_none() && (raw.unless.is_some() || !raw.requires.is_empty()) {
309        return Err(not_allowed("`unless` and `requires` need a `pattern`"));
310    }
311    if raw.path.is_some() && targets.contains(&Target::Command) {
312        return Err(not_allowed(
313            "a command line has no path; `path` and the `command` target exclude each other",
314        ));
315    }
316    if let Some(prose) = raw.prose
317        && (!targets.contains(&Target::Markdown) || prose >= raw.severity)
318    {
319        return Err(not_allowed(&format!(
320            "`prose` ({}) needs the markdown target and a severity below `severity`",
321            prose.as_str()
322        )));
323    }
324    Ok(Rule {
325        path: raw
326            .path
327            .as_deref()
328            .map(|p| compile(&id, "path", p))
329            .transpose()?,
330        pattern: raw
331            .pattern
332            .as_deref()
333            .map(|p| compile(&id, "pattern", p))
334            .transpose()?,
335        unless: raw
336            .unless
337            .as_deref()
338            .map(|p| compile(&id, "unless", p))
339            .transpose()?,
340        requires: raw
341            .requires
342            .iter()
343            .map(|p| compile(&id, "requires", p))
344            .collect::<Result<_, _>>()?,
345        id,
346        severity: raw.severity,
347        message,
348        prose: raw.prose,
349        targets,
350    })
351}