feat: import lab 7 security implementation

This commit is contained in:
2026-12-02 23:44:32 +03:00
parent 20afc2c790
commit ee28cd7dbd
259 changed files with 84919 additions and 35 deletions
+193
View File
@@ -0,0 +1,193 @@
"""Лаба 7, перенос 15: аудит матрицы доверия `make security-audit` без стенда
(`infra/audit/audit.py`).
- Каждая строка таблицы `contracts/trust-matrix.md` — строка сводки, лишних
нет; у каждой строки есть проверки, проверки известны.
- Подкоманды `scripts/lab7.py`, которые зовёт аудит, есть в его argparse.
- «Отказ» и «нет данных» различаются: код 1 — только нарушение, код 2 — проверка
без вердикта (сбой, стенда нет, проба приватности без записей журнала).
- Строка утечек берёт из вывода `telemetry-check` только пробу приватности.
- Цель make и правило Codex.
Контроли: строка матрицы без строки аудита (или лишняя строка аудита) —
`test_missing_or_extra_row_is_named` называет её; ноль записей журнала,
посчитанный утечкой или PASS, — `test_no_log_records_is_no_data`.
"""
import importlib.util
import re
import sys
from pathlib import Path
from types import ModuleType
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[2]
AUDIT_PY = ROOT / "infra" / "audit" / "audit.py"
LAB7_PY = ROOT / "scripts" / "lab7.py"
def _load() -> ModuleType:
spec = importlib.util.spec_from_file_location("vladimirceva_audit", AUDIT_PY)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules["vladimirceva_audit"] = module
spec.loader.exec_module(module)
return module
audit = _load()
def test_matrix_rows_match_audit() -> None:
matrix = audit.matrix_edges()
assert len(matrix) == 12
assert audit.coverage_problems(matrix) == []
assert [edge.name for edge in audit.MATRIX_EDGES] == matrix
def test_missing_or_extra_row_is_named() -> None:
matrix = audit.matrix_edges()
assert audit.coverage_problems([*matrix, "Новая связь → X"]) == [
"matrix row without audit row: Новая связь → X",
]
assert audit.coverage_problems(matrix[1:]) == [
f"audit row not in matrix: {matrix[0]}",
]
broken = (
audit.Edge("Клиент → ingress/LB", (("x", "no-such-check"),)),
*audit.MATRIX_EDGES[1:],
)
assert audit.coverage_problems(matrix, broken) == [
"unknown check no-such-check in row Клиент → ingress/LB",
]
empty = (audit.Edge("Клиент → ingress/LB", ()), *audit.MATRIX_EDGES[1:])
assert audit.coverage_problems(matrix, empty) == [
"row without checks: Клиент → ingress/LB",
]
def test_matrix_parser(tmp_path: Path) -> None:
path = tmp_path / "m.md"
path.write_text(
"# M\n\n| Связь | A |\n| --- | --- |\n| X → Y | a |\n| Z | b |\n\n"
"| Связь | other |\n",
encoding="utf-8",
)
assert audit.matrix_edges(path) == ["X → Y", "Z"]
def test_lab7_commands_exist() -> None:
"""Каждая проверка аудита — подкоманда scripts/lab7.py; каждая проверка
списка доказывает хотя бы одну строку."""
text = LAB7_PY.read_text(encoding="utf-8")
parsers = set(re.findall(r'add_parser\("([a-z0-9-]+)"', text))
parsers |= {"mtls-check"} # заводится циклом уровня 4 с --base-url
assert re.search(
r'"trace-chain", "alerts-check", "telemetry-outage", "mtls-check"', text
)
commands = {command for command, _ in audit.LAB7_CHECKS.values()}
assert commands <= parsers
assert set(audit.LAB7_CHECKS) <= audit.CHECKS
used = {check for edge in audit.EDGES for _, check in edge.checks}
assert used == audit.CHECKS
assert audit.LEAK_ROW in text
PRIVACY = "no password, token, message text, filename or Authorization in telemetry"
TELEMETRY_OUT = """\
PASS provisioning
FAIL resource attributes: service.version 0.6.0
{row}
telemetry-check: FAIL (n/m checks)
"""
def _out(row: str) -> str:
return TELEMETRY_OUT.format(row=row)
def test_leaks_only_privacy_row() -> None:
clean = _out(f"PASS {PRIVACY}: 41 log records, 5123 bytes of traces")
result = audit.leaks_result(1, clean, 1.0)
assert result.code == 0
assert "resource attributes" in result.note
leaked = _out(
f"FAIL {PRIVACY}: 41 log records, 5123 bytes of traces, leaked: token in logs"
)
result = audit.leaks_result(1, leaked, 1.0)
assert result.code == 1
assert result.fails == (leaked.splitlines()[2],)
authorization = _out(
f"FAIL {PRIVACY}: 41 log records, 9 bytes of traces, Authorization in traces"
)
assert audit.leaks_result(1, authorization, 1.0).code == 1
def test_no_log_records_is_no_data() -> None:
"""Пустой Loki — не утечка (1) и не PASS (0): нет данных (2)."""
empty = _out(f"FAIL {PRIVACY}: 0 log records, 2 bytes of traces")
result = audit.leaks_result(1, empty, 1.0)
assert result.code == 2
assert "no log records" in result.note
# команда не дошла до пробы или упала без вердикта
assert audit.leaks_result(1, "FAIL provisioning\n", 1.0).code == 2
assert audit.leaks_result(2, "", 1.0).code == 2
assert audit.leaks_result(137, _out(f"PASS {PRIVACY}: 4 log"), 1.0).code == 2
def test_refusal_and_no_data_are_different_codes() -> None:
"""Код 1 проверки — FAIL строки, любой другой ненулевой — ERROR (нет
вердикта), аудит в целом: 1 важнее 2."""
fail = audit.check_result("mtls-check", 1, "FAIL identity haproxy\n", 1.0)
assert (fail.code, fail.fails) == (1, ("FAIL identity haproxy",))
assert audit.check_result("bao-check", 2, "OpenBao is sealed\n", 1.0).code == 2
assert audit.check_result("s3-check", 137, "", 1.0).code == 2
assert audit.check_result("test-security", 1, "FAIL: unexpected\n", 1.0).code == 1
assert audit.check_result("test-security", 1, "Traceback\n", 1.0).code == 2
ok, bad, err = audit.Result(0, 1.0), audit.Result(1, 1.0), audit.Result(2, 1.0)
assert audit.audit_code({"a": ok, "b": ok}) == 0
assert audit.audit_code({"a": ok, "b": err}) == 2
assert audit.audit_code({"a": err, "b": bad}) == 1
assert audit.verdict(2) == "ERROR"
def test_fail_lines_both_formats() -> None:
"""Строки нарушения в обоих форматах scripts/lab7.py: `FAIL …` (Checks) и
строка таблицы, кончающаяся на FAIL; итоговая строка — не нарушение."""
out = (
"PASS ok row\n"
"FAIL bad row: detail\n"
"host localhost anonymous get object 403 200 FAIL\n"
"host localhost anonymous put object 403 403 ok\n"
"mtls-check: FAIL (1/3 checks, 2 s)\n"
)
assert audit.fail_lines(out) == (
"FAIL bad row: detail",
"host localhost anonymous get object 403 200 FAIL",
)
def test_row_verdict() -> None:
edge = audit.Edge("e", (("a", "mtls-check"), ("b", "s3-check")))
ok = audit.Result(0, 1.0)
assert audit.row_verdict(edge, {}) == "not run"
assert audit.row_verdict(edge, {"mtls-check": ok}) == "PASS (partial)"
assert audit.row_verdict(edge, {"mtls-check": ok, "s3-check": ok}) == "PASS"
bad = audit.Result(1, 1.0)
err = audit.Result(2, 1.0)
assert audit.row_verdict(edge, {"mtls-check": err, "s3-check": bad}) == "FAIL"
assert audit.row_verdict(edge, {"mtls-check": err, "s3-check": ok}) == "ERROR"
def test_make_target_and_codex_rule() -> None:
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
assert re.search(
r"^security-audit:\n\t\$\(PYTHON\) infra/audit/audit.py ", makefile, re.M
)
assert '"security-audit"' in rules
assert '"make security-audit"' in rules