"""Run release gates and preserve reports, tool versions, and process exit codes.""" import argparse import json import subprocess import tempfile from datetime import datetime, timezone from pathlib import Path def now(): return datetime.now(timezone.utc).isoformat() def check_report(report, kind): if kind == "dependencies": dependencies = report["dependencies"] if not dependencies: raise ValueError("Dependency audit returned no packages") return [v for package in dependencies for v in package["vulns"]] if report["SchemaVersion"] != 2 or "ArtifactName" not in report: raise ValueError("Unrecognized Trivy report") results = report["Results"] if not isinstance(results, list): raise ValueError("Trivy Results must be a list") if kind == "image" and not results: raise ValueError("Image scan returned no analyzed targets") if kind == "secrets": return [secret for result in results for secret in result.get("Secrets", [])] return [ vulnerability for result in results for vulnerability in result.get("Vulnerabilities", []) if vulnerability["Severity"] in {"HIGH", "CRITICAL"} ] def redact_secret_matches(report): for result in report.get("Results", []): for secret in result.get("Secrets", []): secret["Match"] = "[REDACTED]" for line in secret.get("Code", {}).get("Lines", []): line["Content"] = "[REDACTED]" def main(): parser = argparse.ArgumentParser() parser.add_argument("phase", choices=["source", "image"]) parser.add_argument("--image") parser.add_argument("--fixture", action="store_true") parser.add_argument("--reports", default="build/delivery/reports") args = parser.parse_args() reports = Path(args.reports).resolve() reports.mkdir(parents=True, exist_ok=True) execution = {"started": now(), "phase": args.phase, "steps": []} def run(command, label, accepted=(0,)): result = subprocess.run(command, text=True, capture_output=True) (reports / f"{label}.log").write_text(result.stdout + result.stderr) execution["steps"].append({ "label": label, "command": command, "completed": now(), "exit_code": result.returncode, }) if result.returncode not in accepted: raise RuntimeError(f"{label} failed with exit code {result.returncode}") return result def scan_secrets(target, label): output = reports / f"{label}.json" run([ "trivy", "fs", "--scanners", "secret", "--secret-config", "delivery/trivy-secret.yaml", "--format", "json", "--output", str(output), "--skip-dirs", ".git", "--skip-dirs", "build", "--skip-dirs", "work", "--skip-dirs", ".venv", str(target), ], label) report = json.loads(output.read_text()) redact_secret_matches(report) output.write_text(json.dumps(report, indent=2)) if check_report(report, "secrets"): raise RuntimeError(f"{label}: detected secrets block delivery") try: run(["trivy", "--version"], "trivy-version") run(["pip-audit", "--version"], "pip-audit-version") if args.phase == "source": scan_secrets(".", "source-secrets") output = reports / "dependencies.json" result = run([ "pip-audit", "-r", "delivery/app/requirements.txt", "--no-deps", "--disable-pip", "--format", "json", "--output", str(output), ], "dependencies", accepted=(0, 1)) findings = check_report(json.loads(output.read_text()), "dependencies") if result.returncode or findings: raise RuntimeError("Dependency findings or audit errors block delivery") if args.fixture: with tempfile.TemporaryDirectory(prefix="ssw590-scan-") as directory: # Construct the nonfunctional course fixture only in the test run. value = "SSW590_SYNTHETIC_SECRET_" + "0" * 16 Path(directory, "fixture.txt").write_text(value) scan_secrets(directory, "synthetic-secret") raise RuntimeError("Synthetic fixture was not detected") else: if not args.image: raise ValueError("--image is required for the image gate") output = reports / "image.json" run([ "trivy", "image", "--scanners", "vuln", "--format", "json", "--output", str(output), args.image, ], "image") run(["trivy", "--version"], "trivy-database-version") if check_report(json.loads(output.read_text()), "image"): raise RuntimeError("HIGH/CRITICAL image findings block delivery") execution["result"] = "passed" print(f"{args.phase} gate passed") except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error: execution["result"] = "blocked" execution["reason"] = str(error) print(f"{args.phase} gate blocked: {error}") return 1 finally: execution["completed"] = now() (reports / f"{args.phase}-execution.json").write_text(json.dumps(execution, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())