Skip to content

Commit 193c355

Browse files
#694 Bandit fails when using importlib with named arguments (#701)
* #694 Bandit fails when using importlib with named arguments * add missing tests * improvement in the tests Co-authored-by: Luke Hinds <[email protected]>
1 parent 1eff509 commit 193c355

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

bandit/core/blacklisting.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,10 @@ def blacklist(context, config):
4747
# argument name as an actual import module name.
4848
# Will produce None if argument is not a literal or identifier
4949
if name in ["importlib.import_module", "importlib.__import__"]:
50-
name = context.call_args[0]
50+
if context.call_args_count > 0:
51+
name = context.call_args[0]
52+
else:
53+
name = context.call_keywords['name']
5154
for check in blacklists[node_type]:
5255
for qn in check['qualnames']:
5356
if name is not None and fnmatch.fnmatch(name, qn):

examples/imports-with-importlib.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,9 @@
77
# Do not crash when target is an expression
88
e = importlib.import_module(MODULE_MAP[key])
99
f = importlib.__import__(MODULE_MAP[key])
10+
11+
# Do not crash when target is a named argument
12+
g = importlib.import_module(name='sys')
13+
h = importlib.__import__(name='subprocess')
14+
i = importlib.import_module(name='subprocess', package='bar.baz')
15+
j = importlib.__import__(name='sys', package='bar.baz')

tests/functional/test_functional.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,8 @@ def test_imports(self):
230230
def test_imports_using_importlib(self):
231231
'''Test for dangerous imports using importlib.'''
232232
expect = {
233-
'SEVERITY': {'UNDEFINED': 0, 'LOW': 2, 'MEDIUM': 0, 'HIGH': 0},
234-
'CONFIDENCE': {'UNDEFINED': 0, 'LOW': 0, 'MEDIUM': 0, 'HIGH': 2}
233+
'SEVERITY': {'UNDEFINED': 0, 'LOW': 4, 'MEDIUM': 0, 'HIGH': 0},
234+
'CONFIDENCE': {'UNDEFINED': 0, 'LOW': 0, 'MEDIUM': 0, 'HIGH': 4}
235235
}
236236
self.check_example('imports-with-importlib.py', expect)
237237

0 commit comments

Comments
 (0)