[flake8-bandit/S506] Dont report violation when SafeLoader is imported from yaml.loader (#9299)

## Summary

Hey there 👋 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.
This commit is contained in:
Mikael Arguedas
2023-12-28 15:30:46 +01:00
committed by GitHub
parent 87086195c8
commit edfad461a8
2 changed files with 11 additions and 2 deletions

View File

@@ -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)

View File

@@ -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 {