#nosec directive not applied to entire expression split across multiple lines by Black formatter
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 8.3k
- Forks
- 836
- Avg merge
- 5d 3h
- Merged PRs (30d)
- 1
Description
Describe the bug
Description
I am encountering an issue when using the #nosec directive on an expression that has been split across multiple lines. The problem is present when I use the Bandit tool in combination with the Black code formatter.
Reproduction steps
1. Here is the original code snippet:
import random
import math
test_list_with_a_very_long_name = [1, 6, 3, 10, 21, 31, 50, 49, 20, 100]
a = random.sample(test_list_with_a_very_long_name, math.floor(random.randint() * len(test_list_with_a_very_long_name))) # nosec
print(a)
- Running Bandit on this code doesn't report any security issues due to the
#nosecdirective. - When the Black formatter is applied, it breaks the line into smaller constituents due to its length, as such:
import random
import math
test_list_with_a_very_long_name = [1, 6, 3, 10, 21, 31, 50, 49, 20, 100]
a = random.sample(
test_list_with_a_very_long_name,
math.floor(random.randint() * len(test_list_with_a_very_long_name)),
) # nosec
print(a)
- After applying Black, running Bandit reports an issue with the random function, even though the
#nosecdirective is present.
>> Issue: [B311:blacklist] Standard pseudo-random generators are not suitable for security/cryptographic purposes.
Severity: Low Confidence: High
CWE: CWE-330 (https://cwe.mitre.org/data/definitions/330.html)
More Info: https://bandit.readthedocs.io/en/0.0.0/blacklists/blacklist_calls.html#b311-random
Location: res1x.py:7:15
6 test_list_with_a_very_long_name,
7 math.floor(random.randint() * len(test_list_with_a_very_long_name)),
8 ) # nosec
Expected behavior
The #nosec directive should apply to the whole expression even when it is split into different lines due to the Black formatter's line length considerations.
Bandit version
1.7.5
Python version
3.10.6
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the report with Bandit 1.7.5 on Python 3.10.6 using the before-and-after Black snippets. Then locate the nosec handling and its regression tests; done means a trailing directive suppresses findings for the full formatter-split expression while existing behavior remains covered.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- security, tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100