Skip to main content

react_auditor/rules/security/
no_insecure_protocol.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 NoInsecureProtocol;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-insecure-protocol",
11    default_severity: Severity::Warning,
12    category: "security",
13    description: "Avoid `http://` URLs, use `https://`",
14};
15
16impl Rule for NoInsecureProtocol {
17    fn meta(&self) -> &RuleMeta {
18        &RULE_META
19    }
20
21    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22        let mut collector = InsecureProtocolCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct InsecureProtocolCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> InsecureProtocolCollector<'a> {
37    fn add_finding(&mut self, start: usize, msg: String) {
38        let line = self.source[..start].lines().count().max(1);
39        let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
40        self.findings.push(RuleFinding {
41            line,
42            column: col + 1,
43            message: msg,
44        });
45    }
46}
47
48impl<'a> Visit<'a> for InsecureProtocolCollector<'a> {
49    fn visit_string_literal(&mut self, s: &oxc_ast::ast::StringLiteral) {
50        let val = s.value.as_str();
51        if val.starts_with("http://") {
52            self.add_finding(
53                s.span.start as usize,
54                "Use `https://` instead of `http://` in URL".to_string(),
55            );
56        }
57    }
58
59    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
60        for attr_item in &el.attributes {
61            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item
62                && let Some(val) = &attr.value
63                && let oxc_ast::ast::JSXAttributeValue::StringLiteral(s) = val
64                && s.value.as_str().starts_with("http://")
65            {
66                self.add_finding(
67                    attr.span.start as usize,
68                    "Use `https://` instead of `http://` in JSX attribute".to_string(),
69                );
70            }
71        }
72    }
73}