Skip to content

Conversation

gouriphadnis0301
Copy link

Description:
This pull request addresses Issue #1204 in Bandit, where # nosec BXXX comments were not correctly recognized on f-strings or multi-line statements.

Problem:

  • The existing get_nosec() function in utils.py only checked line numbers (context["linerange"]) to determine if a # nosec comment was present.

  • This approach caused false positives: Bandit incorrectly raised warnings for code lines that had # nosec when the comment was part of a multi-line f-string or expression.

  • Specific rule IDs like B607, B602 in # nosec BXXX comments were not properly parsed.

Fix:

  1. Replaced the old get_nosec() function with a new implementation that:
  2. Iterates over all lines in context["linerange"] to detect # nosec.
  3. Properly handles multi-line statements and f-strings.
  4. Parses specific rule IDs (e.g., B607, B602) and returns them as a list.
  5. Returns True for a general # nosec without rule IDs.
  6. Returns None if no # nosec comment is found.

Impact:

  • Bandit will now ignore the correct lines with # nosec for both f-strings and multi-line expressions.
  • Reduces false positive security warnings and improves accuracy.

Testing:

  • Verified that lines with # nosec and rule IDs (# nosec B607) are now correctly ignored.
  • Checked multi-line f-strings and concatenated expressions — Bandit no longer reports unnecessary warnings.
  • Ran existing Bandit tests:
    pytest -k nosec
  • All tests pass successfully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant