forked from mtusi2026/mtusi2026lab7
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS. - Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2. - Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1. - TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert, mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape. - OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором, auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login. - Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и пользователи брокера выдаются из OpenBao. - Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе. - Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL, no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API. - Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao, hardening; evidence, в т.ч. прогон из чистого clone.
121 lines
6.9 KiB
Python
121 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
||
"""Аудит F01: очистка staging janitor и операторский replay не теряют исходник принятой работы.
|
||
|
||
python3 student-tests/janitor_replay_race.py --output evidence/janitor-replay-race.json
|
||
|
||
Готовим три failed-вложения (fault-transient-always -> retry_exhausted; worker на время теста
|
||
с WORKER_FAULT_INJECTION=1). Перед каждым сценарием «старим» ровно одно вложение (updated_at
|
||
на 2 суток назад > STAGING_RETENTION_SECONDS), чтобы janitor считал его staging просроченным.
|
||
|
||
C (опасное чередование из аудита): janitor уже выбрал кандидата (учебная пауза
|
||
JANITOR_PAUSE_AFTER_SELECT_SECONDS), в это время replay коммитится. Ожидаем: janitor под
|
||
блокировкой перепроверяет, видит queued и ПРОПУСКАЕТ (staging_skipped_changed); staging
|
||
не освобождён; задание доходит до ready.
|
||
A (replay -> janitor): replay принят, janitor вложение не трогает, ready.
|
||
B (janitor -> replay): janitor снимает staging_key и удаляет объект; replay получает
|
||
refused_staging_expired — принятой работы без исходника не возникает.
|
||
Инвариант во всех случаях: не бывает «replay принят, а staging удалён».
|
||
"""
|
||
import argparse
|
||
import json
|
||
import subprocess
|
||
import time
|
||
|
||
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, ops, recreate, sql, upload, wait_status,
|
||
ROOT)
|
||
|
||
FAULT_ENV = {"WORKER_FAULT_INJECTION": "1", "JOB_RETRY_BASE_SECONDS": "1", "JOB_RETRY_MAX_SECONDS": "4"}
|
||
|
||
|
||
def run_janitor():
|
||
t = time.monotonic()
|
||
out = compose("exec", "-T", "janitor", "python", "/app/src/janitor.py", "--once").stdout
|
||
return json.loads(out.strip().splitlines()[-1]), round(time.monotonic() - t, 2)
|
||
|
||
|
||
def replay(att_id):
|
||
proc = compose("exec", "-T", "janitor", "python", "/app/src/ops.py", "replay", att_id, "--reason", "race test",
|
||
ok=False)
|
||
return json.loads(proc.stdout)["replay"][0]["result"]
|
||
|
||
|
||
def age(att_id):
|
||
sql("UPDATE attachments SET updated_at = now() - interval '2 days' WHERE id = '%s'" % att_id)
|
||
|
||
|
||
def main():
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument("--base-url", default=None)
|
||
p.add_argument("--output")
|
||
args = p.parse_args()
|
||
log = Log("janitor staging cleanup vs operator replay")
|
||
c = Client(args.base_url, timeout=30)
|
||
alice, bob, _eve, chat = c.bootstrap()
|
||
recreate("worker", FAULT_ENV)
|
||
res = {}
|
||
try:
|
||
ids = [upload(c, alice, chat, SAMPLE_PNG, "fault-transient-always.png")["id"] for _ in range(3)]
|
||
for i in ids:
|
||
st = wait_status(c, bob, i, {"failed", "ready"}, 120)
|
||
check(st["status"] == "failed" and st["error_code"] == "retry_exhausted", "expected retry_exhausted")
|
||
z, x, y = ids
|
||
log.step("three failed attachments prepared", ids=ids)
|
||
|
||
# --- C: janitor выбрал кандидата -> replay закоммитился -> janitor удаляет? -----------
|
||
# Это чередование, которое аудит воспроизвёл на старом коде (исходник терялся).
|
||
age(z)
|
||
jn = subprocess.Popen(["docker", "compose", "exec", "-T", "-e", "JANITOR_PAUSE_AFTER_SELECT_SECONDS=4",
|
||
"janitor", "python", "/app/src/janitor.py", "--once"],
|
||
cwd=ROOT, stdout=subprocess.PIPE, text=True)
|
||
time.sleep(2.0) # janitor уже выбрал z и стоит в паузе
|
||
replay_out = replay(z) # replay коммитится между выборкой и захватом
|
||
jrep = json.loads(jn.communicate(timeout=60)[0].strip().splitlines()[-1])
|
||
ready = wait_status(c, bob, z, {"ready", "failed"}, 60)
|
||
ev = events(ops("inspect", z))
|
||
res["C_janitor_selected_then_replay"] = {
|
||
"attachment_id": z, "janitor_candidates_included_z": z in jrep["staging_candidates"],
|
||
"replay": replay_out, "janitor_staging_skipped_changed": jrep["staging_skipped_changed"],
|
||
"janitor_staging_failed_expired": jrep["staging_failed_expired"],
|
||
"final": ready["status"], "janitor_released_staging": "staging_released" in ev, "events": ev}
|
||
check(z in jrep["staging_candidates"] and replay_out == "replayed"
|
||
and jrep["staging_skipped_changed"] >= 1 and "staging_released" not in ev
|
||
and ready["status"] == "ready", "C: %s" % res["C_janitor_selected_then_replay"])
|
||
log.step("C: janitor selected z, replay committed, janitor rechecked under lock and skipped -> ready",
|
||
**res["C_janitor_selected_then_replay"])
|
||
|
||
# --- A: replay, потом janitor --------------------------------------------------
|
||
age(x)
|
||
r = replay(x)
|
||
jrep, _ = run_janitor()
|
||
info = ops("inspect", x)
|
||
res["A_replay_then_janitor"] = {"attachment_id": x, "replay": r,
|
||
"staging_object_present": bool(info["s3_staging_objects"]) or
|
||
info["attachment"]["status"] in ("processing", "ready")}
|
||
ready = wait_status(c, bob, x, {"ready", "failed"}, 60)
|
||
res["A_replay_then_janitor"]["final"] = ready["status"]
|
||
check(r == "replayed" and ready["status"] == "ready", "A: %s" % res["A_replay_then_janitor"])
|
||
log.step("A: replay first -> janitor leaves it -> ready", **res["A_replay_then_janitor"])
|
||
|
||
# --- B: janitor, потом replay --------------------------------------------------
|
||
age(y)
|
||
jrep, _ = run_janitor()
|
||
r = replay(y)
|
||
info = ops("inspect", y)
|
||
res["B_janitor_then_replay"] = {"attachment_id": y, "janitor_staging_failed_expired": jrep["staging_failed_expired"],
|
||
"replay": r, "status": info["attachment"]["status"],
|
||
"staging_key": info["attachment"]["staging_key"],
|
||
"staging_objects": info["s3_staging_objects"],
|
||
"events": events(info)[-3:]}
|
||
check(jrep["staging_failed_expired"] >= 1 and r == "refused_staging_expired"
|
||
and info["attachment"]["status"] == "failed", "B: %s" % res["B_janitor_then_replay"])
|
||
log.step("B: janitor first -> replay refused, no job without source", **res["B_janitor_then_replay"])
|
||
finally:
|
||
recreate("worker")
|
||
log.step("workers restored to .env configuration")
|
||
log.save(args.output, results=res)
|
||
print("PASS: janitor cleanup and replay never lose the source of accepted work")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|