Skip to main content

react_auditor/rules/security/
no_hardcoded_secrets.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoHardcodedSecrets;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-hardcoded-secrets",
11    default_severity: Severity::Error,
12    category: "security",
13    description: "Flag potential API keys, tokens, passwords",
14};
15
16const SUSPICIOUS_NAMES: &[&str] = &[
17    "api_key",
18    "apiKey",
19    "apikey",
20    "api_secret",
21    "apiSecret",
22    "password",
23    "passwd",
24    "secret",
25    "token",
26    "auth_token",
27    "access_token",
28    "private_key",
29    "privateKey",
30];
31
32const SUSPICIOUS_PATTERNS: &[&str] = &[
33    "sk_live_", "sk_test_", "pk_live_", "pk_test_", "ghp_", "gho_", "ghu_", "ghs_", "AKIA",
34    "xoxb-", "xoxp-",
35];
36
37impl Rule for NoHardcodedSecrets {
38    fn meta(&self) -> &RuleMeta {
39        &RULE_META
40    }
41
42    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
43        let mut collector = SecretCollector {
44            findings: Vec::new(),
45            source: source_text,
46        };
47        collector.visit_program(program);
48        collector.findings
49    }
50}
51
52struct SecretCollector<'a> {
53    findings: Vec<RuleFinding>,
54    source: &'a str,
55}
56
57impl<'a> Visit<'a> for SecretCollector<'a> {
58    fn visit_variable_declarator(&mut self, decl: &oxc_ast::ast::VariableDeclarator<'a>) {
59        let name = if let oxc_ast::ast::BindingPattern::BindingIdentifier(id) = &decl.id {
60            id.name.as_str()
61        } else {
62            return;
63        };
64
65        let is_suspicious_name = SUSPICIOUS_NAMES.iter().any(|n| name.contains(n));
66
67        if let Some(init) = &decl.init
68            && let oxc_ast::ast::Expression::StringLiteral(s) = init
69        {
70            let val = s.value.as_str();
71
72            if is_suspicious_name
73                && val.len() > 8
74                && val
75                    .chars()
76                    .any(|c| c.is_ascii_punctuation() || c.is_ascii_digit())
77            {
78                let start = decl.span.start as usize;
79                let line = self.source[..start].lines().count().max(1);
80                let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
81                self.findings.push(RuleFinding {
82                    line,
83                    column: col + 1,
84                    message: format!("Potential hardcoded secret in `{name}`"),
85                });
86            } else if SUSPICIOUS_PATTERNS.iter().any(|p| val.starts_with(p)) {
87                let start = decl.span.start as usize;
88                let line = self.source[..start].lines().count().max(1);
89                let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
90                self.findings.push(RuleFinding {
91                    line,
92                    column: col + 1,
93                    message: "Potential hardcoded secret (matches known pattern)".to_string(),
94                });
95            }
96        }
97    }
98}