Files
mtusi2026lab7/student-tests/test_worker_down.py
T
alenchha 861e7722b5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application stand (lab7) / stand (pull_request) Canceled after 0s
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

85 lines
4.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""Grade 3 demo: worker stopped -> upload 202 -> message with attachment -> restart API + broker (volumes kept)
-> worker started -> ready + thumbnail. Then an explicit duplicate delivery of the finished job is a no-op.
python3 student-tests/test_worker_down.py (stack from REPORT.md must be running)
"""
import hashlib
import time
from stand import (Client, check, compose, started_at, get, log, objects_of, wait_queue, run, sql, upload, wait_http_ready,
wait_status, unique_name, SAMPLE)
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
log("stop all workers")
compose("stop", "-t", "20", "worker")
try:
att = upload(c, alice, chat, filename=unique_name())
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None, "upload must be 202 queued")
log("upload 202 queued id=%s" % att["id"])
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"]
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
log("message %s created with queued attachment" % msg["id"])
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], 409, actor=bob)
c.message(bob, chat, "другие сообщения работают")
depth = wait_queue()
log("broker queue while worker is down:", depth)
check(depth and depth["ready"] >= 1, "job must be waiting in the broker")
unpublished = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
check(unpublished == "0", "outbox row must be published with confirm")
log("restart api-1 api-2 rabbitmq (volumes kept)")
before = started_at("api-1", "api-2", "rabbitmq")
compose("restart", "-t", "10", "rabbitmq", "api-1", "api-2")
wait_http_ready(c)
after = started_at("api-1", "api-2", "rabbitmq")
log("started before:", before)
log("started after: ", after)
check(before != after, "containers must really restart")
check(get(c, bob, att["id"])["status"] == "queued", "still queued after restart, nothing lost")
depth = wait_queue()
log("broker queue after broker restart:", depth)
check(depth and depth["ready"] >= 1, "durable message must survive broker restart")
finally:
log("start workers")
compose("start", "worker")
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
check(ready["status"] == "ready", "expected ready, got %s" % ready["status"])
log("status sequence observed:", " -> ".join(seen))
names = sorted(v["name"] for v in ready["variants"])
check(names == ["crop", "optimized", "thumbnail"], "expected thumbnail+crop+optimized, got %s" % names)
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail 256x160")
body = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
check(hashlib.sha256(body).hexdigest() == thumb["sha256"], "thumbnail checksum")
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
check(orig == SAMPLE, "original unchanged byte for byte")
keys = objects_of(att["id"])
log("objects:", keys)
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys), "original + 3 variants, staging removed")
log("redelivery: republish the finished job through the outbox (duplicate message)")
sql("INSERT INTO outbox (job_id, payload, available_at, created_at) SELECT o.job_id, o.payload, now(), now()"
" FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='%s' ORDER BY o.id LIMIT 1"
% att["id"])
time.sleep(5)
again = get(c, bob, att["id"])
check(again["status"] == "ready" and again["variants"] == ready["variants"], "duplicate must not change the result")
rows = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att["id"])[0][0]
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att["id"])[0][0]
check(rows == "3" and succeeded == "1", "one set of variants and one success (rows=%s succeeded=%s)" % (rows, succeeded))
check(len(objects_of(att["id"])) == 4, "no new objects after duplicate")
noop = compose("logs", "--since", "30s", "worker")
check("decision=done" in noop, "worker must log the duplicate as no-op")
log("duplicate acked as no-op: variants=%s successes=%s" % (rows, succeeded))
print("PASS: worker down / API+broker restart / redelivery no-op")
if __name__ == "__main__":
run(main)