bandit icon indicating copy to clipboard operation
bandit copied to clipboard

Add a configuration option to prohibit `# nosec` without specific error codes

Open mkniewallner opened this issue 3 years ago • 1 comments

Is your feature request related to a problem? Please describe. Now that bandit supports a way to only ignore specific error codes when using # nosec (https://github.com/PyCQA/bandit/pull/597), it could be nice to have a configuration option to disable usages of # nosec without specific error codes from a codebase entirely, in order to ensure that specific error codes are always used.

Today, it is not possible to enforce that, making it hard to make all developers respect this rule on large codebases.

Describe the solution you'd like mypy recently implemented that in https://github.com/python/mypy/pull/11633 (documentation is here), to give you an idea of how this could look like.

The feature could be implemented by adding a new boolean option disallow-broad-nosec (or any better name) that would defaults to False.

If set to True, then bandit would look for any # nosec comment that doesn't specify any error code. So:

  • # nosec would throw an error
  • # nosec: B101 or # nosec: B101 B102 would not

The error itself could re-use the same template as already exists for other tests. Though as the error is kind of a "meta-error", this could go under a specific range of errors ranging from B001 to B099, which could also be helpful if other "meta-errors" are added in the future (for instance, another error code to throw if a specific error code is used for # nosec, but is in the end not needed, to warn the user about it).

So this is what it could like, for instance:

Test results:
>> Issue: [B001:nosec_without_error_code] # nosec comment used without specifying error code
   Severity: High   Confidence: High
   Location: foo/bar.py:1:1
   More Info: https://bandit.readthedocs.io/en/X.X.X/plugins/b001_nosec_without_error_code.html

Describe alternatives you've considered Instead of re-using existing template for error codes that are directly related to security issues, we could also have a dedicated template, to clearly separate "meta" errors like those and security ones, though a too broad # nosec comment could also be considered a security issue, depending on how we see it.

Additional context If you feel like this feature could be useful, I'd be happy to try working on an implementation (though we would need to decide early or after a first draft if we re-use the existing error template, or handle the error in a different way).

Love this idea? Give it a 👍. We prioritize fulfilling features with the most 👍.

mkniewallner avatar Apr 24 '22 17:04 mkniewallner

Taking this a step further, I'd also like to see lines that are annotated with # nosec BXXX to be reported if the specified error is not raised.

cleder avatar Jul 14 '23 12:07 cleder