react_auditor/rules/security/
no_unsafe_iframe.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoUnsafeIframe;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "no-unsafe-iframe",
11 default_severity: Severity::Warning,
12 category: "security",
13 description: "iframes should include `sandbox` and `title` attributes",
14};
15
16impl Rule for NoUnsafeIframe {
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 = UnsafeIframeCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct UnsafeIframeCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for UnsafeIframeCollector<'a> {
37 fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38 let is_iframe = matches!(
39 &el.name,
40 oxc_ast::ast::JSXElementName::Identifier(id) if id.name.as_str() == "iframe"
41 );
42 if !is_iframe {
43 return;
44 }
45
46 let mut has_sandbox = false;
47 let mut has_title = false;
48
49 for attr_item in &el.attributes {
50 if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item
51 && let oxc_ast::ast::JSXAttributeName::Identifier(ident) = &attr.name
52 {
53 match ident.name.as_str() {
54 "sandbox" => has_sandbox = true,
55 "title" => has_title = true,
56 _ => {}
57 }
58 }
59 }
60
61 let start = el.span.start as usize;
62 let line = self.source[..start].lines().count().max(1);
63 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
64
65 if !has_sandbox {
66 self.findings.push(RuleFinding {
67 line,
68 column: col + 1,
69 message: "`<iframe>` is missing a `sandbox` attribute for security isolation"
70 .to_string(),
71 });
72 }
73 if !has_title {
74 self.findings.push(RuleFinding {
75 line,
76 column: col + 1,
77 message: "`<iframe>` is missing a `title` attribute for accessibility".to_string(),
78 });
79 }
80 }
81}