Files
mtusi2026lab7-safronov/infra/track1/analysis.py
T
ricoromaandClaude Opus 5.5 4f2f940a07 feat: confine a compromised worker and drill its compromise end to end
- 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>
2026-12-02 03:01:20 +03:00

488 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Выводы учений «Компрометация worker» без docker и сети: строки таблицы, окна
материалов, контрольные числа, вердикты гипотез и отчёт (change
track1-worker-compromise, design, решения 9–11, 13). Чистые функции, stdlib,
синтаксис Python 3.9; быстрый тест — `service-tests/unit/test_track1.py`.
"""
from __future__ import annotations
from typing import NamedTuple
import operations as ops
HYPOTHESES = ("H1", "H2", "H3", "H4", "H5")
MATERIALS = (
"amqp_new",
"amqp_open",
"amqp_early",
"otlp_new",
"otlp_open",
"bao_login",
"bao_token",
"pg_new",
"pg_open",
"s3_key",
)
TITLES = {
"amqp_new": "новый вход в брокер",
"amqp_open": "открытое соединение брокера",
"amqp_early": "вход в брокер, начатый до отзыва",
"otlp_new": "новое соединение OTLP",
"otlp_open": "соединение OTLP keep-alive",
"bao_login": "вход в OpenBao",
"bao_token": "токен OpenBao",
"pg_new": "новый вход в PostgreSQL",
"pg_open": "открытая сессия PostgreSQL",
"s3_key": "ключ S3",
}
class TableDiff(NamedTuple):
"""Строки, чей исход — не ожидаемый: `(id, ожидалось, получено)`."""
before: list
after: list
def table_diff(rows, before: dict, after: dict) -> TableDiff:
"""Расхождения обеих колонок. Нет исхода — расхождение, а не пропуск."""
return TableDiff(
[
(row.id, row.before, before.get(row.id, "missing"))
for row in rows
if before.get(row.id, "missing") != row.before
]
if before
else [],
[
(row.id, row.after, after.get(row.id, "missing"))
for row in rows
if after.get(row.id, "missing") != row.after
],
)
def opened(rows, after: dict) -> list:
"""Операции, которые прошли «после» сверх ожидаемого (контроль
wide-rights)."""
return [
row.id
for row in rows
if after.get(row.id) == ops.OK and row.after != ops.OK
]
class Closed(NamedTuple):
"""Сопоставление «до / после» по полученным исходам."""
available_before: int
closed: int
both: list
outside: list
@property
def share(self) -> float:
if not self.available_before:
return 0.0
return self.closed / self.available_before
def closed(rows, before: dict, after: dict) -> Closed:
available = [row for row in rows if before.get(row.id) == ops.OK]
both = [row.id for row in available if after.get(row.id) == ops.OK]
outside = [
row.id
for row in rows
if row.scope == ops.OUTSIDE and after.get(row.id) == ops.OK
]
return Closed(
len(available),
len(available) - len(both),
both,
outside,
)
# окна -----------------------------------------------------------------------
class Window(NamedTuple):
"""Окно материала: секунды от начала порядка до последнего успеха и
команда, после которой успехов нет. `seconds` — `None`, если материал ни
разу не действовал: окно не измерено, и это не успех."""
material: str
seconds: float | None
command: str
after_last: bool
probes: int
def windows(samples: list, marks: dict) -> list:
"""Окно каждого материала по записям A2. `samples` — `(t, материал,
исход)`, `marks` — метка → t тех же часов: `t0`, затем `begin:<команда>` и
`end:<команда>` по порядку. Успех, начатый до `t0`, окна не открывает."""
start = marks["t0"]
commands = [name[6:] for name in marks if name.startswith("begin:")]
last_end = max(
(marks["end:" + name] for name in commands),
default=start,
)
found = []
for material in MATERIALS:
times = [
t
for t, name, outcome in samples
if name == material and t >= start
]
good = [
t
for t, name, outcome in samples
if name == material and outcome == ops.OK
]
late = [t for t in good if t >= start]
if not good or not times:
found.append(Window(material, None, "-", False, len(times)))
continue
seconds = round(late[-1] - start, 1) if late else 0.0
moment = late[-1] if late else start
command = "-"
for name in commands:
if marks["begin:" + name] <= moment:
command = name
found.append(
Window(
material,
seconds,
command,
bool(late) and late[-1] > last_end,
len(times),
),
)
return found
class Damage(NamedTuple):
"""Порча во время порядка: строк испорчено, очисток очереди, секунда
последнего успеха от начала порядка, действует ли после последней
команды."""
rows: int
purges: int
seconds: float
after_last: bool
def damage(samples: list, marks: dict) -> Damage:
"""Записи `damage_rows` (`ok:<строк>`) и `damage_queue` копии атакующего с
начала нагрузки (метка `start`)."""
start = marks["t0"]
last_end = max(
(t for name, t in marks.items() if name.startswith("end:")),
default=start,
)
rows = purges = 0
last = start
for t, name, outcome in samples:
if name == "damage_rows" and outcome.startswith("ok:"):
rows += int(outcome[3:])
elif name == "damage_queue" and outcome == ops.OK:
purges += 1
else:
continue
last = max(last, t)
return Damage(rows, purges, round(last - start, 1), last > last_end)
def window_problems(found: list, limits: dict) -> list:
"""Нарушения окон одного повтора: не измерено, дольше порога, действует
после последней команды."""
problems = []
for item in found:
limit = limits[item.material]
if item.seconds is None:
problems.append(f"{item.material}: never worked, window unknown")
elif item.after_last:
problems.append(
f"{item.material}: works after the last command "
f"({item.seconds:.1f} s)",
)
elif item.seconds > limit:
problems.append(
f"{item.material}: {item.seconds:.1f} s > {limit} s",
)
return problems
# сохранность ------------------------------------------------------------------
class Accepted(NamedTuple):
"""Принятое клиентом (202): id, SHA-256 загруженного, когорта."""
id: str
sha256: str
cohort: str
class Final(NamedTuple):
"""Состояние вложения в конце: статус API, SHA-256 скачанного оригинала,
вариантов, строк вложения и заданий."""
status: str
sha256: str
variants: int
rows: int
jobs: int
class Tally(NamedTuple):
accepted: int
ready: int
lost: list
duplicated: list
wrong: list
def tally(accepted: list, final: dict) -> Tally:
"""Контрольное число: сравниваются принятые клиентом, а не строки базы."""
lost, duplicated, wrong = [], [], []
ready = 0
for item in accepted:
state = final.get(item.id)
if state is None or state.status != "ready" or state.variants != 3:
lost.append(item.id)
continue
ready += 1
if state.sha256 != item.sha256:
wrong.append(item.id)
if state.rows != 1 or state.jobs != 1:
duplicated.append(item.id)
return Tally(len(accepted), ready, lost, duplicated, wrong)
def missed_damage(planted: dict, found: dict) -> list:
"""Испорченные строки, которых сверка не назвала своим классом: `planted` —
вложение → классы, хотя бы один из которых обязан быть назван."""
return [
item
for item, classes in planted.items()
if not set(classes) & set(found.get(item, ()))
]
# вердикты --------------------------------------------------------------------
class Verdict(NamedTuple):
name: str
ok: bool
measured: str
def verdict_h1(limits: dict, diff: TableDiff, comparison: Closed) -> Verdict:
ok = (
len(diff.after) <= limits["unexpected_after"]
and len(diff.before) <= limits["unexpected_before"]
and comparison.share >= limits["closed_share_min"]
and len(comparison.outside) <= limits["outside_available"]
and comparison.available_before > 0
)
return Verdict(
"H1",
ok,
f"unexpected rows: after {len(diff.after)}, before "
f"{len(diff.before)}; closed {comparison.closed} of "
f"{comparison.available_before} available before "
f"({comparison.share:.0%}); available outside: "
f"{len(comparison.outside)}",
)
def verdict_h2(
limits: dict,
rounds: list,
failed_requests: int,
requests: int,
*,
min_rounds: int,
) -> Verdict:
"""`rounds` — окна каждого повтора."""
problems = [
f"round {number}: {problem}"
for number, found in enumerate(rounds, 1)
for problem in window_problems(found, limits["windows_seconds"])
]
worst = {}
for found in rounds:
for item in found:
if item.seconds is not None:
worst[item.material] = max(
worst.get(item.material, 0.0),
item.seconds,
)
ok = (
not problems
and len(rounds) >= min_rounds
and failed_requests <= limits["failed_requests"]
and requests > 0
)
text = (
f"rounds {len(rounds)} (at least {min_rounds}); worst windows: "
+ ", ".join(f"{name} {worst[name]:.1f} s" for name in sorted(worst))
+ f"; failed requests {failed_requests} of {requests}"
)
if problems:
text += "; " + "; ".join(problems)
return Verdict("H2", ok, text)
def verdict_h3(
limits: dict,
tallies: list,
source_changes: int,
ready_seconds: list,
) -> Verdict:
lost = sum(len(item.lost) for item in tallies)
doubled = sum(len(item.duplicated) for item in tallies)
wrong = sum(len(item.wrong) for item in tallies)
accepted = sum(item.accepted for item in tallies)
slowest = max(ready_seconds, default=None)
ok = (
accepted > 0
and lost <= limits["lost"]
and doubled <= limits["duplicated"]
and wrong <= limits["wrong_sha256"]
and source_changes <= limits["source_changes"]
and slowest is not None
and slowest <= limits["ready_seconds"]
)
return Verdict(
"H3",
ok,
f"accepted {accepted}, ready "
f"{sum(item.ready for item in tallies)}, lost {lost}, duplicated "
f"{doubled}, other SHA-256 {wrong}; successful source changes "
f"{source_changes}; all ready "
+ ("never" if slowest is None else f"{slowest:.1f} s")
+ " after the identity returned",
)
def verdict_h4(
limits: dict,
*,
planted: int,
missed: int,
left: int,
overwritten: int,
overwrites_found: int,
) -> Verdict:
ok = (
planted > 0
and overwritten > 0
and missed <= limits["missed_damage"]
and left <= limits["left_after_repair"]
and overwritten - overwrites_found <= limits["missed_overwrites"]
)
return Verdict(
"H4",
ok,
f"damaged rows found {planted - missed} of {planted}, left after "
f"the repair {left}; overwritten originals found by the deep "
f"reconcile {overwrites_found} of {overwritten}, bytes returned 0",
)
def verdict_h5(limits: dict, lost: dict, actions: dict) -> Verdict:
"""`lost` — способ → потерянных заданий, `actions` — действие → удалось."""
failed = sorted(name for name, done in actions.items() if not done)
ok = (
bool(lost)
and bool(actions)
and all(count >= limits["lost_each_min"] for count in lost.values())
and len(failed) <= limits["failed_actions"]
)
return Verdict(
"H5",
ok,
"lost: "
+ ", ".join(f"{name} {count}" for name, count in sorted(lost.items()))
+ f"; actions done {len(actions) - len(failed)} of {len(actions)}"
+ (f"; not done: {', '.join(failed)}" if failed else ""),
)
# отчёт -----------------------------------------------------------------------
def why_text(row) -> str:
if not row.why:
return ""
kind = "код" if row.why[0] == ops.CODE else "остаточное"
return f"{kind}: {row.why[1]}"
def mark(expected: str, got: str) -> str:
return got if got == expected else f"**{got}** (ждали {expected})"
def table_markdown(rows, before: dict, after: dict) -> list:
lines = [
"| Канал | Операция | «До» | «После» | Основание доступной |",
"| --- | --- | --- | --- | --- |",
]
for row in rows:
lines.append(
f"| {row.channel} | {row.title} (`{row.id}`) | "
+ (mark(row.before, before.get(row.id, "-")) if before else "-")
+ f" | {mark(row.after, after.get(row.id, '-'))} | "
f"{why_text(row)} |",
)
return lines
def channel_markdown(rows, before: dict, after: dict) -> list:
"""Строк по каналам: доступно «до», доступно «после», закрыто."""
lines = [
"| Канал | Строк | Доступно «до» | Доступно «после» | Закрыто |",
"| --- | --- | --- | --- | --- |",
]
channels = list(dict.fromkeys(row.channel for row in rows))
for channel in channels:
part = [row for row in rows if row.channel == channel]
was = [row for row in part if before.get(row.id) == ops.OK]
now = [row for row in part if after.get(row.id) == ops.OK]
shut = [row for row in was if after.get(row.id) != ops.OK]
lines.append(
f"| {channel} | {len(part)} | {len(was)} | {len(now)} | "
f"{len(shut)} |",
)
return lines
def windows_markdown(rounds: list, limits: dict) -> list:
header = " | ".join(f"повтор {n}" for n in range(1, len(rounds) + 1))
lines = [
f"| Материал | {header} | порог | перестал после команды |",
"| --- |" + " --- |" * (len(rounds) + 2),
]
for index, material in enumerate(MATERIALS):
cells = []
commands = []
for found in rounds:
item = found[index]
cells.append(
"не измерено"
if item.seconds is None
else f"{item.seconds:.1f} с"
+ (" (действует)" if item.after_last else ""),
)
if item.command not in commands:
commands.append(item.command)
lines.append(
f"| {TITLES[material]} | {' | '.join(cells)} | "
f"{limits[material]} с | {', '.join(commands)} |",
)
return lines