forked from mtusi2026/mtusi2026lab7
Verify every uv.lock export hash against the PyPI file digests of its release (pip-audit only requires hashes), fail on skipped dependencies and on a root operator UID, export the dev group with all extras, state the script and make exit codes like the other checks, bound Python updates by pyproject.toml in the spec, name the fix versions in triage records, cover the GSSENC path with a keytab control, and record the RabbitMQ CLI listener false FAIL of hardening_check in KNOWN_ISSUES. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
748 lines
26 KiB
Python
748 lines
26 KiB
Python
"""Команда `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 — точная версия; файл разбора
|
||
репозитория проходит проверки.
|
||
|
||
- Правки verify: сверка хэшей экспорта `uv.lock` с файлами версии PyPI
|
||
(фрагменты ответа JSON API, без сети; C1), зависимость с `skip_reason`
|
||
pip-audit — код 2 (S3), UID 0 — код 2 (S2), экспорт группы dev — с extras
|
||
(S1).
|
||
|
||
Контроль: горизонт `accepted` 90 суток вместо 30 — тест
|
||
`test_accepted_horizon` красный.
|
||
"""
|
||
|
||
import datetime as dt
|
||
import importlib.util
|
||
import re
|
||
import sys
|
||
import tomllib
|
||
import urllib.error
|
||
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_parse_pip_audit_skipped_dependency() -> None:
|
||
doc = {
|
||
"dependencies": [
|
||
{"name": "pydantic", "version": "2.13.1", "vulns": []},
|
||
{
|
||
"name": "local-pkg",
|
||
"skip_reason": "Dependency not found on PyPI",
|
||
},
|
||
],
|
||
}
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.parse_pip_audit(doc, "dev")
|
||
assert info.value.step == "pip-audit dev"
|
||
assert "local-pkg" in info.value.reason
|
||
assert "Dependency not found on PyPI" in info.value.reason
|
||
|
||
|
||
# --- сверка хэшей uv.lock с PyPI (правки verify C1) ----------------------------
|
||
|
||
H1, H2, H3 = "a" * 64, "b" * 64, "c" * 64
|
||
|
||
EXPORT = f"""\
|
||
# This file was autogenerated by uv via the following command:
|
||
# uv export --locked --no-emit-project --format requirements-txt
|
||
annotated-types==0.7.0 \\
|
||
--hash=sha256:{H1} \\
|
||
--hash=sha256:{H2}
|
||
# via pydantic
|
||
Certifi==2026.10.18 ; sys_platform != 'emscripten' \\
|
||
--hash=sha256:{H3}
|
||
# via
|
||
# httpcore
|
||
uvicorn[standard]==0.40.0 \\
|
||
--hash=sha256:{H1}
|
||
"""
|
||
|
||
# урезанный ответ https://pypi.org/pypi/<имя>/<версия>/json
|
||
PYPI_DOC = {
|
||
"info": {"name": "annotated-types", "version": "0.7.0"},
|
||
"urls": [
|
||
{"filename": "a.whl", "digests": {"md5": "x", "sha256": H1}},
|
||
{"filename": "a.tar.gz", "digests": {"sha256": H2}},
|
||
],
|
||
}
|
||
|
||
|
||
def test_parse_requirements() -> None:
|
||
reqs = scan.parse_requirements(EXPORT)
|
||
assert reqs == [
|
||
("annotated-types", "0.7.0", frozenset({H1, H2})),
|
||
("Certifi", "2026.10.18", frozenset({H3})),
|
||
("uvicorn", "0.40.0", frozenset({H1})),
|
||
]
|
||
assert scan.published_digests(PYPI_DOC) == {H1, H2}
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"line",
|
||
["-e ./local", "./wheels/x.whl", "pkg @ https://x/pkg.whl"],
|
||
)
|
||
def test_requirement_without_version_rejected(line: str) -> None:
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.parse_requirements(f"{line} \\\n --hash=sha256:{H1}\n")
|
||
assert info.value.step == "hashes"
|
||
|
||
|
||
def _fetcher(published: dict) -> tuple:
|
||
calls: list = []
|
||
|
||
def fetch(name: str, version: str) -> frozenset:
|
||
calls.append((name, version))
|
||
return frozenset(published[(name, version)])
|
||
|
||
return fetch, calls
|
||
|
||
|
||
def test_lock_hashes_match() -> None:
|
||
fetch, calls = _fetcher(
|
||
{
|
||
("annotated-types", "0.7.0"): {H1, H2, H3},
|
||
("certifi", "2026.10.18"): {H3},
|
||
("uvicorn", "0.40.0"): {H1},
|
||
},
|
||
)
|
||
reqs = scan.parse_requirements(EXPORT)
|
||
# пакет обеих групп сверяется один раз
|
||
assert scan.verify_lock_hashes([*reqs, reqs[1]], fetch) == (3, 3)
|
||
assert sorted(calls) == [
|
||
("annotated-types", "0.7.0"),
|
||
("certifi", "2026.10.18"),
|
||
("uvicorn", "0.40.0"),
|
||
]
|
||
|
||
|
||
ZERO = "0" * 64
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("lock", "published", "needle"),
|
||
[
|
||
# хэши lock обнулены — ни одного совпадения (проба verify)
|
||
({ZERO}, {H1, H2}, "1 of 1 uv.lock hashes are not published"),
|
||
# один хэш lock есть на PyPI, второго нет — тоже расхождение
|
||
({H3, ZERO}, {H3}, "1 of 2 uv.lock hashes are not published"),
|
||
# у версии нет файлов
|
||
({H3}, set(), "1 of 1 uv.lock hashes are not published"),
|
||
],
|
||
)
|
||
def test_lock_hash_mismatch(lock: set, published: set, needle: str) -> None:
|
||
reqs = [("Certifi", "2026.10.18", frozenset(lock))]
|
||
fetch, _ = _fetcher({("certifi", "2026.10.18"): published})
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.verify_lock_hashes(reqs, fetch)
|
||
assert info.value.step == "hashes"
|
||
assert info.value.reason.startswith("Certifi 2026.10.18: ")
|
||
assert needle in info.value.reason
|
||
|
||
|
||
def test_lock_without_hashes() -> None:
|
||
problems = scan.hash_problems(
|
||
[("idna", "3.11", frozenset())],
|
||
{("idna", "3.11"): frozenset({H1})},
|
||
)
|
||
assert problems == ["idna 3.11: no hashes in uv.lock"]
|
||
|
||
|
||
def test_fetch_failures_are_one_line(monkeypatch: pytest.MonkeyPatch) -> None:
|
||
def refused(*_a: object, **_k: object) -> None:
|
||
raise urllib.error.URLError(ConnectionRefusedError(61, "refused"))
|
||
|
||
monkeypatch.setattr(scan.urllib.request, "urlopen", refused)
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.fetch_digests("certifi", "2026.10.18")
|
||
assert info.value.step == "hashes"
|
||
assert info.value.reason.startswith(
|
||
"PyPI request for certifi 2026.10.18 failed:",
|
||
)
|
||
assert "\n" not in info.value.reason
|
||
|
||
def missing(request: object, **_k: object) -> None:
|
||
raise urllib.error.HTTPError(
|
||
"https://pypi.org/x",
|
||
404,
|
||
"Not Found",
|
||
None, # type: ignore[arg-type]
|
||
None,
|
||
)
|
||
|
||
monkeypatch.setattr(scan.urllib.request, "urlopen", missing)
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.fetch_digests("Certifi", "2026.10.18")
|
||
assert info.value.reason == "Certifi 2026.10.18: release is not on PyPI"
|
||
|
||
|
||
def test_dev_group_exports_extras() -> None:
|
||
groups = dict(scan.GROUPS)
|
||
assert groups["runtime"] == ("--no-dev",)
|
||
# extras (ruff) — зависимости проекта: --only-dev их не выводит
|
||
assert "--all-extras" in groups["dev"]
|
||
assert "--only-dev" not in groups["dev"]
|
||
|
||
|
||
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_root_operator_refused() -> None:
|
||
assert scan.scanner_user(501, 20) == "501:20"
|
||
with pytest.raises(scan.ScanError) as info:
|
||
scan.scanner_user(0, 0)
|
||
assert info.value.step == "user"
|
||
with pytest.raises(scan.ScanError):
|
||
scan.db_args(Path("/cache"), 0, 0, "r1")
|
||
with pytest.raises(scan.ScanError):
|
||
scan.scan_args(
|
||
archive_dir=Path("/tmp/x"),
|
||
archive="a.tar",
|
||
cache_dir=Path("/cache"),
|
||
uid=0,
|
||
gid=0,
|
||
run_id="r1",
|
||
secret_rules=None,
|
||
)
|
||
|
||
|
||
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)
|