Files
mtusi2026lab4/student-tests/login_flood.py
T
zemiles c5a07dc253 ЛР 4 — БПИ2303 — Лазарев — на 4
Перенос lab3 и вложения в приватном S3 (SeaweedFS 4.50).

- POST /chats/{id}/attachments: потоковый приём PNG/JPEG в безымянный
  временный файл, SHA-256 на лету, лимиты 10 MiB / 40 Мпикс до чтения
  и декодирования, проверка MIME по содержимому, валидация filename.
- Порядок записи pending -> S3 PUT -> ready с компенсацией; janitor
  сверяет БД и bucket (dry-run, grace period, advisory lock).
- GET /attachments/{id} и /content только участникам чата, без redirect;
  attachment_ids в сообщениях с проверкой принадлежности чату.
- Отдельные S3-ключи api/janitor/admin с ограниченными правами,
  идемпотентный bootstrap bucket, служебные порты SeaweedFS закрыты.
- Ограничение параллельных S3 PUT и MALLOC_ARENA_MAX: пик RSS API
  178-189 -> 95-102 MiB; лимиты памяти и restart для SeaweedFS после OOM.
- Тесты уровня 4 (негативные, failover вложений, отказы S3/БД, память)
  и доказательства в evidence/, заполнен REPORT.md.
2026-11-07 01:44:58 +03:00

173 lines
7.6 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.
#!/usr/bin/env python3
"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB.
Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики
256 MiB. Без ограничения параллельных проверок несколько одновременных входов
приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм.
Что измеряется:
* статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и
ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy);
* «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном —
обычные пользователи не должны получать ошибки из-за шторма входов;
* состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt.
Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json
"""
import argparse
import base64
import json
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
from collections import Counter
TIMEOUT = 10.0
def http(base, method, path, headers=None, body=None):
data = json.dumps(body).encode() if body is not None else None
h = dict(headers or {})
if data is not None:
h["Content-Type"] = "application/json"
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
return r.status, r.headers, r.read()
except urllib.error.HTTPError as e:
return e.code, e.headers, e.read()
def is_contract_error(headers, raw):
if not (headers.get("Content-Type") or "").startswith("application/json"):
return False
try:
err = json.loads(raw)["error"]
return bool(err["code"] and err["message"] and err["request_id"])
except (ValueError, KeyError, TypeError):
return False
def api_containers():
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True,
text=True, check=True).stdout.split()
out = {}
for cid in ids:
info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True,
check=True).stdout)[0]
out[info["Name"].lstrip("/")] = {
"status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"],
"restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]}
return out
def oom_events(since):
"""Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled
сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker."""
out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1),
"--filter", "type=container", "--filter", "event=oom",
"--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout
return sorted(Counter(out.split()).items())
def main():
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://localhost:8080")
p.add_argument("--parallel", type=int, default=24)
p.add_argument("--duration", type=float, default=20)
p.add_argument("--output")
a = p.parse_args()
base = a.base_url.rstrip("/")
username = "flood_" + uuid.uuid4().hex[:10]
password = "correct-horse-" + uuid.uuid4().hex[:8]
st, _, _ = http(base, "POST", "/api/v1/users",
body={"username": username, "display_name": "Flood", "password": password})
assert st == 201, st
basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode()
st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
assert st == 201, st
token = json.loads(raw)["token"]
bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode()
before = api_containers()
wall0 = time.time()
stop = threading.Event()
lock = threading.Lock()
flood, victim = Counter(), Counter()
non_json_errors = Counter()
retry_after_503 = [0, 0] # [503 всего, из них с Retry-After]
def record(counter, status, headers, raw):
with lock:
counter[str(status)] += 1
if status >= 400 and not is_contract_error(headers, raw):
non_json_errors[str(status)] += 1
if status == 503 and counter is flood:
retry_after_503[0] += 1
retry_after_503[1] += bool(headers.get("Retry-After"))
def flooder():
while not stop.is_set():
try:
record(flood, *http(base, "POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + bad}))
except Exception as exc: # обрыв соединения, timeout
with lock:
flood["exc:" + type(exc).__name__] += 1
def prober():
while not stop.is_set():
try:
record(victim, *http(base, "GET", "/api/v1/users/me",
headers={"Authorization": "Bearer " + token}))
except Exception as exc:
with lock:
victim["exc:" + type(exc).__name__] += 1
time.sleep(0.05)
threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)]
threads.append(threading.Thread(target=prober, daemon=True))
t0 = time.monotonic()
for t in threads:
t.start()
time.sleep(a.duration)
stop.set()
for t in threads:
t.join(TIMEOUT + 1)
elapsed = time.monotonic() - t0
time.sleep(3) # дать restart-policy отработать, если реплика упала
after = api_containers()
restarted = [n for n in after if n in before and (
after[n]["restart_count"] != before[n]["restart_count"]
or after[n]["started_at"] != before[n]["started_at"])]
victim_ok = victim.get("200", 0)
victim_total = sum(victim.values())
summary = {
"parallel": a.parallel, "duration_s": round(elapsed, 1),
"flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1),
"flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]),
"victim_statuses": dict(victim),
"victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None,
"non_contract_error_bodies": dict(non_json_errors),
"containers_before": before, "containers_after": after,
"oom_events": dict(oom_events(wall0)),
"restarted": restarted,
}
summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0
and victim_ok == victim_total and not non_json_errors)
text = json.dumps(summary, ensure_ascii=False, indent=2)
print(text)
if a.output:
with open(a.output, "w", encoding="utf-8") as f:
f.write(text + "\n")
return 0 if summary["pass"] else 1
if __name__ == "__main__":
raise SystemExit(main())