Skip to content

Commit b2d856f

Browse files
authored
[flake8-bandit] Allow suspicious imports in TYPE_CHECKING blocks (S401-S415) (#23441)
Fix false positives for S408/S409 when `xml.dom.minidom` or `xml.dom.pulldom` are imported inside `if TYPE_CHECKING:` blocks. Imports inside TYPE_CHECKING are not executed at runtime, so they should not trigger these Bandit-based security rules. Adds a dedicated fixture and snapshot test for the TYPE_CHECKING case. Refs #14901
1 parent 8710af0 commit b2d856f

4 files changed

Lines changed: 15 additions & 0 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from typing import TYPE_CHECKING
2+
3+
if TYPE_CHECKING:
4+
from xml.dom.minidom import Element

crates/ruff_linter/src/rules/flake8_bandit/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ mod tests {
6767
#[test_case(Rule::SuspiciousXmlExpatImport, Path::new("S407.pyi"))]
6868
#[test_case(Rule::SuspiciousXmlMinidomImport, Path::new("S408.py"))]
6969
#[test_case(Rule::SuspiciousXmlMinidomImport, Path::new("S408.pyi"))]
70+
#[test_case(Rule::SuspiciousXmlMinidomImport, Path::new("S408_type_checking.py"))]
7071
#[test_case(Rule::SuspiciousXmlPulldomImport, Path::new("S409.py"))]
7172
#[test_case(Rule::SuspiciousXmlPulldomImport, Path::new("S409.pyi"))]
7273
#[test_case(Rule::SuspiciousLxmlImport, Path::new("S410.py"))]

crates/ruff_linter/src/rules/flake8_bandit/rules/suspicious_imports.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,11 @@ pub(crate) fn suspicious_imports(checker: &Checker, stmt: &Stmt) {
370370
return;
371371
}
372372

373+
// Imports inside `if TYPE_CHECKING:` are not executed at runtime.
374+
if checker.semantic().in_type_checking_block() {
375+
return;
376+
}
377+
373378
match stmt {
374379
Stmt::Import(ast::StmtImport { names, .. }) => {
375380
for name in names {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
source: crates/ruff_linter/src/rules/flake8_bandit/mod.rs
3+
assertion_line: 98
4+
---
5+

0 commit comments

Comments
 (0)