forked from mtusi2026/mtusi2026lab7
- narrow the worker S3 user to staging reads and attachments writes - add database rules the worker role cannot bypass: no return to pending, variant keys of its own attachment, known error codes only - let the cleaner remove a ready source only after its own SHA-256 check - add make jobs_audit [REPAIR=1] to name and requeue damaged jobs - add make worker_compromise: isolated before/after stands, one operation table, response windows, job safety, controls and committed hypotheses Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1448 lines
48 KiB
Python
1448 lines
48 KiB
Python
"""Учения «Компрометация worker» (change `track1-worker-compromise`, design,
|
||
решения 2, 4, 9–11, 13; спек `worker-compromise`): `infra/track1/` без docker.
|
||
|
||
- Ожидания «после» таблицы операций = источники прав: матрица ролей
|
||
PostgreSQL, права брокера, политики OpenBao, политика S3 bootstrap. Таблица не
|
||
может разойтись с кодом, а ожидание — быть подогнанным под прогон.
|
||
- Исходы пробника: код отказа, а не «любая ошибка».
|
||
- Окна, контрольные числа, вердикты — на записях-примерах: каждый порог один
|
||
делает вердикт отрицательным.
|
||
- Override стендов: ни рабочего имени, ни тега, ни порта вне 127.0.0.1, ни тома.
|
||
- Предусловия — код 2 до любых действий; сигнал — уборка; секреты — только
|
||
stdin, в argv, окружении и отчёте их нет.
|
||
"""
|
||
|
||
import importlib.util
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
from types import ModuleType, SimpleNamespace
|
||
from typing import Any
|
||
|
||
import pytest
|
||
import yaml
|
||
|
||
from src.config.settings import BASE_DIR
|
||
from src.infra.db import roles
|
||
|
||
TRACK_DIR = BASE_DIR / "infra" / "track1"
|
||
POLICIES = BASE_DIR / "infra" / "openbao" / "policies"
|
||
BROKER_START = BASE_DIR / "infra" / "rabbitmq" / "start.sh"
|
||
S3_BOOTSTRAP = BASE_DIR / "infra" / "s3" / "bootstrap.sh"
|
||
COMPOSE = BASE_DIR / "docker-compose.yml"
|
||
SECRET = "sentinel-secret-value-0123456789"
|
||
|
||
|
||
def _load(name: str) -> ModuleType:
|
||
"""Модули учений импортируют друг друга по имени, как скрипт."""
|
||
if str(TRACK_DIR) not in sys.path:
|
||
sys.path.insert(0, str(TRACK_DIR))
|
||
if name in sys.modules:
|
||
return sys.modules[name]
|
||
spec = importlib.util.spec_from_file_location(
|
||
name,
|
||
TRACK_DIR / f"{name}.py",
|
||
)
|
||
assert spec is not None and spec.loader is not None
|
||
module = importlib.util.module_from_spec(spec)
|
||
sys.modules[name] = module
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
ops = _load("operations")
|
||
analysis = _load("analysis")
|
||
stand = _load("stand")
|
||
probe = _load("probe")
|
||
track1 = _load("track1")
|
||
ROWS = {row.id: row for row in ops.OPERATIONS}
|
||
HYPOTHESES = json.loads((TRACK_DIR / "hypotheses.json").read_text("utf-8"))
|
||
LIMITS = {
|
||
name: item["thresholds"] for name, item in HYPOTHESES["hypotheses"].items()
|
||
}
|
||
|
||
|
||
# таблица против источников прав -----------------------------------------------
|
||
|
||
|
||
def _pg_expected() -> dict[str, bool]:
|
||
"""Строка `pg.<операция>.<таблица>[.<колонка>]` → доступна по матрице."""
|
||
matrix = roles.MATRIX[roles.WORKER_ROLE]
|
||
found = {}
|
||
for table in (*roles.TABLES, "alembic_version"):
|
||
grant = matrix.get(table, roles.NO_GRANT)
|
||
found[f"pg.select.{table}"] = grant.select
|
||
found[f"pg.insert.{table}"] = grant.insert
|
||
found[f"pg.delete.{table}"] = grant.delete
|
||
for column in grant.update:
|
||
found[f"pg.update.{table}.{column}"] = True
|
||
return found
|
||
|
||
|
||
def test_postgres_rows_match_roles_matrix() -> None:
|
||
expected = _pg_expected()
|
||
table_rows = {
|
||
name: row
|
||
for name, row in ROWS.items()
|
||
if re.match(r"pg\.(select|insert|delete|update)\.", name)
|
||
}
|
||
for name, allowed in expected.items():
|
||
assert name in table_rows, name
|
||
got = table_rows.pop(name).after
|
||
assert got == (ops.OK if allowed else ops.INSUFFICIENT), name
|
||
# остальные — по одной чужой колонке каждой таблицы, и все запрещены
|
||
assert {name.split(".")[2] for name in table_rows} == {
|
||
*roles.TABLES,
|
||
"alembic_version",
|
||
}
|
||
assert all(row.after == ops.INSUFFICIENT for row in table_rows.values())
|
||
for name in table_rows:
|
||
_, _, table, column = name.split(".")
|
||
grant = roles.MATRIX[roles.WORKER_ROLE].get(table, roles.NO_GRANT)
|
||
assert column not in grant.update, name
|
||
|
||
|
||
def test_postgres_scope_is_pipeline_tables() -> None:
|
||
"""«Своё» — ровно таблицы, где у роли есть права."""
|
||
own = {
|
||
table
|
||
for table, grant in roles.MATRIX[roles.WORKER_ROLE].items()
|
||
if not grant.is_empty
|
||
}
|
||
assert set(ops.PIPELINE_TABLES) == own
|
||
|
||
|
||
# право брокера, которого требует действие (RabbitMQ, «Access Control»)
|
||
MQ_NEEDS = {
|
||
"passive": "read",
|
||
"get": "read",
|
||
"reject": "read",
|
||
"consume": "read",
|
||
"purge": "read",
|
||
"publish": "write",
|
||
"declare": "configure",
|
||
"declare-new": "configure",
|
||
"declare-exclusive": "configure",
|
||
"bind": "write",
|
||
"exchange": "configure",
|
||
"delete": "configure",
|
||
}
|
||
|
||
|
||
def _broker_permissions() -> dict[str, str]:
|
||
"""Права пользователя worker из определений start.sh (namespace
|
||
messenger)."""
|
||
text = BROKER_START.read_text(encoding="utf-8")
|
||
pattern = re.search(r'^queue_pattern="(.+)"$', text, re.M)
|
||
assert pattern is not None
|
||
queue = (
|
||
pattern.group(1)
|
||
.replace("$namespace", "messenger")
|
||
.replace("\\\\\\\\", "\\")
|
||
.replace("\\$", "$")
|
||
)
|
||
block = re.search(
|
||
r'\{"user": "worker", "vhost": "/",\s+"configure": "(.+)",\s+'
|
||
r'"write": "(.+)",\s+"read": "(.+)"\}',
|
||
text,
|
||
)
|
||
assert block is not None
|
||
names = ("configure", "write", "read")
|
||
return {
|
||
name: value.replace("$queue_pattern", queue)
|
||
.replace("\\\\\\\\", "\\")
|
||
.replace("\\$", "$")
|
||
for name, value in zip(names, block.groups(), strict=True)
|
||
}
|
||
|
||
|
||
def test_broker_rows_match_permissions() -> None:
|
||
permissions = _broker_permissions()
|
||
queues = {
|
||
"{queue}": "messenger.attachment.process.v1",
|
||
"{other_queue}": track1.OTHER_QUEUE,
|
||
}
|
||
rows = [row for row in ops.OPERATIONS if row.channel == "RabbitMQ"]
|
||
assert {row.args["action"] for row in rows} == set(MQ_NEEDS)
|
||
for row in rows:
|
||
name = queues.get(row.args["queue"], row.args["queue"])
|
||
if row.args["action"] == "publish":
|
||
# право write — на exchange; безымянный называется amq.default
|
||
name = row.args["exchange"] or "amq.default"
|
||
pattern = permissions[MQ_NEEDS[row.args["action"]]]
|
||
allowed = re.fullmatch(pattern, name) is not None
|
||
assert row.after == (ops.OK if allowed else ops.REFUSED), row.id
|
||
assert (
|
||
row.scope
|
||
== (ops.OWN if row.args["queue"] == "{queue}" else ops.OUTSIDE)
|
||
or row.id == "mq.publish.topic"
|
||
)
|
||
|
||
|
||
def _policy(name: str) -> dict[str, set[str]]:
|
||
text = (POLICIES / f"{name}.hcl").read_text(encoding="utf-8")
|
||
found = re.findall(
|
||
r'^path "([^"]+)" \{\s+capabilities = \[([^\]]*)\]',
|
||
text,
|
||
re.M,
|
||
)
|
||
return {path: set(re.findall(r'"(\w+)"', caps)) for path, caps in found}
|
||
|
||
|
||
def test_openbao_rows_match_policy() -> None:
|
||
policy = _policy("worker")
|
||
need = {"GET": "read", "POST": "update", "DELETE": "delete"}
|
||
for row in ops.OPERATIONS:
|
||
if row.channel != "OpenBao" or "login" in row.args:
|
||
continue
|
||
path, _, query = row.args["path"].partition("?")
|
||
wanted = "list" if query == "list=true" else need[row.args["method"]]
|
||
allowed = wanted in policy.get(path, set())
|
||
assert row.after == (ops.OK if allowed else ops.FORBIDDEN), row.id
|
||
|
||
|
||
def test_openbao_rows_cover_every_secret_path() -> None:
|
||
paths = {
|
||
path.removeprefix("messenger/data/")
|
||
for file in POLICIES.glob("*.hcl")
|
||
for path in _policy(file.stem)
|
||
if path.startswith("messenger/data/")
|
||
}
|
||
assert {*ops.OWN_PATHS, *ops.FOREIGN_PATHS} == paths
|
||
assert set(ops.OWN_PATHS) == {
|
||
path.removeprefix("messenger/data/")
|
||
for path in _policy("worker")
|
||
if path.startswith("messenger/data/")
|
||
}
|
||
|
||
|
||
def _worker_s3_policy(tmp_path: Path) -> dict[str, Any]:
|
||
"""JSON политики worker — функциями самого bootstrap.sh, без сервера."""
|
||
text = S3_BOOTSTRAP.read_text(encoding="utf-8")
|
||
functions = []
|
||
for name in ("worker_databases", "worker_resources", "put_worker_policy"):
|
||
found = re.search(rf"^{name}\(\) \{{\n.*?^\}}$", text, re.M | re.S)
|
||
assert found is not None, name
|
||
functions.append(found.group(0))
|
||
script = "\n".join(
|
||
(
|
||
"set -eu",
|
||
f"WORK={tmp_path}",
|
||
"BUCKET=messenger",
|
||
"LIST_PREFIX=messenger/attachments/",
|
||
"WORKER_POLICY=worker-objects",
|
||
"ws_step() { :; }",
|
||
*functions,
|
||
"put_worker_policy",
|
||
),
|
||
)
|
||
subprocess.run(["/bin/sh", "-c", script], check=True)
|
||
return json.loads((tmp_path / "policy.json").read_text("utf-8"))
|
||
|
||
|
||
def _allows(policy: dict[str, Any], action: str, key: str) -> bool:
|
||
return any(
|
||
action in item["Action"]
|
||
and any(
|
||
f"arn:aws:s3:::messenger/{key}".startswith(
|
||
resource.removesuffix("*"),
|
||
)
|
||
for resource in item["Resource"]
|
||
)
|
||
for item in policy["Statement"]
|
||
)
|
||
|
||
|
||
def test_s3_rows_match_policy(tmp_path: Path) -> None:
|
||
policy = _worker_s3_policy(tmp_path)
|
||
params = {"db": "messenger", "probe": track1.PROBE_ID, "bucket": "m"}
|
||
checked = 0
|
||
for row in ops.OPERATIONS:
|
||
args = probe.substitute(row.args, params)
|
||
if (
|
||
row.channel != "S3"
|
||
or args.get("bucket") is not None
|
||
or not args["key"]
|
||
or ".." in args["key"]
|
||
or ".." in args.get("copy", "")
|
||
# форму и ACL политика по объектам не описывает
|
||
or args["method"] == "FORM"
|
||
or "acl" in args.get("query", "")
|
||
):
|
||
continue
|
||
checked += 1
|
||
action = {
|
||
"GET": "s3:GetObject",
|
||
"HEAD": "s3:GetObject",
|
||
"PUT": "s3:PutObject",
|
||
"POST": "s3:PutObject",
|
||
"DELETE": "s3:DeleteObject",
|
||
}[args["method"]]
|
||
allowed = _allows(policy, action, args["key"])
|
||
if args.get("copy"):
|
||
allowed = allowed and _allows(policy, "s3:GetObject", args["copy"])
|
||
want = ops.OK
|
||
if not allowed:
|
||
want = (
|
||
ops.denied("403")
|
||
if args["method"] == "HEAD"
|
||
else ops.ACCESS_DENIED
|
||
)
|
||
assert row.after == want, row.id
|
||
assert checked >= 18
|
||
|
||
|
||
def test_s3_policy_is_prefixes_only(tmp_path: Path) -> None:
|
||
policy = _worker_s3_policy(tmp_path)
|
||
assert policy["Statement"] == [
|
||
{
|
||
"Effect": "Allow",
|
||
"Action": ["s3:GetObject"],
|
||
"Resource": [
|
||
"arn:aws:s3:::messenger/messenger/staging/*",
|
||
"arn:aws:s3:::messenger/test_messenger/staging/*",
|
||
],
|
||
},
|
||
{
|
||
"Effect": "Allow",
|
||
"Action": ["s3:PutObject"],
|
||
"Resource": [
|
||
"arn:aws:s3:::messenger/messenger/attachments/*",
|
||
"arn:aws:s3:::messenger/test_messenger/attachments/*",
|
||
],
|
||
},
|
||
]
|
||
|
||
|
||
def test_every_available_row_is_explained() -> None:
|
||
"""Доступная «после» — нужна коду либо остаточный риск; вне своего — нет
|
||
ни одной; запрещённая основания не имеет."""
|
||
outcomes = re.compile(r"ok|n/a|denied:[A-Za-z0-9_-]+")
|
||
for row in ops.OPERATIONS:
|
||
assert outcomes.fullmatch(row.before), row.id
|
||
assert outcomes.fullmatch(row.after), row.id
|
||
assert row.kind in probe.KINDS, row.id
|
||
if row.after == ops.OK:
|
||
assert row.why and row.why[0] in (ops.CODE, ops.RESIDUAL), row.id
|
||
assert row.scope != ops.OUTSIDE, row.id
|
||
assert row.before in (ops.OK, ops.NA), row.id
|
||
else:
|
||
assert row.why == (), row.id
|
||
assert len(ROWS) == len(ops.OPERATIONS) >= 150
|
||
|
||
|
||
def test_table_covers_spec_channels() -> None:
|
||
assert {row.channel for row in ops.OPERATIONS} == {
|
||
"S3",
|
||
"RabbitMQ",
|
||
"PostgreSQL",
|
||
"OpenBao",
|
||
"Сеть",
|
||
"Процесс",
|
||
}
|
||
|
||
|
||
# исходы пробника ----------------------------------------------------------------
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("status", "body", "expected"),
|
||
[
|
||
(200, b"object", "ok"),
|
||
(204, b"", "ok"),
|
||
(403, b"", "denied:403"),
|
||
(
|
||
403,
|
||
b"<?xml version='1.0'?><Error><Code>AccessDenied</Code></Error>",
|
||
"denied:AccessDenied",
|
||
),
|
||
(
|
||
200,
|
||
b"<DeleteResult><Error><Key>k</Key><Code>AccessDenied</Code>"
|
||
b"</Error></DeleteResult>",
|
||
"denied:AccessDenied",
|
||
),
|
||
(
|
||
200,
|
||
b"<DeleteResult><Deleted><Key>k</Key></Deleted></DeleteResult>",
|
||
"ok",
|
||
),
|
||
(
|
||
400,
|
||
b"<Error><Code>InvalidRequest</Code></Error>",
|
||
"denied:400",
|
||
),
|
||
# истёкший ключ — не запрет операции
|
||
(
|
||
403,
|
||
b"<Error><Code>InvalidAccessKeyId</Code></Error>",
|
||
"denied:InvalidAccessKeyId",
|
||
),
|
||
(404, b"<Error><Code>NoSuchKey</Code></Error>", "denied:NoSuchKey"),
|
||
(500, b"<Error><Code>InternalError</Code></Error>", "denied:500"),
|
||
],
|
||
)
|
||
def test_s3_outcome(status: int, body: bytes, expected: str) -> None:
|
||
assert probe.s3_outcome(status, body) == expected
|
||
|
||
|
||
def test_outcome_names_code_not_text() -> None:
|
||
error = RuntimeError(SECRET)
|
||
assert probe.outcome_of(error) == "denied:RuntimeError"
|
||
error.sqlstate = "42501" # type: ignore[attr-defined]
|
||
assert probe.outcome_of(error) == "denied:42501"
|
||
assert probe.outcome_of(ConnectionRefusedError()) == "denied:closed"
|
||
assert probe.outcome_of(ConnectionResetError()) == "denied:reset"
|
||
|
||
|
||
def test_broker_outcomes() -> None:
|
||
import aiormq.exceptions as errors
|
||
|
||
assert (
|
||
probe.mq_outcome(errors.ChannelAccessRefused())
|
||
== "denied:ACCESS_REFUSED"
|
||
)
|
||
# право есть, отказ по условию
|
||
assert probe.mq_outcome(errors.ChannelPreconditionFailed()) == "ok"
|
||
assert (
|
||
probe.mq_outcome(errors.ChannelNotFoundEntity()) == "denied:NOT_FOUND"
|
||
)
|
||
assert (
|
||
probe.mq_outcome(errors.AMQPConnectionError())
|
||
== "denied:AMQPConnectionError"
|
||
)
|
||
|
||
|
||
def test_substitute_reaches_nested_values() -> None:
|
||
got = probe.substitute(
|
||
{"a": "{x}/{y}", "b": {"c": "{x}"}, "n": 1},
|
||
{"x": "1", "y": 2},
|
||
)
|
||
assert got == {"a": "1/2", "b": {"c": "1"}, "n": 1}
|
||
|
||
|
||
# строки таблицы -----------------------------------------------------------------
|
||
|
||
|
||
def _as_expected(column: str) -> dict[str, str]:
|
||
return {row.id: getattr(row, column) for row in ops.OPERATIONS}
|
||
|
||
|
||
def test_table_diff_names_every_deviation() -> None:
|
||
before, after = _as_expected("before"), _as_expected("after")
|
||
assert analysis.table_diff(ops.OPERATIONS, before, after) == ([], [])
|
||
after["pg.select.users"] = ops.OK
|
||
del after["s3.get.attachments"]
|
||
before["mq.get.own"] = "denied:timeout"
|
||
diff = analysis.table_diff(ops.OPERATIONS, before, after)
|
||
assert diff.before == [("mq.get.own", "ok", "denied:timeout")]
|
||
assert sorted(diff.after) == [
|
||
("pg.select.users", ops.INSUFFICIENT, "ok"),
|
||
("s3.get.attachments", ops.ACCESS_DENIED, "missing"),
|
||
]
|
||
|
||
|
||
def test_other_refusal_is_a_deviation() -> None:
|
||
"""Отказ другим кодом (таймаут, сеть) запрета не доказывает."""
|
||
after = {**_as_expected("after"), "pg.select.users": "denied:timeout"}
|
||
diff = analysis.table_diff(ops.OPERATIONS, {}, after)
|
||
assert [row for row, _, _ in diff.after] == ["pg.select.users"]
|
||
assert diff.before == []
|
||
|
||
|
||
def test_opened_names_extra_rows() -> None:
|
||
after = {**_as_expected("after"), "s3.put.staging": "ok"}
|
||
assert analysis.opened(ops.OPERATIONS, after) == ["s3.put.staging"]
|
||
|
||
|
||
def test_closed_counts() -> None:
|
||
before, after = _as_expected("before"), _as_expected("after")
|
||
found = analysis.closed(ops.OPERATIONS, before, after)
|
||
assert found.available_before == found.closed + len(found.both)
|
||
assert found.share >= LIMITS["H1"]["closed_share_min"]
|
||
assert found.outside == []
|
||
after["net.api.users"] = "ok"
|
||
found = analysis.closed(ops.OPERATIONS, before, after)
|
||
assert found.outside == ["net.api.users"]
|
||
assert analysis.closed(ops.OPERATIONS, {}, after).share == 0.0
|
||
|
||
|
||
# окна ---------------------------------------------------------------------------
|
||
|
||
MARKS = {
|
||
"start": 0.0,
|
||
"t0": 5.0,
|
||
"begin:revoke": 5.1,
|
||
"end:revoke": 30.0,
|
||
"begin:secret": 30.1,
|
||
"end:secret": 45.0,
|
||
"settled": 49.0,
|
||
"stop": 49.5,
|
||
}
|
||
|
||
|
||
def _samples(last: float, *, step: float = 0.5, until: float = 49.0) -> list:
|
||
"""Каждый материал: успех до `last`, дальше отказ."""
|
||
found = []
|
||
t = 0.0
|
||
while t <= until:
|
||
for name in analysis.MATERIALS:
|
||
found.append((t, name, "ok" if t <= last else "denied:x"))
|
||
t += step
|
||
return found
|
||
|
||
|
||
def test_window_is_last_success_from_t0() -> None:
|
||
found = analysis.windows(_samples(17.0), MARKS)
|
||
assert {item.material for item in found} == set(analysis.MATERIALS)
|
||
for item in found:
|
||
assert item.seconds == 12.0
|
||
assert item.command == "revoke"
|
||
assert not item.after_last
|
||
|
||
|
||
def test_window_names_the_command() -> None:
|
||
found = analysis.windows(_samples(35.0), MARKS)
|
||
assert found[0].command == "secret"
|
||
assert found[0].seconds == 30.0
|
||
|
||
|
||
def test_window_before_t0_is_zero() -> None:
|
||
found = analysis.windows(_samples(4.0), MARKS)
|
||
assert found[0].seconds == 0.0
|
||
assert not found[0].after_last
|
||
|
||
|
||
def test_material_working_after_the_last_command() -> None:
|
||
found = analysis.windows(_samples(47.0), MARKS)
|
||
assert found[0].after_last
|
||
limits = dict.fromkeys(analysis.MATERIALS, 1000)
|
||
problems = analysis.window_problems(found, limits)
|
||
assert len(problems) == len(analysis.MATERIALS)
|
||
assert "works after the last command" in problems[0]
|
||
|
||
|
||
def test_material_never_measured_is_a_problem() -> None:
|
||
"""Ни одного успеха — проба не работала, а не «окно ноль»; нет проб после
|
||
начала порядка — тоже."""
|
||
limits = dict.fromkeys(analysis.MATERIALS, 1000)
|
||
silent = [item for item in _samples(17.0) if item[1] != "s3_key"]
|
||
dead = [(t, n, "denied:x") for t, n, _ in _samples(17.0)]
|
||
early = [item for item in _samples(17.0) if item[0] < 5.0]
|
||
for samples, broken in (
|
||
(silent, {"s3_key"}),
|
||
(dead, set(analysis.MATERIALS)),
|
||
(early, set(analysis.MATERIALS)),
|
||
):
|
||
found = analysis.windows(samples, MARKS)
|
||
assert {item.material for item in found if item.seconds is None} == (
|
||
broken
|
||
)
|
||
problems = analysis.window_problems(found, limits)
|
||
assert len(problems) == len(broken)
|
||
assert all("window unknown" in text for text in problems)
|
||
|
||
|
||
def test_window_over_its_limit() -> None:
|
||
found = analysis.windows(_samples(17.0), MARKS)
|
||
limits = dict.fromkeys(analysis.MATERIALS, 12)
|
||
assert analysis.window_problems(found, limits) == []
|
||
limits["pg_open"] = 11
|
||
assert analysis.window_problems(found, limits) == [
|
||
"pg_open: 12.0 s > 11 s",
|
||
]
|
||
|
||
|
||
def test_damage_during_the_response() -> None:
|
||
samples = [
|
||
(1.0, "damage_rows", "ok:2"),
|
||
(6.0, "damage_rows", "ok:0"),
|
||
(20.0, "damage_rows", "ok:3"),
|
||
(21.0, "damage_queue", "ok"),
|
||
(40.0, "damage_rows", "denied:28P01"),
|
||
(40.0, "pg_new", "ok"),
|
||
]
|
||
found = analysis.damage(samples, MARKS)
|
||
assert found == analysis.Damage(5, 1, 16.0, False)
|
||
late = [*samples, (46.0, "damage_queue", "ok")]
|
||
assert analysis.damage(late, MARKS).after_last
|
||
assert analysis.damage([], MARKS) == analysis.Damage(0, 0, 0.0, False)
|
||
|
||
|
||
def test_hypotheses_limit_every_material() -> None:
|
||
windows = LIMITS["H2"]["windows_seconds"]
|
||
assert set(windows) == set(analysis.MATERIALS) == set(analysis.TITLES)
|
||
assert set(HYPOTHESES["hypotheses"]) == set(analysis.HYPOTHESES)
|
||
assert HYPOTHESES["min_rounds"] >= 3
|
||
assert HYPOTHESES["before_commit"] == "089d786"
|
||
for item in HYPOTHESES["hypotheses"].values():
|
||
assert item["text"].strip()
|
||
|
||
|
||
# сохранность --------------------------------------------------------------------
|
||
|
||
|
||
def _accepted(count: int = 3) -> list:
|
||
return [analysis.Accepted(f"id{n}", f"sha{n}", "B") for n in range(count)]
|
||
|
||
|
||
def _final(items: list, **changes: Any) -> dict:
|
||
found = {
|
||
item.id: analysis.Final("ready", item.sha256, 3, 1, 1)
|
||
for item in items
|
||
}
|
||
found["id0"] = found["id0"]._replace(**changes)
|
||
return found
|
||
|
||
|
||
def test_tally_of_untouched() -> None:
|
||
items = _accepted()
|
||
assert analysis.tally(items, _final(items)) == (3, 3, [], [], [])
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("changes", "kind"),
|
||
[
|
||
({"status": "queued"}, "lost"),
|
||
({"status": "failed"}, "lost"),
|
||
({"variants": 2}, "lost"),
|
||
({"sha256": "other"}, "wrong"),
|
||
({"rows": 2}, "duplicated"),
|
||
({"jobs": 2}, "duplicated"),
|
||
({"jobs": 0}, "duplicated"),
|
||
],
|
||
)
|
||
def test_tally_names_damaged(changes: dict[str, Any], kind: str) -> None:
|
||
items = _accepted()
|
||
found = analysis.tally(items, _final(items, **changes))
|
||
assert getattr(found, kind) == ["id0"]
|
||
for other in {"lost", "wrong", "duplicated"} - {kind}:
|
||
assert getattr(found, other) == []
|
||
|
||
|
||
def test_tally_counts_absent_as_lost() -> None:
|
||
items = _accepted()
|
||
final = _final(items)
|
||
del final["id1"]
|
||
assert analysis.tally(items, final).lost == ["id1"]
|
||
|
||
|
||
def test_missed_damage() -> None:
|
||
planted = {"a": ("stuck_time",), "b": ("false_success",)}
|
||
assert analysis.missed_damage(planted, {"a": ("stuck_time",)}) == ["b"]
|
||
# названо другим классом — не найдено
|
||
assert analysis.missed_damage(
|
||
planted,
|
||
{"a": ("attempt_number",), "b": ("false_success", "stuck_time")},
|
||
) == ["a"]
|
||
|
||
|
||
# вердикты -----------------------------------------------------------------------
|
||
|
||
|
||
def _h1(**changes: Any) -> Any:
|
||
diff = analysis.TableDiff(
|
||
changes.get("before", []),
|
||
changes.get("after", []),
|
||
)
|
||
comparison = analysis.Closed(
|
||
changes.get("available", 100),
|
||
changes.get("closed", 70),
|
||
[],
|
||
changes.get("outside", []),
|
||
)
|
||
return analysis.verdict_h1(LIMITS["H1"], diff, comparison)
|
||
|
||
|
||
def test_h1_thresholds() -> None:
|
||
assert _h1().ok
|
||
assert not _h1(after=[("x", "a", "b")]).ok
|
||
assert not _h1(before=[("x", "a", "b")]).ok
|
||
assert not _h1(closed=66).ok
|
||
assert _h1(closed=67).ok
|
||
assert not _h1(outside=["x"]).ok
|
||
assert not _h1(available=0, closed=0).ok
|
||
assert "70 of 100" in _h1().measured
|
||
|
||
|
||
def _h2(last: float = 17.0, **changes: Any) -> Any:
|
||
rounds = [analysis.windows(_samples(last), MARKS)] * changes.get(
|
||
"rounds",
|
||
3,
|
||
)
|
||
return analysis.verdict_h2(
|
||
LIMITS["H2"],
|
||
rounds,
|
||
changes.get("failed", 0),
|
||
changes.get("requests", 100),
|
||
min_rounds=3,
|
||
)
|
||
|
||
|
||
def test_h2_thresholds() -> None:
|
||
assert _h2().ok
|
||
assert not _h2(rounds=2).ok
|
||
assert not _h2(failed=1).ok
|
||
# нагрузка без запросов — не «0 неуспешных»
|
||
assert not _h2(requests=0).ok
|
||
# 15 с брокера и OpenBao превышены
|
||
verdict = _h2(last=21.0)
|
||
assert not verdict.ok
|
||
assert "round 1: amqp_new: 16.0 s > 15 s" in verdict.measured
|
||
assert "s3_key: 16" not in verdict.measured
|
||
one_bad = [
|
||
analysis.windows(_samples(17.0), MARKS),
|
||
analysis.windows(_samples(21.0), MARKS),
|
||
analysis.windows(_samples(17.0), MARKS),
|
||
]
|
||
verdict = analysis.verdict_h2(LIMITS["H2"], one_bad, 0, 9, min_rounds=3)
|
||
assert not verdict.ok
|
||
assert "round 2" in verdict.measured
|
||
|
||
|
||
def _tally(**changes: Any) -> Any:
|
||
base = {
|
||
"accepted": 10,
|
||
"ready": 10,
|
||
"lost": [],
|
||
"duplicated": [],
|
||
"wrong": [],
|
||
}
|
||
return analysis.Tally(**{**base, **changes})
|
||
|
||
|
||
def test_h3_thresholds() -> None:
|
||
def verdict(*tallies: Any, source: int = 0, ready: Any = (50.0,)) -> Any:
|
||
return analysis.verdict_h3(
|
||
LIMITS["H3"],
|
||
list(tallies),
|
||
source,
|
||
list(ready),
|
||
)
|
||
|
||
assert verdict(_tally()).ok
|
||
assert not verdict(_tally(), _tally(lost=["x"])).ok
|
||
assert not verdict(_tally(duplicated=["x"])).ok
|
||
assert not verdict(_tally(wrong=["x"])).ok
|
||
assert not verdict(_tally(), source=1).ok
|
||
assert not verdict(_tally(), ready=(50.0, 121.0)).ok
|
||
assert not verdict(_tally(), ready=(float("inf"),)).ok
|
||
assert not verdict(_tally(), ready=()).ok
|
||
assert not verdict(_tally(accepted=0, ready=0)).ok
|
||
assert "lost 1" in verdict(_tally(lost=["x"])).measured
|
||
|
||
|
||
def test_h4_thresholds() -> None:
|
||
base = {
|
||
"planted": 11,
|
||
"missed": 0,
|
||
"left": 0,
|
||
"overwritten": 1,
|
||
"overwrites_found": 1,
|
||
}
|
||
|
||
def verdict(**changes: int) -> Any:
|
||
return analysis.verdict_h4(LIMITS["H4"], **{**base, **changes})
|
||
|
||
assert verdict().ok
|
||
assert not verdict(missed=1).ok
|
||
assert not verdict(left=1).ok
|
||
assert not verdict(overwrites_found=0).ok
|
||
assert not verdict(planted=0).ok
|
||
assert not verdict(overwritten=0, overwrites_found=0).ok
|
||
|
||
|
||
def test_h5_thresholds() -> None:
|
||
lost = {"a": 1, "b": 1}
|
||
actions = {"read": True, "write": True}
|
||
|
||
def verdict(one: dict, two: dict) -> Any:
|
||
return analysis.verdict_h5(LIMITS["H5"], one, two)
|
||
|
||
assert verdict(lost, actions).ok
|
||
assert not verdict({**lost, "b": 0}, actions).ok
|
||
bad = verdict(lost, {**actions, "write": False})
|
||
assert not bad.ok
|
||
assert "not done: write" in bad.measured
|
||
assert not verdict({}, actions).ok
|
||
assert not verdict(lost, {}).ok
|
||
|
||
|
||
# классы атаки -------------------------------------------------------------------
|
||
|
||
|
||
def test_attack_covers_every_class() -> None:
|
||
"""Учения портят по строке каждого класса сверки и называют классы теми же
|
||
именами, что SQL."""
|
||
sql = (BASE_DIR / "infra" / "incident" / "jobs_audit.sql").read_text(
|
||
"utf-8",
|
||
)
|
||
known = set(re.findall(r"\(\d, '(\w+)', i\.", sql))
|
||
planted = {
|
||
name
|
||
for _, classes in (
|
||
*track1.ATTACK_SQL.values(),
|
||
*track1.ATTACK_VERIFIED.values(),
|
||
)
|
||
for name in classes
|
||
}
|
||
assert planted == known
|
||
for statements, _ in (
|
||
*track1.ATTACK_SQL.values(),
|
||
*track1.ATTACK_VERIFIED.values(),
|
||
):
|
||
for text in track1.format_sql(
|
||
statements,
|
||
id="ID",
|
||
job="JOB",
|
||
db="messenger",
|
||
):
|
||
assert "{" not in text
|
||
assert "ID" in text or "JOB" in text
|
||
|
||
|
||
def test_attack_uses_only_granted_columns() -> None:
|
||
"""Классы порчи — в пределах прав роли: иначе они не доказали бы ничего."""
|
||
matrix = roles.MATRIX[roles.WORKER_ROLE]
|
||
for statements, _ in (
|
||
*track1.ATTACK_SQL.values(),
|
||
*track1.ATTACK_VERIFIED.values(),
|
||
):
|
||
for text in statements:
|
||
found = re.match(r"UPDATE (\w+) SET (.+?) WHERE ", text)
|
||
if found is None:
|
||
assert text.startswith("INSERT INTO attachment_variants")
|
||
continue
|
||
columns = set(re.findall(r"(\w+) = ", found.group(2)))
|
||
assert columns <= matrix[found.group(1)].update, text
|
||
|
||
|
||
# override стендов ---------------------------------------------------------------
|
||
|
||
|
||
class _Loader(yaml.SafeLoader):
|
||
pass
|
||
|
||
|
||
def _tagged(loader: _Loader, node: yaml.Node) -> Any:
|
||
if isinstance(node, yaml.SequenceNode):
|
||
return loader.construct_sequence(node, deep=True)
|
||
if isinstance(node, yaml.MappingNode):
|
||
return loader.construct_mapping(node, deep=True)
|
||
return None
|
||
|
||
|
||
_Loader.add_constructor("!override", _tagged)
|
||
_Loader.add_constructor("!reset", _tagged)
|
||
|
||
|
||
def _yaml(text: str) -> dict[str, Any]:
|
||
return yaml.load(text, Loader=_Loader) # noqa: S506
|
||
|
||
|
||
def _override(name: str) -> dict[str, Any]:
|
||
return _yaml((TRACK_DIR / name).read_text(encoding="utf-8"))
|
||
|
||
|
||
def _driver() -> ModuleType:
|
||
return stand.load_module("track1_driver_test", stand.DRIVER)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"name",
|
||
["stand.compose.yml", "before.compose.yml"],
|
||
)
|
||
def test_override_is_isolated(name: str) -> None:
|
||
text = (TRACK_DIR / name).read_text(encoding="utf-8")
|
||
model = _override(name)
|
||
code = re.sub(r"#.*", "", text)
|
||
assert "mtusi-messenger:lab7" not in code
|
||
assert "mtusi-lab7" not in code
|
||
assert model["name"].startswith("${COMPOSE_PROJECT_NAME:?")
|
||
assert "volumes" not in model
|
||
for service, spec in model["services"].items():
|
||
assert "container_name" not in spec
|
||
for port in spec.get("ports") or []:
|
||
assert str(port).startswith("127.0.0.1:${"), service
|
||
for volume in spec.get("volumes") or []:
|
||
assert volume["type"] == "bind", service
|
||
assert volume["read_only"] is True, service
|
||
assert volume["source"].startswith("./"), service
|
||
assert volume["source"] != "./config.toml", service
|
||
subnets = [
|
||
network["ipam"]["config"][0]["subnet"]
|
||
for network in model["networks"].values()
|
||
]
|
||
assert tuple(subnets) == stand.SUBNETS
|
||
|
||
|
||
def _merged(service: str, base: dict[str, Any]) -> dict[str, Any]:
|
||
"""Сервис «после»: основной файл, TS_OVERRIDE драйвера и override учений
|
||
(списки `volumes` и `ports` в них — всегда замена)."""
|
||
spec = dict(base["services"][service])
|
||
for layer in (
|
||
_yaml(_driver().TS_OVERRIDE),
|
||
_override("stand.compose.yml"),
|
||
):
|
||
extra = layer["services"].get(service) or {}
|
||
for key in ("image", "volumes", "ports", "build"):
|
||
if key in extra:
|
||
spec[key] = extra[key]
|
||
return spec
|
||
|
||
|
||
def _started(base: dict[str, Any]) -> set[str]:
|
||
"""Сервисы учений вместе с зависимостями."""
|
||
found: set[str] = {"postgres", "valkey", "s3", "rabbitmq", "openbao"}
|
||
todo = [*stand.AFTER_SERVICES, *found]
|
||
while todo:
|
||
name = todo.pop()
|
||
found.add(name)
|
||
spec = base["services"][name]
|
||
depends = spec.get("depends_on") or {}
|
||
todo += [item for item in depends if item not in found]
|
||
mode = str(spec.get("network_mode") or "")
|
||
if mode.startswith("service:") and mode[8:] not in found:
|
||
todo.append(mode[8:])
|
||
return found
|
||
|
||
|
||
def test_stand_after_has_no_working_image_volume_or_port() -> None:
|
||
base = _yaml(COMPOSE.read_text(encoding="utf-8"))
|
||
services = _started(base)
|
||
assert {"postgres-bootstrap", "migrate", "s3-bootstrap"} <= services
|
||
assert not services & {"prometheus", "loki", "tempo", "grafana"}
|
||
for name in services:
|
||
spec = _merged(name, base)
|
||
assert spec.get("image") != "mtusi-messenger:lab7", name
|
||
for volume in spec.get("volumes") or []:
|
||
assert isinstance(volume, dict), (name, volume)
|
||
assert volume["type"] == "bind", (name, volume)
|
||
assert volume["source"] != "./config.toml", name
|
||
for port in spec.get("ports") or []:
|
||
assert str(port).startswith("127.0.0.1:"), (name, port)
|
||
published = bool(spec.get("ports"))
|
||
assert published == (name in {"haproxy", "openbao"}), name
|
||
|
||
|
||
def test_stand_terms_are_reported() -> None:
|
||
"""Сроки override названы в отчёте вместе с рабочими."""
|
||
model = _override("stand.compose.yml")["services"]
|
||
reported = {name: short for name, short, _ in track1.SHORT_TERMS}
|
||
assert (
|
||
model["relay"]["environment"]["RELAY__REPUBLISH_AFTER_SECONDS"]
|
||
== reported["[relay] republish_after_seconds"]
|
||
)
|
||
assert (
|
||
model["cleaner"]["environment"]["CLEANER__INTERVAL_SECONDS"]
|
||
== reported["[cleaner] interval_seconds"]
|
||
)
|
||
before = _override("before.compose.yml")["services"]
|
||
for name in ("relay", "worker", "cleaner"):
|
||
assert before[name]["environment"] == model[name]["environment"], name
|
||
|
||
|
||
# предусловия, уборка, секреты ------------------------------------------------------
|
||
|
||
|
||
def _git(**codes: int) -> Any:
|
||
def call(*args: str) -> SimpleNamespace:
|
||
name = args[0]
|
||
if name == "cat-file":
|
||
name = "commit" if args[2].endswith("{commit}") else "file"
|
||
return SimpleNamespace(
|
||
returncode=codes.get(name, 0),
|
||
stdout="dirty\n" if codes.get("status") else "",
|
||
)
|
||
|
||
return call
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("codes", "dirty", "text"),
|
||
[
|
||
({}, False, None),
|
||
({"commit": 1}, False, "is not available"),
|
||
({"commit": 1}, True, "is not available"),
|
||
({"file": 1}, False, "is not committed"),
|
||
({"diff": 1}, False, "differs from HEAD"),
|
||
({"status": 1}, False, "tree is not committed"),
|
||
({"file": 1, "diff": 1, "status": 1}, True, None),
|
||
],
|
||
)
|
||
def test_repository_preconditions(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
codes: dict[str, int],
|
||
dirty: bool,
|
||
text: str | None,
|
||
) -> None:
|
||
monkeypatch.setattr(stand, "git", _git(**codes))
|
||
problem = stand.repository_problem("089d786", dirty=dirty)
|
||
if text is None:
|
||
assert problem is None
|
||
else:
|
||
assert problem is not None and text in problem
|
||
|
||
|
||
def test_subnets_overlap() -> None:
|
||
assert stand.overlapping([("a", "172.17.0.0/16")]) is None
|
||
assert stand.overlapping([("b", "10.207.0.0/24")]) == "b"
|
||
assert stand.overlapping([("c", "10.0.0.0/8")]) == "c"
|
||
assert stand.overlapping([("d", "10.207.1.128/25")]) == "d"
|
||
assert stand.overlapping([("e", "fd00::/64"), ("f", "bad")]) is None
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("running", "network", "used", "text"),
|
||
[
|
||
("", "172.17.0.0/16", "1GiB", None),
|
||
("abc", "172.17.0.0/16", "1GiB", "working stand"),
|
||
("", "10.207.0.0/16", "1GiB", "overlaps"),
|
||
("", "172.17.0.0/16", "10GiB", "are free"),
|
||
],
|
||
)
|
||
def test_stand_preconditions(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
running: str,
|
||
network: str,
|
||
used: str,
|
||
text: str | None,
|
||
) -> None:
|
||
def docker(*args: str, **_: Any) -> str:
|
||
if args[0] == "ps":
|
||
assert args[-1].endswith("=mtusi-lab7")
|
||
return running
|
||
if args[:2] == ("network", "ls"):
|
||
return "n1"
|
||
if args[0] == "network":
|
||
return f"other {network}\n"
|
||
if args[0] == "info":
|
||
return str(12 * 1024**3)
|
||
assert args[0] == "stats"
|
||
return f"{used} / 12GiB\n100MiB / 1GiB\n"
|
||
|
||
monkeypatch.setattr(stand, "docker", docker)
|
||
problem = stand.stand_problem()
|
||
if text is None:
|
||
assert problem is None
|
||
else:
|
||
assert problem is not None and text in problem
|
||
|
||
|
||
def test_memory_units() -> None:
|
||
assert stand.parse_memory("512KiB / 1GiB") == 512 * 1024
|
||
assert stand.parse_memory("1.5GiB / 2GiB") == int(1.5 * 1024**3)
|
||
assert stand.parse_memory("-- / --") == 0
|
||
|
||
|
||
class _Guard:
|
||
"""Уборка и каталог учений без docker."""
|
||
|
||
def __init__(self) -> None:
|
||
self.calls: list[str] = []
|
||
self.locked = True
|
||
|
||
def lock(self) -> None:
|
||
self.calls.append("lock")
|
||
|
||
def left(self) -> list[str]:
|
||
return []
|
||
|
||
def clean(self) -> list[str]:
|
||
self.calls.append("clean")
|
||
return []
|
||
|
||
def make_run_dir(self) -> Path:
|
||
self.calls.append("run_dir")
|
||
raise AssertionError("created before the preconditions")
|
||
|
||
|
||
@pytest.fixture
|
||
def guard(monkeypatch: pytest.MonkeyPatch) -> _Guard:
|
||
made = _Guard()
|
||
monkeypatch.setattr(track1, "Guard", lambda: made)
|
||
monkeypatch.setattr(track1, "clean_environment", lambda: None)
|
||
monkeypatch.setattr(track1, "repository_problem", lambda *_, **__: None)
|
||
monkeypatch.setattr(track1, "stand_problem", lambda: None)
|
||
monkeypatch.setattr(track1.signal, "signal", lambda *_: None)
|
||
return made
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("name", "argv"),
|
||
[
|
||
("repository_problem", []),
|
||
("stand_problem", ["--dirty"]),
|
||
(None, ["--rounds", "0"]),
|
||
(None, ["--out", "/no/such/directory/report.md"]),
|
||
],
|
||
)
|
||
def test_precondition_is_code_2_and_nothing_created(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
guard: _Guard,
|
||
name: str | None,
|
||
argv: list[str],
|
||
) -> None:
|
||
if name is not None:
|
||
monkeypatch.setattr(track1, name, lambda *_, **__: "broken thing")
|
||
assert track1.main(argv) == 2
|
||
assert "run_dir" not in guard.calls
|
||
assert "clean" not in guard.calls
|
||
assert "nothing was created" in capsys.readouterr().out
|
||
|
||
|
||
def test_unknown_control_is_code_2(
|
||
guard: _Guard,
|
||
capsys: pytest.CaptureFixture[str],
|
||
) -> None:
|
||
with pytest.raises(SystemExit) as found:
|
||
track1.main(["--control", "нет-такого"])
|
||
assert found.value.code == 2
|
||
assert guard.calls == []
|
||
capsys.readouterr()
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("error", "code"),
|
||
[
|
||
(stand.Interrupted("SIGINT"), 130),
|
||
(stand.Failed("step"), 1),
|
||
(RuntimeError(SECRET), 1),
|
||
(None, 0),
|
||
(False, 1),
|
||
],
|
||
)
|
||
def test_clean_on_every_outcome(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
guard: _Guard,
|
||
error: object,
|
||
code: int,
|
||
) -> None:
|
||
def scenario(*_: Any) -> bool:
|
||
if isinstance(error, BaseException):
|
||
raise error
|
||
return error is None
|
||
|
||
monkeypatch.setattr(track1, "scenario", scenario)
|
||
assert track1.main(["--dirty"]) == code
|
||
assert guard.calls == ["lock", "clean"]
|
||
out = capsys.readouterr().out
|
||
assert SECRET not in out
|
||
if error is not None and code == 1:
|
||
assert "CONFIRMED" not in out
|
||
|
||
|
||
def test_leftovers_make_the_run_red(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
guard: _Guard,
|
||
) -> None:
|
||
monkeypatch.setattr(track1, "scenario", lambda *_: True)
|
||
monkeypatch.setattr(guard, "clean", lambda: ["container abc"])
|
||
assert track1.main(["--dirty"]) == 1
|
||
assert "LEFTOVERS: container abc" in capsys.readouterr().out
|
||
|
||
|
||
def test_killed_run_is_cleaned_by_the_next(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
capsys: pytest.CaptureFixture[str],
|
||
guard: _Guard,
|
||
) -> None:
|
||
monkeypatch.setattr(guard, "left", lambda: ["network n"])
|
||
monkeypatch.setattr(track1, "scenario", lambda *_: True)
|
||
assert track1.main(["--dirty"]) == 0
|
||
assert guard.calls == ["lock", "clean", "clean"]
|
||
monkeypatch.setattr(guard, "clean", lambda: ["network n"])
|
||
assert track1.main(["--dirty"]) == 2
|
||
assert "cannot remove" in capsys.readouterr().out
|
||
|
||
|
||
def test_second_run_is_refused(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
tmp_path: Path,
|
||
) -> None:
|
||
monkeypatch.setattr(stand.tempfile, "gettempdir", lambda: str(tmp_path))
|
||
first, second = stand.Guard(), stand.Guard()
|
||
first.lock()
|
||
with pytest.raises(stand.NotReady, match="another"):
|
||
second.lock()
|
||
|
||
|
||
def test_environment_hides_working_stand(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
"""Переменные рабочего `.env` и каталоги оператора из окружения make до
|
||
стенда учений не доходят."""
|
||
names = (
|
||
"PKI_OPERATOR_DIR",
|
||
"PKI_STAND_DIR",
|
||
"BAO_OPERATOR_DIR",
|
||
"POSTGRES_WORKER_PASSWORD",
|
||
"COMPOSE_FILE",
|
||
"S3_API_SECRET_KEY",
|
||
"RABBITMQ_DEFAULT_PASS",
|
||
)
|
||
for name in names:
|
||
monkeypatch.setenv(name, SECRET)
|
||
stand.clean_environment()
|
||
assert not [name for name in names if name in stand.os.environ]
|
||
|
||
|
||
class _Process:
|
||
"""Подставной процесс: argv, окружение и stdin."""
|
||
|
||
calls: list[dict[str, Any]] = []
|
||
stdout_text = ""
|
||
|
||
def __init__(self, args: list[str], **options: Any) -> None:
|
||
self.record = {
|
||
"args": args,
|
||
"env": options.get("env") or {},
|
||
"stdin": "",
|
||
}
|
||
type(self).calls.append(self.record)
|
||
self.pid = 0
|
||
self.returncode = 0
|
||
self.stdin = self
|
||
self.stdout = iter([json.dumps({"ready": {"s3_key": "ok"}})])
|
||
self.stderr = iter(())
|
||
|
||
def write(self, text: str) -> None:
|
||
self.record["stdin"] += text
|
||
|
||
def flush(self) -> None:
|
||
return None
|
||
|
||
def communicate(self, text: str, timeout: float) -> tuple[str, str]:
|
||
self.record["stdin"] += text
|
||
return self.stdout_text, ""
|
||
|
||
def wait(self, timeout: float | None = None) -> int:
|
||
return 0
|
||
|
||
|
||
@pytest.fixture
|
||
def processes(monkeypatch: pytest.MonkeyPatch) -> type[_Process]:
|
||
_Process.calls = []
|
||
_Process.stdout_text = json.dumps({"results": {}})
|
||
monkeypatch.setattr(stand.subprocess, "Popen", _Process)
|
||
return _Process
|
||
|
||
|
||
def _stand(tmp_path: Path) -> Any:
|
||
made = stand.StandAfter(tmp_path)
|
||
made.values = {
|
||
"POSTGRES_DB": "messenger",
|
||
"S3__BUCKET": "messenger",
|
||
"S3_API_ACCESS_KEY": SECRET,
|
||
"S3_API_SECRET_KEY": SECRET,
|
||
}
|
||
made.env = {"TRACK1_TLS": "1"}
|
||
return made
|
||
|
||
|
||
def test_secrets_go_by_stdin_only(
|
||
processes: type[_Process],
|
||
tmp_path: Path,
|
||
) -> None:
|
||
made = _stand(tmp_path)
|
||
made.probe({"action": "table", "data": SECRET})
|
||
made.seed_objects({"messenger/staging/x/original": "x"})
|
||
attacker = stand.Attacker(made, {"files": {}, "s3": {"secret": SECRET}})
|
||
assert attacker.ready == {"s3_key": "ok"}
|
||
with_secret = 0
|
||
for call in processes.calls:
|
||
text = " ".join(call["args"]) + json.dumps(call["env"])
|
||
assert SECRET not in text
|
||
assert "PRIVATE KEY" not in text
|
||
with_secret += SECRET in call["stdin"]
|
||
assert with_secret == 3
|
||
docker_run = processes.calls[-1]["args"]
|
||
for flag in ("--read-only", "ALL", "no-new-privileges:true"):
|
||
assert flag in docker_run
|
||
assert "-e" not in docker_run and "--env" not in docker_run
|
||
|
||
|
||
def test_report_has_no_secret_values(tmp_path: Path) -> None:
|
||
args = SimpleNamespace(control="", dirty=True)
|
||
report = track1.Report(args, HYPOTHESES)
|
||
report.before = _as_expected("before")
|
||
report.after = {**_as_expected("after"), "s3.put.staging": "ok"}
|
||
item = track1.Round(_stand(tmp_path), 1, "")
|
||
item.windows = analysis.windows(_samples(17.0), MARKS)
|
||
item.tally = _tally()
|
||
item.accepted = _accepted()
|
||
item.refused = {"source-put": "denied:AccessDenied"}
|
||
item.commands = [("revoke", 24.0)]
|
||
item.ready_seconds = 22.0
|
||
report.rounds = [item]
|
||
report.verdicts = [_h1(), _h2(), analysis.Verdict("H3", False, "lost 1")]
|
||
report.lost_before = {"pending": 1}
|
||
report.final_before = {"pending": "gone"}
|
||
report.actions_before = {"read sessions": True}
|
||
text = report.markdown()
|
||
assert SECRET not in text
|
||
for pattern in (r"\bs\.[A-Za-z0-9]{20,}", "BEGIN ", "PRIVATE KEY"):
|
||
assert not re.search(pattern, text)
|
||
assert "не доказательство" in text
|
||
# строка сверх ожидаемого видна прямо в таблице
|
||
assert "**ok** (ждали denied:AccessDenied)" in text
|
||
assert "H3: НЕ подтверждена" in text
|
||
assert "12.0 с" in text
|
||
for name, short, work in track1.SHORT_TERMS:
|
||
assert f"{name}: {short} (рабочее {work})" in text
|
||
for limit in track1.LIMITS:
|
||
assert limit in text
|
||
|
||
|
||
def test_sources_are_stdlib_and_python_39() -> None:
|
||
"""Оркестратор — системный python3: его модули не импортируют зависимостей
|
||
и разбираются синтаксисом 3.9."""
|
||
import ast
|
||
|
||
for name in ("track1", "stand", "analysis", "operations"):
|
||
text = (TRACK_DIR / f"{name}.py").read_text(encoding="utf-8")
|
||
tree = ast.parse(text, feature_version=(3, 9))
|
||
assert "from __future__ import annotations" in text
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, ast.Import):
|
||
modules = [alias.name for alias in node.names]
|
||
elif isinstance(node, ast.ImportFrom):
|
||
modules = [node.module or ""]
|
||
else:
|
||
continue
|
||
for module in modules:
|
||
root = module.split(".")[0]
|
||
assert root in sys.stdlib_module_names or root in {
|
||
"analysis",
|
||
"operations",
|
||
"stand",
|
||
}, (name, module)
|
||
|
||
|
||
class _Calls:
|
||
"""Стенд и копия атакующего повтора: порядок вызовов."""
|
||
|
||
def __init__(self, codes: tuple[int, int, int] = (1, 0, 0)) -> None:
|
||
self.calls: list[str] = []
|
||
self.codes = iter(codes)
|
||
self.found: dict[str, tuple[str, ...]] = {}
|
||
|
||
def mark(self, name: str) -> None:
|
||
self.calls.append(f"mark {name}")
|
||
|
||
def rotation(self, *args: str) -> str:
|
||
self.calls.append(" ".join(args))
|
||
return ""
|
||
|
||
def recreate_worker(self) -> None:
|
||
self.calls.append("recreate")
|
||
|
||
def wait_log(self, *_: str) -> None:
|
||
self.calls.append("started")
|
||
|
||
def incident(self) -> dict[str, tuple[str, ...]]:
|
||
self.calls.append("incident")
|
||
return self.found
|
||
|
||
def jobs(self, mode: str) -> tuple[int, str]:
|
||
self.calls.append(f"jobs {mode}")
|
||
code = next(self.codes)
|
||
return code, f"class stuck_time {code}\ndamaged {code}\n"
|
||
|
||
def replay_failed(self) -> None:
|
||
self.calls.append("replay")
|
||
|
||
def wait_attachments(self, *_: Any, **__: Any) -> float | None:
|
||
self.calls.append("wait")
|
||
return 1.0
|
||
|
||
|
||
@pytest.fixture
|
||
def no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
|
||
monkeypatch.setattr(track1.time, "sleep", lambda _: None)
|
||
|
||
|
||
@pytest.mark.parametrize("control", ["", "no-revoke", "no-republish"])
|
||
def test_response_order(no_sleep: None, control: str) -> None:
|
||
"""Порядок «Компрометация процесса»: каждая команда — между метками A2;
|
||
контроль no-revoke пропускает только отзыв."""
|
||
calls = _Calls()
|
||
item = track1.Round(calls, 1, control)
|
||
item.respond(calls)
|
||
steps = [
|
||
("revoke", "revoke worker"),
|
||
("secret postgres/worker", "secret postgres/worker"),
|
||
("secret s3/worker", "secret s3/worker"),
|
||
("recreate worker", "recreate"),
|
||
("leaf worker", "leaf worker"),
|
||
]
|
||
if control == "no-revoke":
|
||
steps = steps[1:]
|
||
expected = ["mark t0"]
|
||
for name, call in steps:
|
||
expected += [f"mark begin:{name}", call, f"mark end:{name}"]
|
||
assert calls.calls == expected
|
||
assert [name for name, _ in item.commands] == [name for name, _ in steps]
|
||
|
||
|
||
def test_recovery_after_the_identity_returned(no_sleep: None) -> None:
|
||
calls = _Calls()
|
||
calls.found = {"a": ("stuck_time",)}
|
||
item = track1.Round(calls, 1, "")
|
||
item.planted = {"a": ("stuck_time",), "b": ("false_success",)}
|
||
item.accepted = _accepted()
|
||
item.user = {}
|
||
item.recover(track1.time.monotonic())
|
||
assert calls.calls == [
|
||
"started",
|
||
"incident",
|
||
"jobs audit",
|
||
"jobs repair",
|
||
"jobs audit",
|
||
"replay",
|
||
"wait",
|
||
]
|
||
assert item.missed == ["b"]
|
||
assert (item.audit, item.left, item.problems) == ((1, 0, 0), 0, [])
|
||
assert item.ready_seconds is not None
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("codes", "problem", "left"),
|
||
[
|
||
# порчи не нашли, хотя она есть
|
||
((0, 0, 0), "jobs_audit code 0, expected 1", 0),
|
||
((2, 0, 0), "jobs_audit code 2, expected 1", 0),
|
||
# возврат не вернул
|
||
((1, 1, 1), "jobs_audit after the repair: code 1", 1),
|
||
],
|
||
)
|
||
def test_recovery_problems_are_named(
|
||
no_sleep: None,
|
||
codes: tuple[int, int, int],
|
||
problem: str,
|
||
left: int,
|
||
) -> None:
|
||
item = track1.Round(_Calls(codes), 1, "")
|
||
item.user = {}
|
||
item.recover(track1.time.monotonic())
|
||
assert item.problems == [problem]
|
||
assert item.left == left
|
||
|
||
|
||
def test_never_ready_is_not_a_time(
|
||
no_sleep: None,
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
calls = _Calls()
|
||
monkeypatch.setattr(calls, "wait_attachments", lambda *_, **__: None)
|
||
item = track1.Round(calls, 1, "")
|
||
item.user = {}
|
||
item.recover(track1.time.monotonic())
|
||
assert item.ready_seconds is None
|