Skip to content

Commit 3d25433

Browse files
authored
Rewrite Bandit Without Tox (#43241)
* initial script * add pip freeze * black * black again * warn instead of error
1 parent e872727 commit 3d25433

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

doc/tool_usage_guide.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ This repo is currently migrating all checks from a slower `tox`-based framework,
2222
|`black`| Runs `black` checks. | `azpysdk black .` |
2323
|`verifytypes`| Runs `verifytypes` checks. | `azpysdk verifytypes .` |
2424
|`ruff`| Runs `ruff` checks. | `azpysdk ruff .` |
25+
|`bandit`| Runs `bandit` checks, which detect common security issues. | `azpysdk bandit .` |
2526
|`verifywhl`| Verifies that the root directory in whl is azure, and verifies manifest so that all directories in source are included in sdist. | `azpysdk verifywhl .` |
2627
|`verifysdist`| Verify directories included in sdist and contents in manifest file. Also ensures that py.typed configuration is correct within the setup.py. | `azpysdk verifysdist .` |
2728
|`verify_keywords`| Verify that the keyword 'azure sdk' is present in the targeted package's keywords. | `azpysdk verify_keywords .` |
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import argparse
2+
import os
3+
import sys
4+
from typing import Optional, List
5+
import subprocess
6+
from subprocess import check_call, CalledProcessError
7+
8+
from .Check import Check
9+
from ci_tools.environment_exclusions import is_check_enabled
10+
from ci_tools.variables import in_ci, set_envvar_defaults
11+
from ci_tools.logging import logger
12+
from ci_tools.functions import install_into_venv, get_pip_command
13+
14+
15+
class bandit(Check):
16+
def __init__(self) -> None:
17+
super().__init__()
18+
19+
def register(
20+
self, subparsers: "argparse._SubParsersAction", parent_parsers: Optional[List[argparse.ArgumentParser]] = None
21+
) -> None:
22+
"""Register the bandit check. The bandit check installs bandit and runs bandit against the target package to find common security issues."""
23+
parents = parent_parsers or []
24+
p = subparsers.add_parser(
25+
"bandit", parents=parents, help="Run the bandit check to find common security issues for a package"
26+
)
27+
p.set_defaults(func=self.run)
28+
29+
def run(self, args: argparse.Namespace) -> int:
30+
"""Run the bandit check command."""
31+
logger.info("Running bandit check...")
32+
33+
set_envvar_defaults()
34+
targeted = self.get_targeted_directories(args)
35+
36+
results: List[int] = []
37+
38+
for parsed in targeted:
39+
package_dir = parsed.folder
40+
package_name = parsed.name
41+
executable, staging_directory = self.get_executable(args.isolate, args.command, sys.executable, package_dir)
42+
logger.info(f"Processing {package_name} for bandit check")
43+
44+
self.install_dev_reqs(executable, args, package_dir)
45+
46+
try:
47+
install_into_venv(executable, ["bandit"], package_dir)
48+
except CalledProcessError as e:
49+
logger.error(f"Failed to install bandit: {e}")
50+
return e.returncode
51+
52+
# debug a pip freeze result
53+
cmd = get_pip_command(executable) + ["freeze"]
54+
freeze_result = subprocess.run(
55+
cmd, cwd=package_dir, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
56+
)
57+
logger.debug(f"Running pip freeze with {cmd}")
58+
logger.debug(freeze_result.stdout)
59+
60+
if in_ci():
61+
if not is_check_enabled(package_dir, "bandit"):
62+
logger.warning(f"Bandit is disabled for {package_name}. Skipping...")
63+
continue
64+
65+
try:
66+
check_call(
67+
[
68+
executable,
69+
"-m",
70+
"bandit",
71+
"-r",
72+
os.path.join(package_dir, "azure"),
73+
"-ll",
74+
]
75+
)
76+
except CalledProcessError as e:
77+
logger.error(f"{package_name} exited with error {e.returncode}")
78+
results.append(e.returncode)
79+
80+
return max(results) if results else 0

eng/tools/azure-sdk-tools/azpysdk/main.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from .verifytypes import verifytypes
2828
from .verify_whl import verify_whl
2929
from .verify_sdist import verify_sdist
30+
from .bandit import bandit
3031
from .verify_keywords import verify_keywords
3132

3233
from ci_tools.logging import configure_logging, logger
@@ -86,6 +87,7 @@ def build_parser() -> argparse.ArgumentParser:
8687
verifytypes().register(subparsers, [common])
8788
verify_sdist().register(subparsers, [common])
8889
verify_whl().register(subparsers, [common])
90+
bandit().register(subparsers, [common])
8991
verify_keywords().register(subparsers, [common])
9092

9193
return parser

0 commit comments

Comments
 (0)