Skip to main content

slopguard_core/
rule.rs

1use std::collections::HashSet;
2use std::fmt;
3use std::fs::read_to_string;
4use std::io::Error as IoError;
5use std::path::{Component, Path, PathBuf};
6use std::str::{from_utf8, Utf8Error};
7
8use ast_grep_language::SupportLang;
9use ignore::WalkBuilder;
10use serde::{Deserialize, Serialize};
11use serde_yaml::Value;
12use slopguard_rules::BuiltinRules;
13use strum::{Display, EnumIter, EnumString};
14use thiserror::Error;
15
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub struct RuleId(pub String);
18
19impl fmt::Display for RuleId {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        f.write_str(&self.0)
22    }
23}
24
25impl RuleId {
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl From<String> for RuleId {
32    fn from(s: String) -> Self {
33        Self(s)
34    }
35}
36
37impl From<&str> for RuleId {
38    fn from(s: &str) -> Self {
39        Self(s.to_string())
40    }
41}
42
43#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "lowercase")]
45#[strum(serialize_all = "lowercase")]
46pub enum Severity {
47    Error,
48    Warning,
49}
50
51#[derive(Debug, Display, EnumIter, Clone, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "lowercase")]
53#[strum(serialize_all = "lowercase")]
54pub enum Language {
55    Rust,
56    TypeScript,
57}
58
59impl Language {
60    /// The ast-grep languages a rule written for this language is compiled
61    /// against. TypeScript rules also cover TSX files.
62    pub fn ast_grep_langs(&self) -> &'static [SupportLang] {
63        match self {
64            Language::Rust => &[SupportLang::Rust],
65            Language::TypeScript => &[SupportLang::TypeScript, SupportLang::Tsx],
66        }
67    }
68}
69
70#[derive(Debug, Display, EnumString, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "lowercase")]
72#[strum(serialize_all = "lowercase")]
73pub enum Category {
74    Slop,
75    Security,
76    #[default]
77    Correctness,
78}
79
80impl Category {
81    /// Derive the category from the first directory of a rule path relative to
82    /// its ruleset root (e.g. `security/no-debug.yml`). Returns `None` when the
83    /// path has no directory or the directory is not a known category.
84    fn from_rule_path(path: &Path) -> Option<Self> {
85        match path.components().next()? {
86            Component::Normal(dir) => dir.to_str()?.parse().ok(),
87            _ => None,
88        }
89    }
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct RuleTests {
94    #[serde(default)]
95    pub should_match: Vec<String>,
96    #[serde(default)]
97    pub should_not_match: Vec<String>,
98}
99
100fn default_enabled() -> bool {
101    true
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct Rule {
106    pub id: RuleId,
107    pub language: Language,
108    pub severity: Severity,
109    pub message: String,
110    #[serde(default)]
111    pub note: Option<String>,
112    #[serde(default)]
113    pub category: Option<Category>,
114    #[serde(default)]
115    pub fix: Option<String>,
116    pub rule: Value,
117    #[serde(default)]
118    pub files: Option<Vec<String>>,
119    #[serde(default)]
120    pub ignores: Option<Vec<String>>,
121    /// Drop findings located inside `#[cfg(test)]` blocks of scanned Rust files.
122    /// Complements `ignores`, which only filters whole files by path.
123    #[serde(default = "default_enabled")]
124    pub enabled: bool,
125    #[serde(default)]
126    pub skip_test_code: bool,
127    #[serde(default)]
128    pub tests: Option<RuleTests>,
129}
130
131#[derive(Debug, Error)]
132pub enum RuleError {
133    #[error("failed to parse rule YAML: {0}")]
134    Parse(#[from] serde_yaml::Error),
135
136    #[error("rule '{id}': rule field must not be empty")]
137    EmptyRule { id: RuleId },
138
139    #[error("duplicate rule id: '{id}'")]
140    DuplicateId { id: RuleId },
141
142    #[error("failed to read rule file '{path}': {source}")]
143    Io {
144        path: String,
145        #[source]
146        source: IoError,
147    },
148
149    #[error("rule file '{path}' is not valid UTF-8: {source}")]
150    Utf8 {
151        path: String,
152        #[source]
153        source: Utf8Error,
154    },
155}
156
157impl RuleError {
158    fn io(path: &Path, source: IoError) -> Self {
159        Self::Io {
160            path: path.display().to_string(),
161            source,
162        }
163    }
164}
165
166/// Parse a single YAML string into a Rule, validating required fields.
167pub fn parse_rule(yaml: &str) -> Result<Rule, RuleError> {
168    let rule: Rule = serde_yaml::from_str(yaml)?;
169    if rule.rule.is_null() {
170        return Err(RuleError::EmptyRule { id: rule.id });
171    }
172    Ok(rule)
173}
174
175/// Parse a rule and fill in its category from the ruleset-relative path when
176/// the YAML omits it.
177fn parse_rule_at(yaml: &str, relative_path: &Path) -> Result<Rule, RuleError> {
178    let mut rule = parse_rule(yaml)?;
179    if rule.category.is_none() {
180        rule.category = Category::from_rule_path(relative_path);
181    }
182    Ok(rule)
183}
184
185fn is_rule_file(path: &Path) -> bool {
186    matches!(
187        path.extension().and_then(|e| e.to_str()),
188        Some("yml" | "yaml")
189    )
190}
191
192/// Load all builtin rules embedded via rust-embed.
193pub fn load_builtin_rules() -> Result<Vec<Rule>, RuleError> {
194    BuiltinRules::iter()
195        .filter(|path| is_rule_file(Path::new(path.as_ref())))
196        .filter_map(|path| BuiltinRules::get(&path).map(|file| (path, file)))
197        .map(|(path, file)| {
198            let yaml = from_utf8(&file.data).map_err(|e| RuleError::Utf8 {
199                path: path.to_string(),
200                source: e,
201            })?;
202            parse_rule_at(yaml, Path::new(path.as_ref()))
203        })
204        .collect()
205}
206
207/// Load rules from custom directories on the filesystem. Missing directories
208/// are skipped; subdirectories are searched recursively.
209pub fn load_custom_rules(dirs: &[PathBuf]) -> Result<Vec<Rule>, RuleError> {
210    let mut rules = Vec::new();
211    for dir in dirs.iter().filter(|dir| dir.is_dir()) {
212        // Custom rule directories are plain file trees: gitignore and
213        // hidden-file filtering would silently drop rules.
214        for entry in WalkBuilder::new(dir).standard_filters(false).build() {
215            let entry = entry.map_err(|e| RuleError::io(dir, IoError::other(e)))?;
216            let path = entry.path();
217            let is_file = entry.file_type().is_some_and(|t| t.is_file());
218            if !is_file || !is_rule_file(path) {
219                continue;
220            }
221            let yaml = read_to_string(path).map_err(|e| RuleError::io(path, e))?;
222            let relative = path.strip_prefix(dir).unwrap_or(path);
223            rules.push(parse_rule_at(&yaml, relative)?);
224        }
225    }
226    Ok(rules)
227}
228
229/// Whether a builtin rule takes part in a scan under `config`.
230///
231/// A rule listed in `rules.enable` is always active. Otherwise it must be
232/// enabled by default, belong to an active ruleset, and not be listed in
233/// `rules.disable`.
234pub fn is_rule_active(rule: &Rule, config: &crate::config::Config) -> bool {
235    let listed = |ids: &[String]| ids.iter().any(|id| id == rule.id.as_str());
236    if listed(&config.rules.enable) {
237        return true;
238    }
239    let ruleset_on = match rule.category.as_ref().unwrap_or(&Category::Correctness) {
240        Category::Slop => config.rulesets.slop,
241        Category::Security => config.rulesets.security,
242        Category::Correctness => config.rulesets.correctness,
243    };
244    ruleset_on && rule.enabled && !listed(&config.rules.disable)
245}
246
247/// Load all effective rules based on config: builtin (filtered by rulesets and
248/// the enable/disable lists) plus custom rules from configured directories.
249pub fn load_effective_rules(config: &crate::config::Config) -> Result<Vec<Rule>, RuleError> {
250    let mut rules: Vec<Rule> = load_builtin_rules()?
251        .into_iter()
252        .filter(|rule| is_rule_active(rule, config))
253        .collect();
254
255    let custom = load_custom_rules(&config.rules.custom_dirs)?;
256    rules.extend(custom);
257    validate_unique_ids(&rules)?;
258    Ok(rules)
259}
260
261/// Validate that all rule ids are unique.
262pub fn validate_unique_ids(rules: &[Rule]) -> Result<(), RuleError> {
263    let mut seen = HashSet::new();
264    for rule in rules {
265        if !seen.insert(&rule.id) {
266            return Err(RuleError::DuplicateId {
267                id: rule.id.clone(),
268            });
269        }
270    }
271    Ok(())
272}
273
274#[cfg(test)]
275mod tests {
276    use std::fs::{create_dir, write};
277
278    use tempfile::tempdir;
279
280    use super::*;
281
282    #[test]
283    fn parse_valid_rule_all_fields() {
284        let yaml = r#"
285id: test-rule
286language: rust
287severity: error
288message: "Test message"
289note: "Test note"
290category: security
291fix: "Use X instead"
292rule:
293  kind: call_expression
294  regex: '\.unwrap\(\)\s*$'
295files:
296  - "**/src/**/*.rs"
297ignores:
298  - "**/tests/**"
299skip_test_code: true
300tests:
301  should_match:
302    - "let x = foo().unwrap();"
303  should_not_match:
304    - "let x = foo()?;"
305"#;
306        let rule = parse_rule(yaml).unwrap();
307        assert!(rule.skip_test_code);
308        assert_eq!(rule.id, RuleId::from("test-rule"));
309        assert_eq!(rule.language, Language::Rust);
310        assert_eq!(rule.severity, Severity::Error);
311        assert_eq!(rule.message, "Test message");
312        assert_eq!(rule.note.as_deref(), Some("Test note"));
313        assert_eq!(rule.category, Some(Category::Security));
314        assert_eq!(rule.fix.as_deref(), Some("Use X instead"));
315        assert!(!rule.rule.is_null());
316        assert_eq!(rule.files.as_ref().unwrap().len(), 1);
317        assert_eq!(rule.ignores.as_ref().unwrap().len(), 1);
318        let tests = rule.tests.as_ref().unwrap();
319        assert_eq!(tests.should_match.len(), 1);
320        assert_eq!(tests.should_not_match.len(), 1);
321    }
322
323    #[test]
324    fn parse_minimal_rule() {
325        let yaml = r#"
326id: minimal-rule
327language: rust
328severity: warning
329message: "Minimal"
330rule:
331  pattern: $X.unwrap()
332"#;
333        let rule = parse_rule(yaml).unwrap();
334        assert_eq!(rule.id, RuleId::from("minimal-rule"));
335        assert_eq!(rule.severity, Severity::Warning);
336        assert!(rule.note.is_none());
337        assert!(rule.category.is_none());
338        assert!(rule.fix.is_none());
339        assert!(rule.files.is_none());
340        assert!(rule.ignores.is_none());
341        assert!(!rule.skip_test_code);
342        assert!(rule.tests.is_none());
343        assert!(rule.enabled);
344    }
345
346    #[test]
347    fn rule_activation_precedence() {
348        let opt_in = parse_rule(
349            r#"
350id: opt-in
351language: rust
352severity: warning
353category: slop
354enabled: false
355message: "Opt-in"
356rule:
357  pattern: $X.unwrap()
358"#,
359        )
360        .unwrap();
361        let mut config = crate::config::Config::default();
362
363        assert!(!is_rule_active(&opt_in, &config), "enabled: false is off");
364
365        config.rules.enable.push("opt-in".to_string());
366        assert!(is_rule_active(&opt_in, &config), "enable list turns it on");
367
368        config.rules.disable.push("opt-in".to_string());
369        assert!(is_rule_active(&opt_in, &config), "enable wins over disable");
370
371        config.rulesets.slop = false;
372        assert!(is_rule_active(&opt_in, &config), "enable wins over ruleset");
373
374        config.rules.enable.clear();
375        config.rules.disable.clear();
376        config.rulesets.slop = true;
377        let mut default_on = opt_in.clone();
378        default_on.enabled = true;
379        assert!(is_rule_active(&default_on, &config));
380
381        config.rules.disable.push("opt-in".to_string());
382        assert!(!is_rule_active(&default_on, &config), "disable list");
383
384        config.rules.disable.clear();
385        config.rulesets.slop = false;
386        assert!(!is_rule_active(&default_on, &config), "ruleset off");
387    }
388
389    #[test]
390    fn reject_missing_id() {
391        let yaml = r#"
392language: rust
393severity: error
394message: "No id"
395rule:
396  pattern: $X
397"#;
398        let err = parse_rule(yaml).unwrap_err();
399        let msg = err.to_string();
400        assert!(
401            msg.contains("missing field"),
402            "expected missing field error, got: {msg}"
403        );
404    }
405
406    #[test]
407    fn reject_unsupported_language() {
408        let yaml = r#"
409id: bad-lang
410language: python
411severity: error
412message: "Bad lang"
413rule:
414  pattern: $X
415"#;
416        let err = parse_rule(yaml).unwrap_err();
417        assert!(matches!(err, RuleError::Parse(_)));
418        let msg = err.to_string();
419        assert!(
420            msg.contains("unknown variant"),
421            "expected unknown variant error, got: {msg}"
422        );
423    }
424
425    #[test]
426    fn reject_empty_rule() {
427        let yaml = r#"
428id: empty-rule
429language: rust
430severity: error
431message: "Empty rule"
432rule:
433"#;
434        let err = parse_rule(yaml).unwrap_err();
435        let msg = err.to_string();
436        assert!(
437            msg.contains("must not be empty"),
438            "expected empty rule error, got: {msg}"
439        );
440    }
441
442    #[test]
443    fn reject_malformed_yaml() {
444        let yaml = "this is: [not: valid: yaml: {{{";
445        let err = parse_rule(yaml).unwrap_err();
446        assert!(matches!(err, RuleError::Parse(_)));
447    }
448
449    #[test]
450    fn load_all_builtin_rules() {
451        let rules = load_builtin_rules().unwrap();
452        assert_eq!(
453            rules.len(),
454            34,
455            "expected 34 builtin rules, got {}",
456            rules.len()
457        );
458
459        let slop_count = rules
460            .iter()
461            .filter(|r| r.category == Some(Category::Slop))
462            .count();
463        let security_count = rules
464            .iter()
465            .filter(|r| r.category == Some(Category::Security))
466            .count();
467        let correctness_count = rules
468            .iter()
469            .filter(|r| r.category == Some(Category::Correctness))
470            .count();
471        assert_eq!(slop_count, 9, "expected 9 slop rules");
472        assert_eq!(security_count, 8, "expected 8 security rules");
473        assert_eq!(correctness_count, 17, "expected 17 correctness rules");
474
475        assert!(rules
476            .iter()
477            .any(|r| r.id == RuleId::from("no-unwrap-in-prod")));
478        assert!(rules
479            .iter()
480            .any(|r| r.id == RuleId::from("no-debug-on-secrets")));
481        assert!(rules.iter().any(|r| r.id == RuleId::from("no-slop-words")));
482
483        validate_unique_ids(&rules).unwrap();
484    }
485
486    #[test]
487    fn load_custom_rules_from_dir() {
488        let dir = tempdir().unwrap();
489        let rule_yaml = r#"
490id: custom-rule
491language: rust
492severity: warning
493message: "Custom rule"
494rule:
495  pattern: $X.clone()
496"#;
497        write(dir.path().join("custom.yml"), rule_yaml).unwrap();
498
499        let rules = load_custom_rules(&[dir.path().to_path_buf()]).unwrap();
500        assert_eq!(rules.len(), 1);
501        assert_eq!(rules[0].id, RuleId::from("custom-rule"));
502    }
503
504    #[test]
505    fn reject_duplicate_ids() {
506        let rule1 = parse_rule(
507            r#"
508id: same-id
509language: rust
510severity: error
511message: "First"
512rule:
513  pattern: $X
514"#,
515        )
516        .unwrap();
517        let rule2 = parse_rule(
518            r#"
519id: same-id
520language: rust
521severity: warning
522message: "Second"
523rule:
524  pattern: $Y
525"#,
526        )
527        .unwrap();
528        let err = validate_unique_ids(&[rule1, rule2]).unwrap_err();
529        let msg = err.to_string();
530        assert!(
531            msg.contains("duplicate rule id"),
532            "expected duplicate id error, got: {msg}"
533        );
534        assert!(
535            msg.contains("same-id"),
536            "expected same-id in error, got: {msg}"
537        );
538    }
539
540    #[test]
541    fn category_from_rule_path() {
542        let category = |p: &str| Category::from_rule_path(Path::new(p));
543        assert_eq!(category("slop/no-slop-words.yml"), Some(Category::Slop));
544        assert_eq!(category("security/no-debug.yml"), Some(Category::Security));
545        assert_eq!(
546            category("correctness/no-unwrap.yml"),
547            Some(Category::Correctness)
548        );
549        assert_eq!(category("unknown/something.yml"), None);
550        assert_eq!(category("rule.yml"), None);
551    }
552
553    #[test]
554    fn all_builtin_rules_valid_messages() {
555        for path in BuiltinRules::iter() {
556            if !is_rule_file(Path::new(path.as_ref())) {
557                continue;
558            }
559            let file = BuiltinRules::get(&path).unwrap();
560            let yaml = from_utf8(&file.data).unwrap();
561            let rule: Rule = serde_yaml::from_str(yaml).unwrap();
562            assert!(
563                !rule.message.contains('\u{2014}'),
564                "rule '{}' message contains em dash: {}",
565                rule.id,
566                rule.message
567            );
568            assert!(
569                !rule.message.contains('\u{2013}'),
570                "rule '{}' message contains en dash: {}",
571                rule.id,
572                rule.message
573            );
574            assert!(
575                rule.message.is_ascii() || rule.message.chars().all(|c| c.is_ascii() || c == '\''),
576                "rule '{}' message contains non-ASCII characters: {}",
577                rule.id,
578                rule.message
579            );
580        }
581    }
582
583    #[test]
584    fn all_builtin_rules_have_tests() {
585        for path in BuiltinRules::iter() {
586            if !is_rule_file(Path::new(path.as_ref())) {
587                continue;
588            }
589            let file = BuiltinRules::get(&path).unwrap();
590            let yaml = from_utf8(&file.data).unwrap();
591            let rule: Rule = serde_yaml::from_str(yaml).unwrap();
592            let tests = rule.tests.as_ref().unwrap_or_else(|| {
593                panic!("rule '{}' (at {path}) is missing `tests` block", rule.id)
594            });
595            assert!(
596                tests.should_match.len() >= 2,
597                "rule '{}' (at {path}) needs >= 2 should_match, got {}",
598                rule.id,
599                tests.should_match.len()
600            );
601            assert!(
602                tests.should_not_match.len() >= 2,
603                "rule '{}' (at {path}) needs >= 2 should_not_match, got {}",
604                rule.id,
605                tests.should_not_match.len()
606            );
607        }
608    }
609
610    #[test]
611    fn all_builtin_rules_have_explicit_category() {
612        for path in BuiltinRules::iter() {
613            if !is_rule_file(Path::new(path.as_ref())) {
614                continue;
615            }
616            let file = BuiltinRules::get(&path).unwrap();
617            let yaml = from_utf8(&file.data).unwrap();
618            let rule: Rule = serde_yaml::from_str(yaml).unwrap();
619            assert!(
620                rule.category.is_some(),
621                "rule '{}' (at {path}) is missing an explicit `category` field",
622                rule.id
623            );
624        }
625    }
626
627    #[test]
628    fn custom_rules_category_from_subdir() {
629        let dir = tempdir().unwrap();
630        let security_dir = dir.path().join("security");
631        create_dir(&security_dir).unwrap();
632        let rule_yaml = r#"
633id: custom-sec
634language: rust
635severity: error
636message: "Custom security"
637rule:
638  pattern: $X
639"#;
640        write(security_dir.join("rule.yml"), rule_yaml).unwrap();
641
642        let rules = load_custom_rules(&[dir.path().to_path_buf()]).unwrap();
643        assert_eq!(rules.len(), 1);
644        assert_eq!(rules[0].category, Some(Category::Security));
645    }
646}