feat: scan images and uv.lock for vulnerabilities with a triage file and patch-line updates

make scan runs pinned Trivy (by digest, no Docker socket, images as
docker save archives, network none, read-only) over every compose image
and the app image (also secrets in layers) and pinned pip-audit over the
uv.lock groups; every CRITICAL/HIGH image finding, secret and pip-audit
finding needs a triage record (verdict, reason, control, review date)
in infra/scan/triage.toml, otherwise a non-zero exit. Fixable findings
are updated within the patch line after a 7-day quarantine: PostgreSQL
and RabbitMQ rebuilds, Valkey 9.1.4, HAProxy 3.4.7, Loki 3.7.10, Python
3.12.15, certifi, dnspython, black, filelock, virtualenv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 12:48:07 +03:00
co-authored by Claude Opus 5.5
parent 1ea196c38f
commit b6eed88e95
21 changed files with 3007 additions and 70 deletions
+560
View File
@@ -0,0 +1,560 @@
"""Команда `make scan` без Docker и сети (change `vulnerability-scan`, design,
решение 14; спек `vulnerability-management`).
- Разбор JSON Trivy и pip-audit (урезанные фрагменты формы пробы, дубли
pip-audit — одна находка).
- Правило обязательных находок, покрытие записью (ID и алиасы, образы,
пакеты, пути), истёкший срок, устаревшая запись, код завершения.
- Проверки записи файла разбора: каждое нарушение — TriageError с ключом и
полем (код 2); горизонты 90 / 30 суток.
- Список образов из модели compose: образ приложения, отказ незакреплённому
образу; сторонние образы основного файла закреплены.
- Аргументы контейнеров сканера: scan без сети, корень только на чтение,
без capabilities, не root, пределы, монтирования только на чтение, без
сокета Docker; загрузка базы — без архивов.
- Ссылка Trivy — тег и digest; pip-audit — точная версия; файл разбора
репозитория проходит проверки.
Контроль: горизонт `accepted` 90 суток вместо 30 — тест
`test_accepted_horizon` красный.
"""
import datetime as dt
import importlib.util
import re
import sys
import tomllib
from pathlib import Path
from types import ModuleType
import pytest
import yaml
from src.config.settings import BASE_DIR
SCAN_PY = BASE_DIR / "infra" / "scan" / "scan.py"
TODAY = dt.date(2026, 11, 27)
def _load() -> ModuleType:
spec = importlib.util.spec_from_file_location("mtusi_scan", SCAN_PY)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules.setdefault("mtusi_scan", module)
spec.loader.exec_module(module)
return module
scan = _load()
TRIVY_DOC = {
"Trivy": {"Version": "0.76.2"},
"Metadata": {"OS": {"Family": "debian", "Name": "13.7"}},
"Results": [
{
"Target": "/images/x.tar (debian 13.7)",
"Class": "os-pkgs",
"Type": "debian",
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2026-1",
"PkgName": "libssl3t64",
"InstalledVersion": "3.5.1-1",
"FixedVersion": "",
"Status": "affected",
"Severity": "HIGH",
"VendorIDs": ["DSA-1-1"],
"Title": "openssl: quic",
},
{
"VulnerabilityID": "CVE-2026-1",
"PkgName": "libssl3t64",
"InstalledVersion": "3.5.1-1",
"Status": "affected",
"Severity": "HIGH",
},
{
"VulnerabilityID": "CVE-2026-1",
"PkgName": "openssl",
"InstalledVersion": "3.5.1-1",
"Status": "affected",
"Severity": "HIGH",
},
{
"VulnerabilityID": "CVE-2026-2",
"PkgName": "ncurses-base",
"InstalledVersion": "6.5",
"Status": "affected",
"Severity": "MEDIUM",
},
],
},
{
"Target": "usr/local/bin/gosu",
"Class": "lang-pkgs",
"Type": "gobinary",
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2025-68121",
"PkgName": "stdlib",
"InstalledVersion": "v1.24.6",
"FixedVersion": "1.24.13",
"Status": "fixed",
"Severity": "CRITICAL",
},
],
},
{
"Target": "Python",
"Class": "lang-pkgs",
"Type": "python-pkg",
"Vulnerabilities": [
{
"VulnerabilityID": "GHSA-6q48-6c7w-9gw2",
"PkgName": "certifi",
"PkgPath": "app/.venv/lib/python3.12/site-packages/"
"certifi-2026.7.22.dist-info/METADATA",
"InstalledVersion": "2026.7.22",
"FixedVersion": "2026.10.18",
"Status": "fixed",
"Severity": "CRITICAL",
},
],
},
{
"Target": "/app/.env",
"Class": "secret",
"Secrets": [
{
"RuleID": "project-env-secret",
"Severity": "CRITICAL",
"Title": "Secret value assigned in an environment file",
"StartLine": 2,
"Match": "S3_API_SECRET_KEY=****",
"Layer": {"CreatedBy": "COPY probe.env /app/.env"},
},
],
},
],
}
PIP_AUDIT_DOC = {
"dependencies": [
{
"name": "certifi",
"version": "2026.7.22",
"vulns": [
{
"id": "PYSEC-2026-4320",
"fix_versions": ["2026.10.18"],
"aliases": ["GHSA-6q48-6c7w-9gw2"],
"description": "emSign root",
},
{
"id": "GHSA-6q48-6c7w-9gw2",
"fix_versions": ["2026.10.18"],
"aliases": ["PYSEC-2026-4320"],
"description": "emSign root",
},
],
},
{"name": "pydantic", "version": "2.13.1", "vulns": []},
{
"name": "dnspython",
"version": "2.8.0",
"vulns": [
{
"id": "CVE-2026-114605",
"fix_versions": ["2.9.0"],
"aliases": ["GHSA-45c3-73f7-pv4m"],
"description": "### Impact\nCPU",
},
],
},
],
"fixes": [],
}
def _entry(**overrides: object) -> dict:
entry: dict = {
"key": "openssl-quic",
"ids": ["CVE-2026-1"],
"targets": ["haproxy"],
"verdict": "not_affected",
"reason": "no QUIC listeners",
"control": "make hardening_check: TCP listeners only",
"review_by": TODAY + dt.timedelta(days=30),
}
entry.update(overrides)
return {k: v for k, v in entry.items() if v is not None}
TARGETS = {"haproxy", "postgres", "mtusi-messenger", "uv.lock"}
def _entries(*items: dict) -> list:
return scan.parse_triage({"entry": list(items)}, TARGETS, TODAY)
# --- разбор JSON ---------------------------------------------------------------
def test_parse_trivy() -> None:
os_name, findings = scan.parse_trivy(TRIVY_DOC, "postgres")
assert os_name == "debian 13.7"
vulns = [f for f in findings if f.kind == "vuln"]
# дубль строки (тот же ID, пакет, версия, путь) — одна находка
assert len(vulns) == 5
gosu = next(f for f in vulns if f.package == "stdlib")
assert gosu.path == "usr/local/bin/gosu"
assert gosu.severity == "CRITICAL" and gosu.fixed == "1.24.13"
certifi = next(f for f in vulns if f.package == "certifi")
assert certifi.path.endswith("METADATA")
ssl = next(f for f in vulns if f.package == "libssl3t64")
assert ssl.path == "" and ssl.aliases == ("DSA-1-1",)
(secret,) = [f for f in findings if f.kind == "secret"]
assert secret.vuln_id == "project-env-secret"
assert secret.path == "app/.env" and secret.line == 2
assert secret.layer == "COPY probe.env /app/.env"
# значение совпадения в находку не попадает
assert "****" not in repr(secret)
def test_parse_pip_audit_merges_duplicates() -> None:
packages, findings = scan.parse_pip_audit(PIP_AUDIT_DOC, "runtime")
assert packages == 3
assert len(findings) == 2
certifi = next(f for f in findings if f.package == "certifi")
assert certifi.ids == {"PYSEC-2026-4320", "GHSA-6q48-6c7w-9gw2"}
assert certifi.fixed == "2026.10.18" and certifi.group == "runtime"
assert certifi.target == "uv.lock"
dns = next(f for f in findings if f.package == "dnspython")
assert dns.title == "### Impact"
def test_mandatory_rule() -> None:
_, findings = scan.parse_trivy(TRIVY_DOC, "postgres")
by_pkg = {f.package or f.vuln_id: f for f in findings}
assert by_pkg["libssl3t64"].mandatory
assert by_pkg["stdlib"].mandatory
assert not by_pkg["ncurses-base"].mandatory
assert by_pkg["project-env-secret"].mandatory
_, deps = scan.parse_pip_audit(PIP_AUDIT_DOC, "dev")
assert all(f.mandatory for f in deps)
# --- покрытие ----------------------------------------------------------------
def _finding(**kw: object):
base = {
"target": "haproxy",
"kind": "vuln",
"vuln_id": "CVE-2026-1",
"package": "libssl3t64",
"version": "3.5.1-1",
"severity": "HIGH",
}
base.update(kw)
return scan.Finding(**base)
def test_coverage_alias_target_package_path() -> None:
entries = _entries(
_entry(ids=["DSA-1-1"]),
_entry(
key="gosu",
ids=["CVE-2025-68121"],
targets=["postgres"],
packages=["stdlib"],
paths=["usr/local/bin/*"],
),
)
by_alias = _finding(aliases=("DSA-1-1",))
other_image = _finding(target="postgres", aliases=("DSA-1-1",))
gosu = _finding(
target="postgres",
vuln_id="CVE-2025-68121",
package="stdlib",
path="usr/local/bin/gosu",
severity="CRITICAL",
)
other_path = _finding(
target="postgres",
vuln_id="CVE-2025-68121",
package="stdlib",
path="usr/lib/postgresql/bin/x",
severity="CRITICAL",
)
other_pkg = _finding(
target="postgres",
vuln_id="CVE-2025-68121",
package="golang.org/x/net",
path="usr/local/bin/gosu",
)
cov = scan.apply_triage(
[by_alias, other_image, gosu, other_path, other_pkg],
entries,
TODAY,
{"haproxy", "postgres"},
)
assert cov.covered == {by_alias: "openssl-quic", gosu: "gosu"}
# запись называет только haproxy: находка postgres с тем же ID непокрыта
assert cov.uncovered == [other_image, other_path, other_pkg]
assert scan.verdict_code(False, cov) == 1
assert scan.verdict_code(True, cov) == 0
def test_below_threshold_needs_no_triage() -> None:
medium = _finding(severity="MEDIUM")
cov = scan.apply_triage([medium], [], TODAY, {"haproxy"})
assert cov.uncovered == [] and scan.verdict_code(False, cov) == 0
def test_expired_entry_covers_nothing() -> None:
entries = _entries(_entry(review_by=TODAY - dt.timedelta(days=1)))
finding = _finding()
cov = scan.apply_triage([finding], entries, TODAY, {"haproxy"})
assert cov.uncovered == [finding]
assert cov.expired_hits == {finding: "openssl-quic"}
assert cov.states["openssl-quic"] == "EXPIRED"
assert scan.verdict_code(False, cov) == 1
# срок сегодня — ещё действует
entries = _entries(_entry(review_by=TODAY))
cov = scan.apply_triage([finding], entries, TODAY, {"haproxy"})
assert cov.covered == {finding: "openssl-quic"}
def test_stale_and_skipped_entries() -> None:
entries = _entries(
_entry(),
_entry(key="lock", ids=["PYSEC-1"], targets=["uv.lock"]),
)
cov = scan.apply_triage([], entries, TODAY, {"haproxy"})
assert cov.states == {"openssl-quic": "stale", "lock": "skipped"}
assert scan.verdict_code(False, cov) == 0
# --- проверки записи -----------------------------------------------------------
@pytest.mark.parametrize(
("overrides", "field"),
[
({"key": "Bad Key"}, "key"),
({"ids": []}, "ids"),
({"ids": None}, "ids"),
({"ids": [""]}, "ids"),
({"targets": None}, "targets"),
({"targets": ["grafana/grafana"]}, "targets"),
({"packages": "stdlib"}, "packages"),
({"paths": [1]}, "paths"),
({"verdict": "ignored"}, "verdict"),
({"reason": " "}, "reason"),
({"control": ""}, "control"),
({"control": None}, "control"),
({"reason": "todo: check later"}, "reason"),
({"review_by": "2027-01-01"}, "review_by"),
({"review_by": dt.datetime(2027, 1, 1)}, "review_by"), # noqa: DTZ001
({"review_by": TODAY + dt.timedelta(days=91)}, "review_by"),
({"comment": "x"}, "comment"),
],
)
def test_invalid_entry(overrides: dict, field: str) -> None:
with pytest.raises(scan.TriageError) as info:
_entries(_entry(**overrides))
assert info.value.field == field
assert "openssl-quic" in str(info.value) or field == "key"
def test_duplicate_key() -> None:
with pytest.raises(scan.TriageError) as info:
_entries(_entry(), _entry())
assert (info.value.key, info.value.field) == ("openssl-quic", "key")
def test_review_horizon() -> None:
(entry,) = _entries(_entry(review_by=TODAY + dt.timedelta(days=90)))
assert entry.review_by == TODAY + dt.timedelta(days=90)
def test_accepted_horizon() -> None:
_entries(
_entry(verdict="accepted", review_by=TODAY + dt.timedelta(days=30)),
)
with pytest.raises(scan.TriageError) as info:
_entries(
_entry(
verdict="accepted",
review_by=TODAY + dt.timedelta(days=31),
),
)
assert info.value.field == "review_by"
def test_unknown_top_level_key() -> None:
with pytest.raises(scan.TriageError):
scan.parse_triage({"entries": []}, TARGETS, TODAY)
# --- образы compose ------------------------------------------------------------
PIN = "postgres:18.6-trixie@sha256:" + "a" * 64
def test_images_from_model() -> None:
model = {
"services": {
"api": {"build": {"context": "."}, "image": "mtusi-messenger:x"},
"worker": {"image": "mtusi-messenger:x"},
"postgres": {"image": PIN},
"replica": {"image": PIN},
},
}
third, app = scan.images_from_model(model)
assert app == ["api", "worker"]
assert third == {PIN: ["postgres", "replica"]}
assert scan.target_name(PIN) == "postgres"
@pytest.mark.parametrize(
"image",
[
"postgres:latest",
"postgres:18.6-trixie",
"postgres:latest@sha256:" + "a" * 64,
"postgres@sha256:" + "a" * 64,
"",
],
)
def test_unpinned_image_rejected(image: str) -> None:
model = {
"services": {
"api": {"build": {}, "image": "mtusi-messenger:x"},
"db": {"image": image},
},
}
with pytest.raises(scan.ScanError) as info:
scan.images_from_model(model)
assert info.value.step == "compose" and "service db" in info.value.reason
@pytest.mark.parametrize(
("ref", "name"),
[
("valkey/valkey:9.1.2-trixie@sha256:" + "b" * 64, "valkey/valkey"),
("docker.io/library/postgres:18.6", "postgres"),
("ghcr.io/org/tool:1.0", "org/tool"),
("mtusi-messenger:scan", "mtusi-messenger"),
],
)
def test_target_name(ref: str, name: str) -> None:
assert scan.target_name(ref) == name
def _compose_model() -> dict:
text = (BASE_DIR / "docker-compose.yml").read_text(encoding="utf-8")
return yaml.safe_load(text)
def test_compose_images_pinned() -> None:
third, app = scan.images_from_model(_compose_model())
assert set(app) == {
"api",
"cleaner",
"migrate",
"postgres-bootstrap",
"relay",
"worker",
}
assert len(third) >= 11
for ref in third:
assert scan.PIN_RE.match(ref), ref
def test_repository_triage_is_valid() -> None:
third, _ = scan.images_from_model(_compose_model())
targets = {"mtusi-messenger", "uv.lock", *map(scan.target_name, third)}
data = tomllib.loads(scan.TRIAGE_FILE.read_text(encoding="utf-8"))
# день scan — сегодня: срок записи не дальше горизонта от сегодняшнего дня
entries = scan.parse_triage(data, targets, dt.date.today())
assert len({e.key for e in entries}) == len(entries)
# --- контейнеры сканера и пины ---------------------------------------------------
def _mounts(args: list[str]) -> list[str]:
return [args[i + 1] for i, a in enumerate(args) if a == "--mount"]
def _opt(args: list[str], name: str) -> str:
return args[args.index(name) + 1]
@pytest.mark.parametrize("rules", [None, Path("/repo/infra/scan/s.yaml")])
def test_scan_container_isolated(rules: Path | None) -> None:
args = scan.scan_args(
archive_dir=Path("/tmp/mtusi-scan-x/images"),
archive="a.tar",
cache_dir=Path("/cache"),
uid=501,
gid=20,
run_id="r1",
secret_rules=rules,
)
image_at = args.index(scan.TRIVY_IMAGE)
docker_args = args[:image_at]
assert _opt(docker_args, "--network") == "none"
assert "--read-only" in docker_args
assert _opt(docker_args, "--cap-drop") == "ALL"
assert _opt(docker_args, "--security-opt") == "no-new-privileges"
assert not _opt(docker_args, "--user").startswith("0")
assert _opt(docker_args, "--memory") == _opt(docker_args, "--memory-swap")
assert int(_opt(docker_args, "--pids-limit")) > 0
assert "--privileged" not in docker_args
mounts = _mounts(docker_args)
assert all(m.endswith(",readonly") for m in mounts)
assert not any("docker.sock" in m for m in mounts)
assert "-v" not in docker_args and "--volume" not in docker_args
assert len(mounts) == (3 if rules else 2)
tail = args[image_at:]
for flag in (
"--skip-db-update",
"--offline-scan",
"--skip-java-db-update",
):
assert flag in tail
assert ("--secret-config" in tail) == (rules is not None)
assert _opt(tail, "--scanners") == ("vuln,secret" if rules else "vuln")
def test_db_container_has_no_images() -> None:
args = scan.db_args(Path("/cache"), 501, 20, "r1")
docker_args = args[: args.index(scan.TRIVY_IMAGE)]
(mount,) = _mounts(docker_args)
assert "dst=/cache" in mount and "images" not in mount
assert "--read-only" in docker_args
assert _opt(docker_args, "--cap-drop") == "ALL"
assert "--download-db-only" in args
def test_tool_pins() -> None:
assert re.fullmatch(
r"aquasec/trivy:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}",
scan.TRIVY_IMAGE,
)
project = tomllib.loads(
(BASE_DIR / "pyproject.toml").read_text(encoding="utf-8"),
)
pins = [d for d in project["dependency-groups"]["dev"] if "pip-audit" in d]
assert pins == ["pip-audit==2.10.1"]
lock = tomllib.loads((BASE_DIR / "uv.lock").read_text(encoding="utf-8"))
(pkg,) = [p for p in lock["package"] if p["name"] == "pip-audit"]
assert pkg["version"] == "2.10.1" and pkg["wheels"][0]["hash"]
def test_out_inside_repository() -> None:
assert scan.inside(BASE_DIR / "evidence" / "x", BASE_DIR)
assert not scan.inside(Path("/tmp/scan-out"), BASE_DIR)