Skip to main content

diff_risk_core/detectors/
auth.rs

1//! Auth & permission-gate detector (Risk Matrix category D).
2//!
3//! Strategy: keyword-weighted scan over added and removed lines. A line
4//! matching a *strong* auth keyword (`authorize`, `authenticate`, `jwt`,
5//! `permission`, `role`, `bearer`, `session`) in a Rust-y context
6//! (identifier, string literal, attribute, or function name) is flagged
7//! as a `Critical` finding. A line matching a *weak* keyword (`token`,
8//! `admin`, `login`, `logout`) is flagged as `High`.
9//!
10//! Comments and CSS-like contexts are skipped. Non-Rust files still match
11//! — LLMs are just as dangerous editing middleware in TOML configs.
12
13use regex::Regex;
14use std::sync::OnceLock;
15
16use crate::detectors::Detector;
17use crate::diff::Diff;
18use crate::report::{Finding, RiskCategory, Severity};
19
20/// Keyword-weighted auth-gate detector.
21#[derive(Debug, Default, Clone, Copy)]
22pub struct AuthDetector;
23
24impl AuthDetector {
25    /// Construct a new detector.
26    #[must_use]
27    pub fn new() -> Self {
28        Self
29    }
30}
31
32// Identifier-boundary pattern: matches at the start/end of the line OR when the
33// neighbouring character is a non-alphanumeric. Crucially this treats `_` as a
34// boundary, so `skip_jwt_check` and `check_permission` still match, unlike the
35// default `\b` (which considers `_` a word character).
36const ID_BOUNDARY_PRE: &str = r"(?:^|[^a-z0-9])";
37const ID_BOUNDARY_POST: &str = r"(?:[^a-z0-9]|$)";
38
39fn strong_re() -> &'static Regex {
40    static RE: OnceLock<Regex> = OnceLock::new();
41    RE.get_or_init(|| {
42        let pat = format!(
43            r"(?ix){ID_BOUNDARY_PRE}(
44              authorize | authorise | authorization | authorisation |
45              authenticate | authentication |
46              jwt | oauth |
47              permission | permissions |
48              bearer |
49              role | roles
50            ){ID_BOUNDARY_POST}"
51        );
52        Regex::new(&pat).expect("strong auth regex")
53    })
54}
55
56fn weak_re() -> &'static Regex {
57    static RE: OnceLock<Regex> = OnceLock::new();
58    RE.get_or_init(|| {
59        let pat = format!(
60            r"(?ix){ID_BOUNDARY_PRE}(
61              token | tokens |
62              admin |
63              login | logout |
64              session | sessions |
65              credentials?
66            ){ID_BOUNDARY_POST}"
67        );
68        Regex::new(&pat).expect("weak auth regex")
69    })
70}
71
72// Lines that are pure comments or doc strings — deprioritize but still scan so
73// a commented-out `authorize()` call doesn't register as Critical.
74fn is_comment_line(line: &str) -> bool {
75    let trimmed = line.trim_start();
76    trimmed.starts_with("//") || trimmed.starts_with("///") || trimmed.starts_with("*")
77}
78
79impl Detector for AuthDetector {
80    fn name(&self) -> &'static str {
81        "auth-gate"
82    }
83
84    fn detect(&self, diff: &Diff) -> Vec<Finding> {
85        let strong = strong_re();
86        let weak = weak_re();
87        let mut out = Vec::new();
88
89        // Added lines — most likely vector for an LLM to introduce a bypass.
90        for (path, added) in diff.added_lines() {
91            if is_comment_line(&added.text) {
92                continue;
93            }
94            let severity = classify(&added.text, strong, weak);
95            if let Some(sev) = severity {
96                out.push(Finding {
97                    category: RiskCategory::AuthGate,
98                    severity: sev,
99                    file: path.to_string(),
100                    line: Some(added.line),
101                    message: format!(
102                        "auth-related change on added line: {}",
103                        truncate(&added.text, 120)
104                    ),
105                });
106            }
107        }
108
109        // Removed lines — deletion of a check is as dangerous as adding one.
110        for (path, removed) in diff.removed_lines() {
111            if is_comment_line(removed) {
112                continue;
113            }
114            let severity = classify(removed, strong, weak);
115            if let Some(sev) = severity {
116                out.push(Finding {
117                    category: RiskCategory::AuthGate,
118                    severity: sev,
119                    file: path.to_string(),
120                    line: None,
121                    message: format!("auth-related line removed: {}", truncate(removed, 120)),
122                });
123            }
124        }
125
126        out
127    }
128}
129
130fn classify(line: &str, strong: &Regex, weak: &Regex) -> Option<Severity> {
131    if strong.is_match(line) {
132        Some(Severity::Critical)
133    } else if weak.is_match(line) {
134        Some(Severity::High)
135    } else {
136        None
137    }
138}
139
140fn truncate(s: &str, max: usize) -> String {
141    let trimmed = s.trim();
142    if trimmed.chars().count() <= max {
143        trimmed.to_string()
144    } else {
145        let cut: String = trimmed.chars().take(max).collect();
146        format!("{cut}…")
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use crate::diff::parse_unified_diff;
154
155    fn run(diff_text: &str) -> Vec<Finding> {
156        let diff = parse_unified_diff(diff_text).expect("valid diff");
157        AuthDetector::new().detect(&diff)
158    }
159
160    #[test]
161    fn flags_added_authorize_call_as_critical() {
162        let diff = "\
163--- a/src/auth.rs
164+++ b/src/auth.rs
165@@ -10,3 +10,4 @@
166 fn handler() {
167-    authorize(&req)?;
168+    // TODO: re-enable later
169 }
170";
171        let findings = run(diff);
172        assert!(
173            findings.iter().any(|f| f.severity == Severity::Critical),
174            "removed authorize() must fire critical, got {findings:?}"
175        );
176    }
177
178    #[test]
179    fn flags_added_jwt_change_as_critical() {
180        let diff = "\
181--- a/src/mw.rs
182+++ b/src/mw.rs
183@@ -1,3 +1,4 @@
184 fn verify() {}
185+fn skip_jwt_check() { true }
186";
187        let findings = run(diff);
188        assert_eq!(findings.len(), 1);
189        assert_eq!(findings[0].severity, Severity::Critical);
190        assert_eq!(findings[0].category, RiskCategory::AuthGate);
191        assert_eq!(findings[0].line, Some(2));
192    }
193
194    #[test]
195    fn bare_token_word_is_high_not_critical() {
196        // No strong keyword (no "bearer", "jwt", etc.) — just "token".
197        let diff = "\
198--- a/src/client.rs
199+++ b/src/client.rs
200@@ -1,1 +1,2 @@
201 fn x() {}
202+    let token = fetch();
203";
204        let findings = run(diff);
205        assert_eq!(findings.len(), 1);
206        assert_eq!(findings[0].severity, Severity::High);
207    }
208
209    #[test]
210    fn admin_alone_is_high() {
211        let diff = "\
212--- a/src/users.rs
213+++ b/src/users.rs
214@@ -1,1 +1,2 @@
215 fn x() {}
216+    user.admin = true;
217";
218        let findings = run(diff);
219        assert_eq!(findings.len(), 1);
220        assert_eq!(findings[0].severity, Severity::High);
221    }
222
223    #[test]
224    fn comment_only_lines_are_ignored() {
225        let diff = "\
226--- a/src/notes.rs
227+++ b/src/notes.rs
228@@ -1,1 +1,2 @@
229 fn x() {}
230+    // authorize the user later
231";
232        assert!(run(diff).is_empty());
233    }
234
235    #[test]
236    fn non_auth_diff_produces_nothing() {
237        let diff = "\
238--- a/src/math.rs
239+++ b/src/math.rs
240@@ -1,1 +1,2 @@
241 fn x() {}
242+    let sum = a + b;
243";
244        assert!(run(diff).is_empty());
245    }
246
247    #[test]
248    fn removed_permission_check_is_critical() {
249        let diff = "\
250--- a/src/mw.rs
251+++ b/src/mw.rs
252@@ -5,4 +5,3 @@
253 fn guard() {
254-    check_permission(user, \"admin\")?;
255 }
256";
257        let findings = run(diff);
258        assert!(findings.iter().any(|f| f.severity == Severity::Critical));
259    }
260}