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
+445
View File
@@ -0,0 +1,445 @@
{
"source_commit": "53e4d8e72908b7ad167651a62b6327b6dbacdd75",
"seed": "diagnostic-gc-seed.json",
"complete": true,
"real_s3_age_seconds": 1859.672862,
"dry_run": {
"apply": false,
"retention_seconds": 300,
"actions": [
{
"action": "delete_expired_object",
"key": "objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/old-orphan",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/crop",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/optimized",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/thumbnail",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/071fd46b-4192-4923-8c82-7915d2cf2a27/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/1dd99e05-70f5-48ed-9cde-3d27d9c8c6ef/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/263a3ffc-7ed3-4eb0-bbf2-9d44b02627f8/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/31fb6c8f-288a-4ab2-bd74-f09349d106e7/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/349f1620-f013-41cf-9537-0859f06af77b/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/3e16aa3b-2f37-4764-874f-50576f50895b/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/45b367de-7b72-442a-b6d2-c1d124d765bb/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/4fcdbe2e-5ad4-454c-809d-991fc59ca092/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/57f1f046-072d-4b80-b35e-465c73527c59/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/5bcfd528-bcb2-44f6-b68a-d0b13f94eac8/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/608ecc35-b02b-4baf-a831-6de748682ef0/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/621d695d-60b0-4894-be56-25f31a2d6f20/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/66de8671-f2f8-4cea-ad31-2484c0a5d454/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/6d01013c-026b-4ad8-a974-f9f6a13d4b53/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/74d977c9-cd52-4c7e-9c85-aad47f31927c/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/76229eb2-88fa-48da-8f5c-ee4736850801/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/7b34905f-ef50-4b92-aaab-253561f93c73/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/8df597be-2f78-4d20-9893-221e5d2f81ed/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/92dbbca4-b497-4074-bac5-49d99452b71f/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/9b91a27b-d52c-48a1-a5b1-4d198bc0178b/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/9f278645-d8fd-4e67-b090-4439a43acf64/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/a9f7bf9f-416d-4a6d-abbe-3e9654426794/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/c10ca9fb-f70b-4f22-a16d-7beca87af9d1/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/d2a6a149-0c21-4a4b-a170-c73f64a341ab/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/d590569c-068e-4169-8929-cc8f300ddfb9/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/d89330e5-7db0-4995-b8df-edefc7c0791c/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/e16ae582-8420-4fe3-915b-1891450618a3/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/e3901deb-dd65-4a14-9f15-8fb928947ec0/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/e66e2f91-be33-4105-8248-767e111a0e3c/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/e6ea9d7f-8913-40f6-9f4c-da1e1dbb77be/original",
"applied": false
},
{
"action": "delete_expired_object",
"key": "objects/staging/f1681a6f-f6b3-4722-aa95-ac49f2a34001/original",
"applied": false
}
]
},
"apply": {
"apply": true,
"retention_seconds": 300,
"actions": [
{
"action": "delete_expired_object",
"key": "objects/4fcdbe2e-5ad4-454c-809d-991fc59ca092/v1/crop",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/4fcdbe2e-5ad4-454c-809d-991fc59ca092/v1/optimized",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/4fcdbe2e-5ad4-454c-809d-991fc59ca092/v1/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/4fcdbe2e-5ad4-454c-809d-991fc59ca092/v1/thumbnail",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/old-orphan",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/crop",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/optimized",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/thumbnail",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/071fd46b-4192-4923-8c82-7915d2cf2a27/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/1dd99e05-70f5-48ed-9cde-3d27d9c8c6ef/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/263a3ffc-7ed3-4eb0-bbf2-9d44b02627f8/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/31fb6c8f-288a-4ab2-bd74-f09349d106e7/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/349f1620-f013-41cf-9537-0859f06af77b/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/3e16aa3b-2f37-4764-874f-50576f50895b/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/45b367de-7b72-442a-b6d2-c1d124d765bb/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/4fcdbe2e-5ad4-454c-809d-991fc59ca092/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/57f1f046-072d-4b80-b35e-465c73527c59/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/5bcfd528-bcb2-44f6-b68a-d0b13f94eac8/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/608ecc35-b02b-4baf-a831-6de748682ef0/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/621d695d-60b0-4894-be56-25f31a2d6f20/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/66de8671-f2f8-4cea-ad31-2484c0a5d454/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/6d01013c-026b-4ad8-a974-f9f6a13d4b53/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/74d977c9-cd52-4c7e-9c85-aad47f31927c/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/76229eb2-88fa-48da-8f5c-ee4736850801/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/7b34905f-ef50-4b92-aaab-253561f93c73/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/8df597be-2f78-4d20-9893-221e5d2f81ed/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/92dbbca4-b497-4074-bac5-49d99452b71f/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/9b91a27b-d52c-48a1-a5b1-4d198bc0178b/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/9f278645-d8fd-4e67-b090-4439a43acf64/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/a9f7bf9f-416d-4a6d-abbe-3e9654426794/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/c10ca9fb-f70b-4f22-a16d-7beca87af9d1/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/d2a6a149-0c21-4a4b-a170-c73f64a341ab/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/d590569c-068e-4169-8929-cc8f300ddfb9/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/d89330e5-7db0-4995-b8df-edefc7c0791c/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/e16ae582-8420-4fe3-915b-1891450618a3/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/e3901deb-dd65-4a14-9f15-8fb928947ec0/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/e66e2f91-be33-4105-8248-767e111a0e3c/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/e6ea9d7f-8913-40f6-9f4c-da1e1dbb77be/original",
"applied": true
},
{
"action": "delete_expired_object",
"key": "objects/staging/f1681a6f-f6b3-4722-aa95-ac49f2a34001/original",
"applied": true
}
]
},
"repeat": {
"apply": true,
"retention_seconds": 300,
"actions": []
},
"before": {
"objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/old-orphan": true,
"objects/staging/5bcfd528-bcb2-44f6-b68a-d0b13f94eac8/original": true,
"objects/staging/1dd99e05-70f5-48ed-9cde-3d27d9c8c6ef/original": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/original": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/thumbnail": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/crop": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/optimized": true,
"objects/staging/61952df8-ce5a-4e5a-8f89-46a34e3cc102/original": true,
"objects/staging/97a3a190-fbc4-403c-a70c-3dcf785247dc/original": true,
"objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/fresh-orphan": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/original": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/thumbnail": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/crop": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/optimized": true
},
"after": {
"objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/old-orphan": false,
"objects/staging/5bcfd528-bcb2-44f6-b68a-d0b13f94eac8/original": false,
"objects/staging/1dd99e05-70f5-48ed-9cde-3d27d9c8c6ef/original": false,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/original": false,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/thumbnail": false,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/crop": false,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v1/optimized": false,
"objects/staging/61952df8-ce5a-4e5a-8f89-46a34e3cc102/original": true,
"objects/staging/97a3a190-fbc4-403c-a70c-3dcf785247dc/original": true,
"objects/cleanup-82c080f2d5564bbf8dce79c9e4ff6a08/fresh-orphan": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/original": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/thumbnail": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/crop": true,
"objects/e3901deb-dd65-4a14-9f15-8fb928947ec0/v2/optimized": true
},
"dry_run_unchanged": true,
"active_current_and_fresh_protected": true,
"expired_source_replay_refused": true,
"expired_writer_fenced": true,
"diagnostic_provenance": {
"runtime_application_revision": "53e4d8e72908b7ad167651a62b6327b6dbacdd75",
"operator_helpers_commit": "37d40e4",
"restart_hook_commit": "10b280a",
"fresh_full_verification": false
}
}
@@ -0,0 +1,20 @@
{
"result": "INCOMPLETE",
"diagnostic_provenance": {
"runtime_application_revision": "53e4d8e72908b7ad167651a62b6327b6dbacdd75",
"operator_helpers_commit": "37d40e4",
"restart_hook_commit": "10b280a",
"fresh_full_verification": false
},
"passed": 111,
"failed": 1,
"seconds": 171.85,
"failure": "oversized image must return contract JSON 413; one run returned HAProxy HTML 502",
"failed_test": "test_image_guards[data5-image/png-413]",
"isolated_repeat": {
"passed": 6,
"failed": 0,
"seconds": 7.82
},
"intermittent_failure_not_a_complete_HTTP_pass": true
}
File diff suppressed because it is too large Load Diff
+240
View File
@@ -0,0 +1,240 @@
"""Summarize only completed PKI observations and their actual time intervals."""
import argparse
import csv
import json
import math
import re
import statistics
from collections import Counter
from itertools import pairwise
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def quantile(values, fraction):
ordered = sorted(values)
return (
ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
if ordered
else None
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
report = json.loads(args.input.read_text())
assert report["complete"], (
"An incomplete experiment cannot yield a final analysis"
)
with args.input.with_name(
args.input.stem + "-requests.csv"
).open() as stream:
rows = list(csv.DictReader(stream))
for row in rows:
row["started_at"] = float(row["started_at"])
row["duration_seconds"] = float(row["duration_seconds"])
row["status"] = int(row["status"])
phases = []
for phase in report["phases"]:
observed = [
r
for r in rows
if phase["started_at"] <= r["started_at"] < phase["ended_at"]
]
successful = [
r["duration_seconds"] for r in observed if r["status"] == 201
]
duration = phase["ended_at"] - phase["started_at"]
phases.append(
{
"phase": phase["name"],
"seconds": round(duration, 3),
"scheduled_messages": len(observed),
"statuses": dict(Counter(str(r["status"]) for r in observed)),
"successful_rps": round(len(successful) / duration, 4),
"http_errors": sum(
r["status"] not in {201, 0, -1} for r in observed
),
"transport_errors": sum(r["status"] == 0 for r in observed),
"client_backpressure_drops": sum(
r["status"] == -1 for r in observed
),
"attempted_request_error_fraction": (
sum(r["status"] not in {201, -1} for r in observed)
/ sum(r["status"] != -1 for r in observed)
)
if any(r["status"] != -1 for r in observed)
else None,
**{
f"success_p{int(q * 100)}_seconds": quantile(successful, q)
for q in [0.5, 0.95, 0.99]
},
}
)
args.output.mkdir(parents=True, exist_ok=True)
summary = {
"source_commit": report["source_commit"],
"complete": True,
"phase_assignment": "actual request start within measured phase wall-clock bounds",
"preservation": report["preservation"],
"phases": phases,
"all_statuses": dict(Counter(str(r["status"]) for r in rows)),
}
resources = {}
for sample in report.get("resource_samples", []):
for observation in sample["containers"]:
name = observation["Name"]
result = resources.setdefault(
name,
{
"observations": 0,
"maximum_observed_cpu_cores": 0,
"maximum_observed_memory_mib": 0,
},
)
result["observations"] += 1
result["maximum_observed_cpu_cores"] = max(
result["maximum_observed_cpu_cores"],
float(observation["CPUPerc"].rstrip("%")) / 100,
)
value, unit = re.fullmatch(
r"([\d.]+)([KMGT]?i?B)",
observation["MemUsage"].split("/")[0].strip(),
).groups()
factor = {
"B": 1,
"KiB": 1024,
"MiB": 1024**2,
"GiB": 1024**3,
"TiB": 1024**4,
"kB": 1000,
"MB": 1000**2,
"GB": 1000**3,
}[unit]
result["maximum_observed_memory_mib"] = max(
result["maximum_observed_memory_mib"],
float(value) * factor / 1024**2,
)
samples = report.get("resource_samples", [])
intervals = [
b["started_at"] - a["started_at"] for a, b in pairwise(samples)
]
summary["sampling_intervals_seconds"] = (
{
"min": min(intervals),
"median": statistics.median(intervals),
"max": max(intervals),
}
if intervals
else None
)
summary["resources"] = {
"measurement": report.get("resource_measurement"),
"limits": report.get("resource_limits"),
"sampled_maxima_not_absolute_peaks": resources,
"sampling_errors": report.get("resource_sampling_errors", []),
}
(args.output / "summary.json").write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n"
)
with (args.output / "phases.csv").open("w") as stream:
writer = csv.DictWriter(stream, fieldnames=list(phases[0]))
writer.writeheader()
writer.writerows(
{**p, "statuses": json.dumps(p["statuses"])} for p in phases
)
origin = report["phases"][0]["started_at"]
finish = max(r["started_at"] + r["duration_seconds"] for r in rows)
count = math.ceil((finish - origin) / 10)
windows = [
[
r
for r in rows
if origin + i * 10 <= r["started_at"] < origin + (i + 1) * 10
]
for i in range(count)
]
fig, axes = plt.subplots(
2, 1, figsize=(12, 7), sharex=True, constrained_layout=True
)
positions = [i * 10 + 5 for i in range(count)]
bottom = [0] * count
for label, color, predicate in [
("201: подтверждено", "#238b45", lambda s: s == 201),
("Ошибки HTTP", "#d95f0e", lambda s: s not in {201, 0, -1}),
("Ошибка TLS / сети", "#756bb1", lambda s: s == 0),
("Генератор занят", "#969696", lambda s: s == -1),
]:
values = [
sum(predicate(r["status"]) for r in window) for window in windows
]
axes[0].bar(
positions,
values,
width=9.5,
bottom=bottom,
label=label,
color=color,
)
bottom = [a + b for a, b in zip(bottom, values, strict=True)]
for q, label in [(0.5, "p50"), (0.95, "p95")]:
values = [
quantile(
[r["duration_seconds"] for r in window if r["status"] == 201],
q,
)
for window in windows
]
axes[1].plot(
positions,
[v if v is not None else math.nan for v in values],
label=label,
)
labels = ["1", "2", "3", "4", "5", "6", "7"]
for i, phase in enumerate(report["phases"]):
left, right = phase["started_at"] - origin, phase["ended_at"] - origin
for axis in axes:
axis.axvspan(
left,
right,
color="#d9e5ef",
alpha=0.22 if i % 2 == 0 else 0.04,
)
axis.axvline(left, color="#51616c", lw=0.6)
axes[0].text(
(left + right) / 2,
1.02,
labels[i],
transform=axes[0].get_xaxis_transform(),
ha="center",
fontsize=8,
)
axes[0].set_ylabel("Запросы сообщений за 10 с")
axes[1].set_ylabel("Задержка успешного запроса, с")
axes[1].set_xlabel("Секунды от начала первого этапа")
for axis in axes:
axis.legend(loc="upper left", fontsize=8)
axis.grid(axis="y", alpha=0.2)
fig.suptitle("Жизненный цикл сертификатов под нагрузкой HTTPS", y=1.04)
fig.text(
0.5,
-0.04,
"1 — Обновление; 2 — Смена рабочего ключа; 3 — Отзыв; 4 — Истечение;\n5 — Блокировка OpenBao; 6 — Замена CA; 7 — После восстановления",
ha="center",
fontsize=9,
)
fig.savefig(args.output / "pki-results.png", dpi=170, bbox_inches="tight")
plt.close(fig)
print("PASS: observed phase summaries and PKI figure")
if __name__ == "__main__":
main()
+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()
+27 -17
View File
@@ -115,11 +115,16 @@ def main():
output = ROOT / args.output
if output.exists():
raise SystemExit("Choose new output path")
for name in ["pki-research-final.json", "pki-research-final-requests.csv"]:
if (ROOT / "evidence" / name).exists():
raise SystemExit(
"Retain the existing research receipt under a distinct name before a fresh full run"
)
research_output = output.with_name(
"pki-research-final.json"
if output.name == "clean-clone-final.json"
else output.stem + "-pki-research.json"
)
research_csv_output = research_output.with_name(
research_output.stem + "-requests.csv"
)
if any(path.exists() for path in [research_output, research_csv_output]):
raise SystemExit("Choose a new verification and research receipt path")
assert not subprocess.check_output(
["git", "status", "--porcelain"], cwd=ROOT
)
@@ -127,6 +132,10 @@ def main():
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
).strip()
identity = uuid4().hex[:10]
research_relative = Path("evidence/verification-pki-" + identity + ".json")
research_csv_relative = research_relative.with_name(
research_relative.stem + "-requests.csv"
)
project = "mtusi-lab7-clean-" + identity
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
@@ -303,25 +312,23 @@ def main():
"-m",
"scripts.research_security",
"--output",
"evidence/pki-research-final.json",
str(research_relative),
],
cwd=clone,
env=env,
)
receipt["security_research"] = json.loads(
(clone / "evidence/pki-research-final.json").read_text()
(clone / research_relative).read_text()
)
for name in [
"pki-research-final.json",
"pki-research-final-requests.csv",
receipt["security_research_file"] = research_output.name
for source, destination in [
(clone / research_relative, research_output),
(clone / research_csv_relative, research_csv_output),
]:
destination = ROOT / "evidence" / name
assert not destination.exists(), (
"Choose a fresh research receipt path"
)
destination.write_text(
redact((clone / "evidence" / name).read_text(), clone)
)
destination.write_text(redact(source.read_text(), clone))
import hashlib
expected = {
@@ -394,14 +401,17 @@ def main():
"pipeline",
"cleanup",
"gc-seed",
"pki-research-final",
]:
prefix = "" if name == "pki-research-final" else "clean-"
partial = clone / "evidence" / (prefix + name + ".json")
partial = clone / "evidence" / ("clean-" + name + ".json")
if partial.exists():
receipt["partial_evidence"][name] = json.loads(
redact(partial.read_text(), clone)
)
partial = clone / research_relative
if partial.exists():
receipt["partial_evidence"]["pki-research"] = json.loads(
redact(partial.read_text(), clone)
)
receipt["failure_diagnostics"] = {}
for label, arguments in [
("services", ["ps", "-a", "--format", "json"]),