PyCQA / PyCQA/bandit

f-strings marked with a `# nosec BXXX` show an incorrect warning about no failed tests appears

Open
#1,204 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
8.3k
Forks
836
Avg merge
5d 3h
Merged PRs (30d)
1

Description

Describe the bug

When running bandit against code using f-strings that are marked with # nosec BXXX a warning appears when there should not be one. This happens for both single-line and multi-line f-strings. The behaviour is not present when using blanket nosec or when using template strings.

Works:

table = "my_table"
query = f"SELECT * FROM {table} WHERE True"  # nosec
table = "my_table"
query = (f"SELECT * "
         f"FROM {table} "  # nosec
         f"WHERE True")
table = "my_table"
query = ("SELECT * "
         "FROM {} "  # nosec B608
         "WHERE True".format(table)
         )

Incorrect Warning:

[tester] WARNING nosec encountered (B608), but no failed test on line 3

table = "my_table"
query = (f"SELECT * "
         f"FROM {table} "  # nosec B608
         f"WHERE True")

[tester] WARNING nosec encountered (B608), but no failed test on line 2

table = "my_table"
query = f"SELECT * FROM {table} WHERE True"  # nosec B608
Reproduction steps
1.  Create a file foo.py with the following code:

table = "my_table"
query = f"SELECT * FROM {table} WHERE True"  # nosec B608

2. Run `bandit foo.py`
3. Notice that in the run info there is a warning:
   `[tester]        WARNING nosec encountered (B608), but no failed test on line 2`
Expected behavior

No warning appears when the a nosec correctly applies to a failed test.

Bandit version

1.7.10 (Default)

Python version

3.12

Additional context

This seems related to #942, #1003, #1041 and #1092

While playing around I applied the patch from #1004 but that did not resolve this issue.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the provided foo.py example and run bandit foo.py, then compare the single-line and multi-line f-string cases with the working blanket nosec and template-string examples. Review related issues #942, #1003, #1041, and #1092; done means correctly applied nosec B608 suppresses the warning without regressing the other cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
security
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.