From edfad461a8c1935e1a350ac93e6b63d320925c3f Mon Sep 17 00:00:00 2001 From: Mikael Arguedas Date: Thu, 28 Dec 2023 15:30:46 +0100 Subject: [PATCH] [flake8-bandit/S506] Dont report violation when SafeLoader is imported from yaml.loader (#9299) ## Summary Hey there :wave: thanks for this great project! On python code looking like the following ``` import yaml from yaml.loader import SafeLoader with MY_FILE_PATH.open("r") as my_file: my_data = yaml.load(my_file, Loader=SafeLoader) ``` ruff reports this error: ``` S506 Probable use of unsafe loader `SafeLoader` with `yaml.load`. Allows instantiation of arbitrary objects. Consider `yaml.safe_load`. ``` This PR is an attempt to support SafeLoader being imported for either `yaml` or `yaml.loader` Disclaimer: I am not familiar with Rust so this is likely not the better way of doing it. Interested in hearing how to adapt this PR to provide similar behavior in a better way ## Test Plan The S506.py file was updated accordingly to cover the use cases and test were confirmed to pass with this change. --- .../resources/test/fixtures/flake8_bandit/S506.py | 7 ++++++- .../src/rules/flake8_bandit/rules/unsafe_yaml_load.rs | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/ruff_linter/resources/test/fixtures/flake8_bandit/S506.py b/crates/ruff_linter/resources/test/fixtures/flake8_bandit/S506.py index b332cbe143..9fd87de3e3 100644 --- a/crates/ruff_linter/resources/test/fixtures/flake8_bandit/S506.py +++ b/crates/ruff_linter/resources/test/fixtures/flake8_bandit/S506.py @@ -2,7 +2,7 @@ import json import yaml from yaml import CSafeLoader from yaml import SafeLoader -from yaml import SafeLoader as NewSafeLoader +from yaml.loader import SafeLoader as NewSafeLoader def test_yaml_load(): @@ -29,3 +29,8 @@ yaml.load("{}", yaml.SafeLoader) yaml.load("{}", CSafeLoader) yaml.load("{}", yaml.CSafeLoader) yaml.load("{}", NewSafeLoader) +yaml.load("{}", Loader=SafeLoader) +yaml.load("{}", Loader=yaml.SafeLoader) +yaml.load("{}", Loader=CSafeLoader) +yaml.load("{}", Loader=yaml.CSafeLoader) +yaml.load("{}", Loader=NewSafeLoader) diff --git a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs index 68b8f59647..22b100c1d8 100644 --- a/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs +++ b/crates/ruff_linter/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs @@ -70,7 +70,11 @@ pub(crate) fn unsafe_yaml_load(checker: &mut Checker, call: &ast::ExprCall) { .semantic() .resolve_call_path(loader_arg) .is_some_and(|call_path| { - matches!(call_path.as_slice(), ["yaml", "SafeLoader" | "CSafeLoader"]) + matches!( + call_path.as_slice(), + ["yaml", "SafeLoader" | "CSafeLoader"] + | ["yaml", "loader", "SafeLoader" | "CSafeLoader"] + ) }) { let loader = match loader_arg {