test(security): retain reproducible lifecycle and image scan evidence

This commit is contained in:
2026-11-22 19:16:23 +03:00
parent 2b6f99284d
commit 87d71cba8f
6 changed files with 5343 additions and 17 deletions
+198
View File
@@ -0,0 +1,198 @@
"""Scan actual verified application/S3 images using an isolated pinned scanner."""
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SCANNER = "aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb"
def isolated(cache, workspace, *, offline=False):
args = [
"docker",
"run",
"--rm",
"--user",
f"{os.getuid()}:{os.getgid()}",
"--cpus",
"0.5",
"--memory",
"768m",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges:true",
"-v",
f"{cache}:/cache",
"-v",
f"{workspace / 'tmp'}:/tmp",
"-v",
f"{workspace / 'input'}:/scan:ro",
"-v",
f"{workspace / 'reports'}:/output",
"-e",
"TRIVY_CACHE_DIR=/cache",
"-e",
"GOMEMLIMIT=384MiB",
]
if offline:
args += ["--network", "none"]
return args + [SCANNER]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--verification", default="evidence/clean-clone-review.json"
)
parser.add_argument("--output", default="evidence/image-scan-review.json")
args = parser.parse_args()
output = ROOT / args.output
assert not output.exists(), "Choose a new receipt path"
proof = json.loads((ROOT / args.verification).read_text())
assert proof["result"] == "PASS" and proof["checks_completed"]
research = proof["security_research"]
assert research["complete"]
selected = []
for label, role in [("application", "worker"), ("object-store", "s3")]:
# identity-s3 has the application image; it is not the S3 server.
pattern = r"/mtusi-lab7-clean-[0-9a-f]{10}-" + role + r"-\d+"
matches = {
image
for name, image in research["images_before"].items()
if re.fullmatch(pattern, name)
}
assert len(matches) == 1, "Missing or ambiguous verified service image"
selected.append((label, matches.pop()))
assert len({image for _, image in selected}) == 2
assert shutil.disk_usage(ROOT).free >= 3 * 1024**3, (
"Scanning needs 3 GiB free for the vulnerability database and image archive"
)
cache = ROOT / ".work-trivy-cache"
workspace = ROOT / ".work-image-scans" / output.stem
for directory in [
cache,
workspace / "tmp",
workspace / "input",
workspace / "reports",
]:
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
receipt = {
"date": datetime.now(UTC).isoformat(),
"scanner": SCANNER,
"verified_runtime_source": proof["source_commit"],
"scope": "actual local application and object-store images; other images not covered",
"isolation": "no Docker socket or credentials; read-only root; scan network disabled",
"complete": False,
"images": [],
}
output.parent.mkdir(parents=True, exist_ok=True)
try:
subprocess.run(
isolated(cache, workspace)
+ ["image", "--download-db-only", "--timeout", "10m"],
check=True,
)
receipt["database"] = json.loads(
(cache / "db/metadata.json").read_text()
)
for label, image in selected:
metadata = json.loads(
subprocess.check_output(
["docker", "image", "inspect", image],
text=True,
)
)[0]
revision = (metadata["Config"].get("Labels") or {}).get(
"org.opencontainers.image.revision"
)
if label == "application":
assert revision == proof["source_commit"]
archive = workspace / "input/image.tar"
try:
subprocess.run(
[
"docker",
"image",
"save",
"--output",
str(archive),
image,
],
check=True,
)
name = label + ".json"
subprocess.run(
isolated(cache, workspace, offline=True)
+ [
"image",
"--skip-db-update",
"--scanners",
"vuln",
"--input",
"/scan/image.tar",
"--format",
"json",
"--output",
"/output/" + name,
"--timeout",
"10m",
],
check=True,
)
raw = (workspace / "reports" / name).read_bytes()
vulnerabilities = []
for target in json.loads(raw).get("Results", []):
for value in target.get("Vulnerabilities", []):
vulnerabilities.append(
{
"target": target["Target"],
"type": target.get("Type"),
"id": value["VulnerabilityID"],
"package": value["PkgName"],
"installed": value["InstalledVersion"],
"fixed": value.get("FixedVersion"),
"severity": value["Severity"],
"status": value.get("Status"),
"url": value.get("PrimaryURL"),
}
)
counts = dict(
Counter(value["severity"] for value in vulnerabilities)
)
receipt["images"].append(
{
"name": label,
"image": image,
"id": metadata["Id"],
"revision": revision,
"architecture": metadata["Architecture"],
"report_sha256": hashlib.sha256(raw).hexdigest(),
"counts": counts,
"vulnerabilities": vulnerabilities,
}
)
print("SCANNED", label, counts, flush=True)
finally:
archive.unlink(missing_ok=True)
receipt["complete"] = True
except BaseException as error:
receipt["failure_type"] = type(error).__name__
raise
finally:
output.write_text(
json.dumps(receipt, ensure_ascii=False, indent=2) + "\n"
)
if __name__ == "__main__":
main()