From ecd53cc4478f1a67ce41875110b948bc6ff46619 Mon Sep 17 00:00:00 2001 From: Kamil Frydel Date: Mon, 27 Mar 2023 18:18:10 +0200 Subject: [PATCH] Fix nosec for nested dicts Before this commit nosec was searched from the begnning of the expression's context, which may be broader than the exact piece of code that a developer wants to skip. This caused, that for the below example: 1. example = { 2. 'S3_CONFIG_PARAMS': dict( # nosec B106 3. ... 4. ), 5. 'LOCALFS_BASEDIR': '/var/tmp/herp', # nosec B108 6. } for line 5, nosec from line 2 was returned. Thus `nosec B108` was ignored. This commit changes the algorithm that search for nosec for an expression and nosec from the exact line of the expression is preferred. Resolves: #1003 --- bandit/core/utils.py | 4 ++-- examples/nosec.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/bandit/core/utils.py b/bandit/core/utils.py index a7e1c2b60..46345f45d 100644 --- a/bandit/core/utils.py +++ b/bandit/core/utils.py @@ -373,8 +373,8 @@ def check_ast_node(name): def get_nosec(nosec_lines, context): - for lineno in context["linerange"]: - nosec = nosec_lines.get(lineno, None) + for lineno in [context["lineno"], *context["linerange"]]: + nosec = nosec_lines.get(lineno) if nosec is not None: return nosec return None diff --git a/examples/nosec.py b/examples/nosec.py index c69979114..d84751aa8 100644 --- a/examples/nosec.py +++ b/examples/nosec.py @@ -13,3 +13,14 @@ subprocess.Popen('/bin/ls *', shell=True) # type: ... # noqa: E501 ; pylint: disable=line-too-long # nosec subprocess.Popen('#nosec', shell=True) # nosec B607, B101 subprocess.Popen('#nosec', shell=True) # nosec B602, subprocess_popen_with_shell_equals_true +# check that nosec in nested dict does not cause "higher" annotations to be ignored +# reproduction of https://github.com/PyCQA/bandit/issues/1003 +example = { + 'S3_CONFIG_PARAMS': dict( # nosec B106 + aws_access_key_id='key_goes_here', + aws_secret_access_key='secret_goes_here', + endpoint_url='s3.amazonaws.com', + ), + 'LOCALFS_BASEDIR': '/var/tmp/herp', # nosec B108 + 'ALPINE_APORTS_DIR': '/tmp/derp', # nosec B108 +}