fix: address vulnerability-scan verify findings

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>
This commit is contained in:
2026-11-27 13:40:06 +03:00
co-authored by Claude Opus 5.5
parent 3e0d39ff05
commit fe30334ee7
16 changed files with 809 additions and 83 deletions
+187
View File
@@ -15,6 +15,11 @@
- Ссылка 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` красный.
"""
@@ -24,6 +29,7 @@ import importlib.util
import re
import sys
import tomllib
import urllib.error
from pathlib import Path
from types import ModuleType
@@ -233,6 +239,168 @@ def test_parse_pip_audit_merges_duplicates() -> None:
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}
@@ -530,6 +698,25 @@ def test_scan_container_isolated(rules: Path | None) -> 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)]