363 lines
14 KiB
Python
363 lines
14 KiB
Python
"""Лаба 7, трек 1 «Компрометация worker»: всё, что проверяется без стенда.
|
|
|
|
Таблица операций `infra/track1/operations.py` против источников прав (матрица
|
|
ролей `src/db_roles.py`, права брокера `infra/rabbitmq/start.sh`, политика
|
|
OpenBao `worker.hcl`, политика S3 worker в `infra/s3/bootstrap.sh`): ожидание
|
|
«после» не может разойтись с правами и не подгоняется под прогон. Политика S3
|
|
— только префиксы своей базы. Ревизия 0006: функции триггеров без SECURITY
|
|
DEFINER, `search_path = pg_catalog`, перечень кодов = константы кода, вид ключа
|
|
варианта = ключ, который строит `AttachmentObjects`. Чистые функции учений
|
|
(окна, вердикты, сводка таблицы), override «до» и «после», гипотезы, цели make и
|
|
правила Codex.
|
|
"""
|
|
|
|
import importlib.util
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
from types import ModuleType
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
|
|
from src import constants, db_roles
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
TRACK1 = ROOT / "infra" / "track1"
|
|
|
|
|
|
def _load(name: str, path: Path) -> ModuleType:
|
|
spec = importlib.util.spec_from_file_location(name, path)
|
|
assert spec is not None
|
|
assert spec.loader is not None
|
|
module = importlib.util.module_from_spec(spec)
|
|
sys.modules[name] = module
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
operations = _load("operations", TRACK1 / "operations.py")
|
|
sys.path.insert(0, str(ROOT / "student-tests"))
|
|
track1 = _load("track1_drill", TRACK1 / "track1.py")
|
|
revision = _load(
|
|
"revision_0006", ROOT / "migrations" / "versions" / "0006_pipeline_value_rules.py"
|
|
)
|
|
|
|
|
|
def _row(op_id: str):
|
|
return operations.by_id()[op_id]
|
|
|
|
|
|
# --- таблица против источников прав -------------------------------------------
|
|
|
|
|
|
def test_postgres_rows_match_the_worker_matrix() -> None:
|
|
grants = db_roles.MATRIX[db_roles.WORKER_ROLE]
|
|
assert set(operations.PG_TABLES) == set(db_roles.TABLES)
|
|
for table in operations.PG_TABLES:
|
|
grant = grants[table]
|
|
assert (table in operations.PG_SELECT) == grant.select, table
|
|
assert (table in operations.PG_INSERT) == grant.insert, table
|
|
assert (table in operations.PG_DELETE) == grant.delete, table
|
|
assert set(operations.PG_UPDATE.get(table, ())) == set(grant.update), table
|
|
assert operations.PG_FOREIGN_COLUMN[table] not in grant.update, table
|
|
for verb in ("select", "insert", "delete"):
|
|
row = _row(f"pg.{verb}.{table}")
|
|
allowed = getattr(grant, verb)
|
|
assert row.after == (operations.OK if allowed else operations.INSUFFICIENT)
|
|
for row in operations.OPERATIONS:
|
|
if row.id.startswith("pg.update."):
|
|
table, column = row.id.split(".")[2:]
|
|
allowed = column in grants[table].update
|
|
assert row.after == (operations.OK if allowed else operations.INSUFFICIENT)
|
|
|
|
|
|
def _worker_permissions() -> dict[str, str]:
|
|
text = (ROOT / "infra" / "rabbitmq" / "start.sh").read_text(encoding="utf-8")
|
|
block = re.search(r'\{"user": "worker",(.*?)\}', text, re.S)
|
|
assert block is not None
|
|
# heredoc без кавычек: «\$» в файле — «$» в определениях брокера
|
|
found = re.findall(r'"(configure|write|read)": "([^"]*)"', block.group(1))
|
|
return {verb: value.replace("\\$", "$") for verb, value in found}
|
|
|
|
|
|
def test_broker_rows_match_the_worker_permissions() -> None:
|
|
permissions = _worker_permissions()
|
|
assert permissions["configure"] == "^$"
|
|
assert permissions["write"] == "^$"
|
|
assert permissions["read"] == "$queue_pattern"
|
|
# read на свою очередь: получение и очистка; запись и настройка — нет
|
|
for action in ("passive", "get", "purge"):
|
|
assert _row(f"amqp.{action}").after == operations.OK
|
|
for action in ("publish", "declare", "bind", "get_other", "delete_other"):
|
|
assert _row(f"amqp.{action}").after == operations.REFUSED
|
|
|
|
|
|
def test_openbao_rows_match_the_worker_policy() -> None:
|
|
text = (ROOT / "infra" / "openbao" / "policies" / "worker.hcl").read_text()
|
|
readable = set(re.findall(r'path "(messenger/data/[^"]+)"', text))
|
|
assert readable == {"messenger/data/postgres/worker", "messenger/data/s3/worker"}
|
|
for row in operations.OPERATIONS:
|
|
if row.kind != "bao":
|
|
continue
|
|
path = row.args["path"]
|
|
expected = (
|
|
operations.OK
|
|
if row.args["method"] == "GET" and path in readable
|
|
else operations.BAO_FORBIDDEN
|
|
)
|
|
assert row.after == expected, row.id
|
|
|
|
|
|
def _worker_policy() -> dict:
|
|
text = (ROOT / "infra" / "s3" / "bootstrap.sh").read_text(encoding="utf-8")
|
|
body = re.search(
|
|
r"write_worker_policy\(\) \{\n cat >[^\n]*<<EOF\n(.*?)\nEOF", text, re.S
|
|
)
|
|
assert body is not None, "write_worker_policy is missing"
|
|
raw = body.group(1).replace("${BUCKET}", "bucket").replace("${DATABASE}", "db")
|
|
return json.loads(raw)
|
|
|
|
|
|
def test_s3_worker_policy_is_prefix_scoped() -> None:
|
|
"""Чтение — только staging своей базы, запись — только attachments; ни
|
|
удаления, ни списка, ни ресурса шире префикса (мутация «весь bucket»)."""
|
|
statements = _worker_policy()["Statement"]
|
|
rights = {tuple(s["Action"]): s["Resource"] for s in statements}
|
|
assert rights == {
|
|
("s3:GetObject",): ["arn:aws:s3:::bucket/db/staging/*"],
|
|
("s3:PutObject",): ["arn:aws:s3:::bucket/db/attachments/*"],
|
|
}
|
|
assert _row("s3.get.staging").after == operations.OK
|
|
assert _row("s3.put.attachments").after == operations.OK
|
|
for op_id in (
|
|
"s3.get.attachments",
|
|
"s3.head.attachments",
|
|
"s3.put.staging",
|
|
"s3.get.other_db",
|
|
"s3.put.other_db",
|
|
"s3.get.root",
|
|
"s3.put.root",
|
|
"s3.copy.from_attachments",
|
|
"s3.multipart.staging",
|
|
):
|
|
assert _row(op_id).after == operations.S3_DENIED, op_id
|
|
|
|
|
|
def test_every_available_row_is_explained() -> None:
|
|
for row in operations.OPERATIONS:
|
|
if row.after == operations.OK:
|
|
assert row.why, row.id
|
|
assert row.why[0] in (operations.CODE, operations.RESIDUAL), row.id
|
|
assert row.scope in (operations.OWN, operations.PROCESS), row.id
|
|
assert len({row.id for row in operations.OPERATIONS}) == len(operations.OPERATIONS)
|
|
|
|
|
|
# --- ревизия 0006 -------------------------------------------------------------
|
|
|
|
|
|
def test_trigger_functions_are_not_security_definer() -> None:
|
|
for sql in (revision.NOT_PENDING_FUNCTION, revision.NAMESPACE_FUNCTION):
|
|
assert "SECURITY DEFINER" not in sql.upper()
|
|
assert "SET search_path = pg_catalog" in sql
|
|
assert "public.attachments" in sql or "RAISE" in sql
|
|
|
|
|
|
def test_error_codes_are_the_code_constants() -> None:
|
|
codes = {
|
|
constants.ERROR_INVALID_IMAGE,
|
|
constants.ERROR_TOO_LARGE,
|
|
constants.ERROR_SOURCE_MISSING,
|
|
constants.ERROR_RETRY_EXHAUSTED,
|
|
constants.ERROR_PROCESSING_FAILED,
|
|
}
|
|
condition = {name: cond for name, _table, cond in revision.CHECKS}
|
|
assert (
|
|
set(re.findall(r"'([a-z_]+)'", condition["ck_attachments_error_code_known"]))
|
|
== codes
|
|
)
|
|
|
|
|
|
def test_tables_repeat_the_revision_checks() -> None:
|
|
from src.storage import tables
|
|
|
|
found = {
|
|
c.name: str(c.sqltext)
|
|
for table in (tables.attachments, tables.attachment_variants)
|
|
for c in table.constraints
|
|
if c.name in {name for name, _t, _c in revision.CHECKS}
|
|
}
|
|
assert found == {name: cond for name, _table, cond in revision.CHECKS}
|
|
|
|
|
|
def _variant_pattern(attachment_id: str, version: int, name: str) -> str:
|
|
# то же выражение, что CHECK ck_attachment_variants_object_key_own
|
|
return (
|
|
"^[a-z0-9_]+/attachments/"
|
|
+ attachment_id
|
|
+ "/p"
|
|
+ str(version)
|
|
+ "/"
|
|
+ name
|
|
+ "[.](jpg|webp)$"
|
|
)
|
|
|
|
|
|
def test_variant_key_rule_accepts_own_keys_only() -> None:
|
|
from src.s3 import ObjectStore
|
|
from src.storage.objects import AttachmentObjects
|
|
|
|
class Store:
|
|
namespace = "messenger"
|
|
|
|
objects = AttachmentObjects(Store()) # type: ignore[arg-type]
|
|
own, other = uuid4(), uuid4()
|
|
for name in constants.VARIANT_FORMATS:
|
|
key = objects.variant_key(own, name)
|
|
assert re.search(
|
|
_variant_pattern(str(own), constants.PIPELINE_VERSION, name), key
|
|
)
|
|
pattern = _variant_pattern(str(own), 1, "thumbnail")
|
|
for foreign in (
|
|
objects.key_of(other),
|
|
objects.variant_key(other, "thumbnail"),
|
|
f"messenger/attachments/{own}/p1/../../{other}/original",
|
|
objects.key_of(own),
|
|
):
|
|
assert not re.search(pattern, foreign), foreign
|
|
assert ObjectStore # модуль клиента импортируется без стенда
|
|
|
|
|
|
# --- чистые функции учений ----------------------------------------------------
|
|
|
|
|
|
def test_windows_from_marks_and_last_success() -> None:
|
|
events = [
|
|
{"mark": "start", "t": 100.0},
|
|
{"mark": "end", "t": 190.0},
|
|
{
|
|
"done": True,
|
|
"last_ok": {"amqp_new": 103.5, "pg_open": 90.0, "s3_key": 191.0},
|
|
},
|
|
]
|
|
found = track1.windows(events)
|
|
assert found["amqp_new"] == {"window": 3.5, "after_end": False}
|
|
assert found["pg_open"] == {"window": 0.0, "after_end": False}
|
|
assert found["s3_key"]["after_end"] is True
|
|
|
|
|
|
def _thresholds() -> dict:
|
|
return json.loads((TRACK1 / "hypotheses.json").read_text())["hypotheses"]
|
|
|
|
|
|
def test_verdicts_follow_the_thresholds() -> None:
|
|
materials = _thresholds()["H2"]["thresholds"]["windows_seconds"]
|
|
good = {
|
|
"H2": {
|
|
"rounds": [{m: {"window": 3.0, "after_end": False} for m in materials}],
|
|
"failed_requests": 0,
|
|
},
|
|
"H3": {
|
|
"accepted": 10,
|
|
"lost": 0,
|
|
"duplicated": 0,
|
|
"wrong_sha256": 0,
|
|
"ready_seconds": 30.0,
|
|
},
|
|
"H4": {
|
|
"damaged": 6,
|
|
"found": 6,
|
|
"missed_damage": 0,
|
|
"left_after_repair": 0,
|
|
"overwrites": 1,
|
|
"missed_overwrites": 0,
|
|
},
|
|
"H5": {"lost": {"a": 1, "b": 2}, "failed_actions": 0},
|
|
}
|
|
assert all(ok for ok, _ in track1.verdicts(_thresholds(), good).values())
|
|
bad = json.loads(json.dumps(good))
|
|
bad["H2"]["rounds"][0]["amqp_new"] = {"window": 16.0, "after_end": False}
|
|
bad["H3"]["lost"] = 1
|
|
bad["H4"]["missed_damage"] = 1
|
|
bad["H5"]["lost"]["a"] = 0
|
|
results = track1.verdicts(_thresholds(), bad)
|
|
assert not any(ok for ok, _ in results.values())
|
|
after_end = json.loads(json.dumps(good))
|
|
after_end["H2"]["rounds"][0]["amqp_new"] = {"window": 1.0, "after_end": True}
|
|
assert not track1.verdicts(_thresholds(), after_end)["H2"][0]
|
|
# материал без единого успеха не измерен — гипотеза не подтверждается
|
|
missing = json.loads(json.dumps(good))
|
|
del missing["H2"]["rounds"][0]["pg_open"]
|
|
ok, text = track1.verdicts(_thresholds(), missing)["H2"]
|
|
assert not ok
|
|
assert "pg_open not measured" in text
|
|
|
|
|
|
def test_table_summary_counts_closed_and_outside() -> None:
|
|
before = {op.id: op.before for op in operations.OPERATIONS}
|
|
after = {op.id: op.after for op in operations.OPERATIONS}
|
|
summary = track1.table_summary(before, after)
|
|
assert summary["unexpected_after"] == []
|
|
assert summary["outside_available"] == []
|
|
assert summary["closed_share"] >= 0.67
|
|
widened = dict(after, **{"pg.select.users": "ok"})
|
|
summary = track1.table_summary(before, widened)
|
|
assert summary["outside_available"] == ["pg.select.users"]
|
|
assert [x[0] for x in summary["unexpected_after"]] == ["pg.select.users"]
|
|
verdict = track1.verdicts(_thresholds(), {"H1": summary})["H1"]
|
|
assert not verdict[0]
|
|
|
|
|
|
def test_png_is_distinct_per_seed() -> None:
|
|
first, second = track1.png(1), track1.png(2)
|
|
assert first.startswith(b"\x89PNG\r\n\x1a\n")
|
|
assert first != second
|
|
|
|
|
|
# --- override, гипотезы, цели make, Codex --------------------------------------
|
|
|
|
|
|
def test_overrides_do_not_touch_the_working_stand() -> None:
|
|
working_image = "mtusi-messenger-vladimirceva:lab7"
|
|
for name, tag in (
|
|
("stand.compose.yml", ":track1"),
|
|
("before.compose.yml", ":track1-before"),
|
|
):
|
|
text = (TRACK1 / name).read_text(encoding="utf-8")
|
|
assert not re.search(r"^name:", text, re.M), name
|
|
assert f"image: {working_image}\n" not in text
|
|
assert f"mtusi-messenger-vladimirceva{tag}" in text
|
|
assert "10.207." not in "".join(
|
|
line for line in text.splitlines() if not line.lstrip().startswith("#")
|
|
)
|
|
assert re.findall(r"subnet: (10\.217\.\d+\.0/24)", text)
|
|
before = (TRACK1 / "before.compose.yml").read_text(encoding="utf-8")
|
|
for service in ("postgres", "valkey", "s3", "rabbitmq", "grafana"):
|
|
assert re.search(rf"^ {service}:\n ports: !reset \[\]", before, re.M), (
|
|
service
|
|
)
|
|
assert '"127.0.0.1:${TRACK1_LB_PORT:-0}:8080"' in before
|
|
|
|
|
|
def test_hypotheses_cover_h1_to_h5() -> None:
|
|
data = json.loads((TRACK1 / "hypotheses.json").read_text())
|
|
assert set(data["hypotheses"]) == {"H1", "H2", "H3", "H4", "H5"}
|
|
assert data["min_rounds"] >= 3
|
|
assert data["before_commit"] == "3e8493b"
|
|
assert all(
|
|
item["text"] and item["thresholds"] for item in data["hypotheses"].values()
|
|
)
|
|
|
|
|
|
def test_make_targets_and_codex_rules() -> None:
|
|
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
|
|
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
|
|
for target in ("jobs-audit", "worker-compromise"):
|
|
assert re.search(rf"^{target}:", makefile, re.M), target
|
|
assert f'"{target}"' in rules, target
|
|
assert 'pattern = ["make", "jobs-audit", "REPAIR=1"]' in rules
|
|
assert "infra/incident/jobs.sh $(if $(REPAIR),repair,audit)" in makefile
|