Skip to main content

sentio_core/
rules.rs

1pub mod anchor;
2
3use crate::finding::{Finding, Severity, SourceLocation};
4use crate::syntax::ParsedFile;
5use serde::Serialize;
6use std::collections::HashMap;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
9#[serde(rename_all = "lowercase")]
10pub enum RuleSeverity {
11    Low,
12    Medium,
13    High,
14    Critical,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
18pub struct RuleMetadata {
19    pub id: &'static str,
20    pub title: &'static str,
21    pub severity: RuleSeverity,
22    pub description: &'static str,
23    pub fix_guidance: &'static str,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct RuleMatch {
28    pub rule_id: &'static str,
29    pub severity: RuleSeverity,
30    pub message: String,
31    pub location: SourceLocation,
32    pub help: Option<String>,
33}
34
35pub trait Rule {
36    fn metadata(&self) -> &RuleMetadata;
37    fn match_file(&self, file: &ParsedFile, ctx: &RuleContext<'_>) -> Vec<RuleMatch>;
38}
39
40#[derive(Clone, Copy)]
41pub struct RuleContext<'a> {
42    pub files: &'a [ParsedFile],
43}
44
45pub struct RuleRegistry {
46    rules: Vec<Box<dyn Rule>>,
47}
48
49impl RuleRegistry {
50    pub fn new(rules: Vec<Box<dyn Rule>>) -> Self {
51        Self { rules }
52    }
53
54    pub fn baseline() -> Self {
55        Self::new(vec![
56            Box::new(anchor::missing_signer_check::MissingSignerCheckRule::default()),
57            Box::new(anchor::missing_pda_seeds_bump::MissingPdaSeedsBumpRule::default()),
58            Box::new(anchor::init_if_needed_usage::InitIfNeededUsageRule::default()),
59            Box::new(anchor::missing_realloc_zero::MissingReallocZeroRule::default()),
60            Box::new(anchor::account_info_as_data_account::AccountInfoAsDataAccountRule::default()),
61            Box::new(anchor::account_info_as_cpi_program::AccountInfoAsCpiProgramRule::default()),
62            Box::new(anchor::missing_owner_check::MissingOwnerCheckRule::default()),
63            Box::new(anchor::arbitrary_cpi::ArbitraryCpiRule::default()),
64            Box::new(anchor::missing_cpi_reload::MissingCpiReloadRule::default()),
65        ])
66    }
67
68    pub fn all(&self) -> &[Box<dyn Rule>] {
69        &self.rules
70    }
71
72    pub fn matching_rules(&self, rule_filter: Option<&str>) -> Vec<&dyn Rule> {
73        let filter = rule_filter
74            .map(normalize_rule_id)
75            .filter(|filter| !filter.is_empty());
76
77        self.rules
78            .iter()
79            .map(|rule| rule.as_ref())
80            .filter(|rule| {
81                filter
82                    .as_ref()
83                    .map_or(true, |filter| rule.metadata().id.eq_ignore_ascii_case(filter))
84            })
85            .collect()
86    }
87}
88
89impl Default for RuleRegistry {
90    fn default() -> Self {
91        Self::baseline()
92    }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct SuppressionSet {
97    same_line: HashMap<usize, Vec<String>>,
98    next_line: HashMap<usize, Vec<String>>,
99}
100
101impl SuppressionSet {
102    pub fn empty() -> Self {
103        Self {
104            same_line: HashMap::new(),
105            next_line: HashMap::new(),
106        }
107    }
108
109    pub fn from_source(source: &str) -> Self {
110        let mut same_line: HashMap<usize, Vec<String>> = HashMap::new();
111        let mut next_line: HashMap<usize, Vec<String>> = HashMap::new();
112
113        for (idx, line) in source.lines().enumerate() {
114            let line_no = idx + 1;
115            if let Some(ids) = parse_ignore_directive(line, "sentio-ignore") {
116                same_line.insert(line_no, ids);
117            }
118            if let Some(ids) = parse_ignore_directive(line, "sentio-ignore-next-line") {
119                next_line.insert(line_no + 1, ids);
120            }
121        }
122
123        Self {
124            same_line,
125            next_line,
126        }
127    }
128
129    pub fn is_suppressed(&self, finding: &Finding) -> bool {
130        let rule_id = finding.rule_id.to_uppercase();
131        let line = finding.location.line;
132
133        self.same_line
134            .get(&line)
135            .is_some_and(|ids| ids.iter().any(|id| id == &rule_id))
136            || self
137                .next_line
138                .get(&line)
139                .is_some_and(|ids| ids.iter().any(|id| id == &rule_id))
140    }
141}
142
143pub fn convert_severity(severity: RuleSeverity) -> Severity {
144    match severity {
145        RuleSeverity::Low => Severity::Low,
146        RuleSeverity::Medium => Severity::Medium,
147        RuleSeverity::High => Severity::High,
148        RuleSeverity::Critical => Severity::Critical,
149    }
150}
151
152fn normalize_rule_id(rule_id: &str) -> String {
153    rule_id.trim().to_uppercase()
154}
155
156fn parse_ignore_directive(line: &str, directive: &str) -> Option<Vec<String>> {
157    let lower = line.to_lowercase();
158    let compact = lower.replace(char::is_whitespace, "");
159    let marker = format!("//{directive}");
160    let start = compact.find(&marker)? + marker.len();
161    let ids = compact[start..]
162        .split(|c: char| c == ',' || c.is_whitespace())
163        .map(|s| s.trim().to_uppercase())
164        .filter(|id| is_rule_id(id))
165        .collect::<Vec<_>>();
166
167    if ids.is_empty() {
168        None
169    } else {
170        Some(ids)
171    }
172}
173
174fn is_rule_id(id: &str) -> bool {
175    id.len() == 5
176        && id.starts_with("SW")
177        && id[2..].chars().all(|c| c.is_ascii_digit())
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn parses_same_line_and_next_line_suppressions() {
186        let suppressions = SuppressionSet::from_source(
187            r#"
188            // sentio-ignore SW012, SW018
189            let a = 1;
190            // sentio-ignore-next-line SW012
191            let b = 2;
192            "#,
193        );
194
195        let same_line = Finding {
196            rule_id: "SW012".to_string(),
197            severity: Severity::High,
198            message: String::new(),
199            location: SourceLocation {
200                path: "x.rs".to_string(),
201                line: 2,
202                column: 1,
203            },
204            help: None,
205            suppressed: false,
206        };
207        let next_line = Finding {
208            rule_id: "SW012".to_string(),
209            severity: Severity::High,
210            message: String::new(),
211            location: SourceLocation {
212                path: "x.rs".to_string(),
213                line: 5,
214                column: 1,
215            },
216            help: None,
217            suppressed: false,
218        };
219
220        assert!(suppressions.is_suppressed(&same_line));
221        assert!(suppressions.is_suppressed(&next_line));
222    }
223}