|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Check Bandit security scan results against threshold.""" |
| 3 | + |
| 4 | +import json |
| 5 | +import os |
| 6 | +import sys |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | + |
| 10 | +def main() -> None: |
| 11 | + """Check bandit results against SECURITY_FAIL_LEVEL threshold.""" |
| 12 | + fail_level = os.getenv("SECURITY_FAIL_LEVEL", "MEDIUM").upper() |
| 13 | + severity_order = ["LOW", "MEDIUM", "HIGH"] |
| 14 | + |
| 15 | + if fail_level not in severity_order: |
| 16 | + print(f"Invalid SECURITY_FAIL_LEVEL: {fail_level}") |
| 17 | + sys.exit(1) |
| 18 | + |
| 19 | + threshold_index = severity_order.index(fail_level) |
| 20 | + |
| 21 | + report_path = Path("bandit-report.json") |
| 22 | + if not report_path.exists(): |
| 23 | + print("No bandit-report.json found, skipping.") |
| 24 | + return |
| 25 | + |
| 26 | + with report_path.open() as f: |
| 27 | + data = json.load(f) |
| 28 | + |
| 29 | + results = data.get("results", []) |
| 30 | + issues_above_threshold = [ |
| 31 | + r for r in results if severity_order.index(r["issue_severity"]) >= threshold_index |
| 32 | + ] |
| 33 | + |
| 34 | + if issues_above_threshold: |
| 35 | + msg = ( |
| 36 | + f"❌ Found {len(issues_above_threshold)} Bandit issues " |
| 37 | + f"at or above {fail_level} severity:" |
| 38 | + ) |
| 39 | + print(msg) |
| 40 | + for issue in issues_above_threshold: |
| 41 | + location = f"{issue['filename']}:{issue['line_number']}" |
| 42 | + msg = f" - {issue['issue_text']} ({issue['issue_severity']}) in {location}" |
| 43 | + print(msg) |
| 44 | + sys.exit(1) |
| 45 | + else: |
| 46 | + print(f"✅ No Bandit issues at or above {fail_level} severity.") |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + main() |
0 commit comments