ЛР 7 — БПИ2303 — Лазарев — на 3
Перенесена реализация 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.
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# Проверки lab4–lab5, не перенесённые на транспорт lab7
|
||||
|
||||
Эти сценарии (нагрузочный failover, медленный клиент, прогрессивный upload, права S3 через
|
||||
`http://s3:8333`, raw-сокеты к `http://lb:8080` и т. п.) написаны для plaintext-стенда lab5/lab6:
|
||||
они обращаются к `:8080`/`:8404` без TLS, через `http.client`/сокеты или со старыми общими
|
||||
credentials. В lab7 этих портов и credentials больше нет (только HTTPS :8443, mTLS внутри,
|
||||
секреты из OpenBao), поэтому скрипты здесь сохранены как история и **в lab7 не запускаются**.
|
||||
|
||||
Что их заменяет в lab7:
|
||||
|
||||
| Было | Чем покрыто сейчас |
|
||||
| --- | --- |
|
||||
| api_negative_lab5, attachments_negative | `tests/smoke.py` (HTTPS) + `student-tests/lab7_api_security.py` (посторонний, лимиты 413, logout/expiry) |
|
||||
| login_flood | `lab7_api_security.py` — `ratelimit.login_429_with_retry_after` |
|
||||
| s3_private_check | `lab7_tls_matrix.py` (анонимный доступ 403 по HTTPS) и `lab7_openbao.py` (у worker свой ключ) |
|
||||
| failover_bench, failover-each.sh, attachment_failover | `make test-failover` по HTTPS для обеих реплик (evidence/test-failover.txt) |
|
||||
| idempotency_concurrency | `tests/smoke.py`, `tests/load.py` по HTTPS |
|
||||
| upload_memory, slow_client, progressive_upload, s3_outage, queue_contract_check, variants_check | не перенесены (уровень 4 lab4/lab5); перенос — в «Следующих шагах» REPORT.md |
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии по внешнему аудиту (HTTP-уровень): F02, F05, F08, F09, F17.
|
||||
|
||||
python3 student-tests/api_negative_lab5.py --output evidence/api-negative-lab5.json
|
||||
|
||||
F08 непарный суррогат (JSON "\\ud800") в display_name / password / title / text -> 400, не 500;
|
||||
то же в filename (%ED%A0%80 — невалидный UTF-8) -> 400
|
||||
F17 HEAD / OPTIONS / неизвестный метод -> 405 JSON с X-Request-Id и X-Instance-Id (у HEAD без тела)
|
||||
F05 PNG с байтом фильтра 5 и 255, interlaced PNG с плохим фильтром -> 415, строка не создана
|
||||
F09 объект ready-вложения испорчен в S3 (та же длина) -> content 503, а не 200 с чужими байтами
|
||||
F02 4 progressive 4:4:4 + 1 progressive 4:2:0 + 1 baseline JPEG ~40 Мпикс одновременно -> все 202
|
||||
и ready; RestartCount/OOMKilled реплик API не изменились
|
||||
"""
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, container_ids, ops, sql, upload, wait_status)
|
||||
|
||||
|
||||
def api_state():
|
||||
out = {}
|
||||
for cid in container_ids("api"):
|
||||
r = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.RestartCount}} {{.State.OOMKilled}}", cid],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
out[r[0].lstrip("/")] = {"restarts": int(r[1]), "oom_killed": r[2] == "true"}
|
||||
return out
|
||||
|
||||
|
||||
def raw(base, method, path, body=None, headers=None):
|
||||
u = urlsplit(base)
|
||||
conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=15)
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
r = conn.getresponse()
|
||||
data = r.read()
|
||||
conn.close()
|
||||
return r.status, dict((k.lower(), v) for k, v in r.getheaders()), data
|
||||
|
||||
|
||||
def png(w, h, raw_rows, interlace=0):
|
||||
def chunk(k, d):
|
||||
return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d) & 0xFFFFFFFF)
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, interlace))
|
||||
+ chunk(b"IDAT", zlib.compress(raw_rows)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("audit regressions: unicode, protocol errors, PNG filters, download integrity, progressive JPEG")
|
||||
c = Client(args.base_url, timeout=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
res = {}
|
||||
|
||||
# --- F08 -------------------------------------------------------------------------
|
||||
bad = '"\\ud800"'
|
||||
cases = {
|
||||
"display_name": ("/api/v1/users", None,
|
||||
'{"username":"u_%s","display_name":%s,"password":"Passw0rd-long-1"}' % (uuid.uuid4().hex[:10], bad)),
|
||||
"password": ("/api/v1/users", None,
|
||||
'{"username":"u_%s","display_name":"x","password":%s}' % (uuid.uuid4().hex[:10], '"Passw0rd-long-\\ud800"')),
|
||||
"chat title": ("/api/v1/chats", alice, '{"title":%s,"member_ids":["%s"]}' % (bad, alice["id"])),
|
||||
"message text": ("/api/v1/chats/%s/messages" % chat["id"], alice, '{"text":%s}' % bad),
|
||||
}
|
||||
f08 = {}
|
||||
for name, (path, actor, body) in cases.items():
|
||||
h = {"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex}
|
||||
if actor:
|
||||
h["Authorization"] = "Bearer " + actor["token"]
|
||||
st, hd, data = raw(args.base_url, "POST", path, body.encode(), h)
|
||||
code = json.loads(data)["error"]["code"] if data.startswith(b"{") else None
|
||||
f08[name] = {"status": st, "code": code}
|
||||
check(st == 400 and code == "invalid_request", "F08 %s: %s %s" % (name, st, code))
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%%ED%%A0%%80.png" % chat["id"], 400, actor=alice,
|
||||
raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
|
||||
f08["filename %ED%A0%80"] = {"status": r["status"]}
|
||||
res["F08"] = f08
|
||||
log.step("F08 lone surrogates -> 400", **f08)
|
||||
|
||||
# --- F17 -------------------------------------------------------------------------
|
||||
f17 = {}
|
||||
for method, path in (("HEAD", "/health/live"), ("OPTIONS", "/api/v1/chats"), ("BREW", "/health/live"),
|
||||
("TRACE", "/health/live")):
|
||||
st, hd, data = raw(args.base_url, method, path)
|
||||
item = {"status": st, "x_request_id": bool(hd.get("x-request-id")), "x_instance_id": bool(hd.get("x-instance-id")),
|
||||
"content_type": hd.get("content-type"), "body_bytes": len(data)}
|
||||
if method != "HEAD":
|
||||
item["code"] = json.loads(data)["error"]["code"]
|
||||
item["request_id_matches"] = json.loads(data)["error"]["request_id"] == hd.get("x-request-id")
|
||||
check(item["request_id_matches"], "F17 request_id")
|
||||
check(st == 405 and item["x_request_id"] and item["x_instance_id"], "F17 %s: %s" % (method, item))
|
||||
check(method != "HEAD" or len(data) == 0, "HEAD must have no body")
|
||||
f17[method] = item
|
||||
res["F17"] = f17
|
||||
log.step("F17 unsupported methods -> 405 JSON", **f17)
|
||||
|
||||
# --- F05 -------------------------------------------------------------------------
|
||||
f05 = {}
|
||||
import sys
|
||||
sys.path.insert(0, str(__import__("lab5lib").ROOT / "src"))
|
||||
import images
|
||||
w, h = 13, 11
|
||||
passes = images._png_passes(w, h, 24, 1)
|
||||
adam = bytearray(b"".join((b"\x00" + bytes(rb - 1)) * rows for rows, rb in passes))
|
||||
adam[sum(rr * bb for rr, bb in passes[:4]) + passes[4][1] * 2] = 9
|
||||
samples = {"filter 5 (1x1)": png(1, 1, b"\x05\x01\x02\x03"),
|
||||
"filter 255 in row 57 (10x100)": png(10, 100, b"".join((b"\xff" if i == 57 else b"\x00") + bytes(30)
|
||||
for i in range(100))),
|
||||
"Adam7, filter 9 in pass 5": png(w, h, bytes(adam), interlace=1)}
|
||||
for name, data in samples.items():
|
||||
fname = "badfilter-%s.png" % uuid.uuid4().hex[:8]
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], fname), 415, actor=alice,
|
||||
raw=data, headers={"Content-Type": "image/png"})
|
||||
rows = int(sql("SELECT count(*) FROM attachments WHERE filename = '%s'" % fname)[0][0])
|
||||
check(rows == 0, "F05 row created")
|
||||
f05[name] = {"status": r["status"], "bytes": len(data), "rows_created": rows}
|
||||
res["F05"] = f05
|
||||
log.step("F05 bad PNG filters -> 415, no job", **f05)
|
||||
|
||||
# --- F09 -------------------------------------------------------------------------
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "integrity.png")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, 60)
|
||||
check(ready["status"] == "ready", "F09 not ready")
|
||||
key = ops("inspect", att["id"])["attachment"]["object_key"]
|
||||
compose("--profile", "tools", "run", "--rm", "-T", "checks", "/app/student-tests/s3_tamper.py", key)
|
||||
st, hd, data = raw(args.base_url, "GET", "/api/v1/attachments/%s/content" % att["id"],
|
||||
headers={"Authorization": "Bearer " + bob["token"]})
|
||||
thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)
|
||||
tv = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
|
||||
import hashlib
|
||||
res["F09"] = {"attachment_id": att["id"], "tampered_original_status": st,
|
||||
"code": json.loads(data)["error"]["code"] if st >= 400 else None,
|
||||
"untouched_thumbnail_status": thumb["status"],
|
||||
"thumbnail_sha_ok": hashlib.sha256(thumb["bytes"]).hexdigest() == tv["sha256"]}
|
||||
check(st == 503 and res["F09"]["thumbnail_sha_ok"], "F09: %s" % res["F09"])
|
||||
log.step("F09 corrupted object -> 503, intact variant still 200", **res["F09"])
|
||||
|
||||
# --- F02 -------------------------------------------------------------------------
|
||||
before = api_state()
|
||||
proc = compose("--profile", "tools", "run", "--rm", "-T", "checks", "/app/student-tests/progressive_upload.py",
|
||||
"--base-url", "http://lb:8080", "--output", "/app/evidence/progressive-upload.json", ok=False,
|
||||
timeout=600)
|
||||
after = api_state()
|
||||
res["F02"] = {"checks_exit": proc.returncode, "api_before": before, "api_after": after,
|
||||
"tail": proc.stdout.strip().splitlines()[-1:]}
|
||||
check(proc.returncode == 0 and before == after and not any(v["oom_killed"] for v in after.values()),
|
||||
"F02: %s" % res["F02"])
|
||||
log.step("F02 concurrent ~40 Mpx progressive JPEG: all ready, API not restarted", **res["F02"])
|
||||
log.save(args.output, results=res)
|
||||
print("PASS: F02, F05, F08, F09, F17 regressions")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> остановка ИМЕННО обслужившей upload реплики -> download через другую.
|
||||
|
||||
python3 student-tests/attachment_failover.py [--output evidence/attachment-failover.json]
|
||||
|
||||
Для каждой API-реплики по очереди: загрузить файл так, чтобы его обслужила эта реплика
|
||||
(round-robin LB, повторяем до попадания), остановить её scripts/stop-one.sh
|
||||
(SIGTERM, контейнер остаётся остановленным), затем 5 раз скачать оригинал через LB и
|
||||
проверить SHA-256 и что отвечает уже другая реплика. Восстановление — scripts/start-all.sh.
|
||||
Доказывает, что на API нет обязательного локального файла оригинала.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
CONTENT = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
instances = set()
|
||||
for _ in range(10):
|
||||
instances.add(c.call("GET", "/health/ready")["headers"]["X-Instance-Id"])
|
||||
check(len(instances) >= 2, "need >=2 replicas")
|
||||
rounds = []
|
||||
for target in sorted(instances):
|
||||
for _ in range(20): # round-robin: попадаем в нужную реплику за пару попыток
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=failover.png" % chat["id"], 202, actor=alice,
|
||||
raw=CONTENT, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
if r["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise SystemExit("could not hit replica " + target)
|
||||
att = c.wait_ready(alice, r["json"]) # lab5: 202 queued -> ждём ready, затем отказ реплики
|
||||
stop = subprocess.run([str(ROOT / "scripts/stop-one.sh")], env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
check(stop.returncode == 0, "stop-one failed")
|
||||
downloads = []
|
||||
for _ in range(5):
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
|
||||
downloads.append({"instance": d["headers"]["X-Instance-Id"],
|
||||
"sha256_ok": hashlib.sha256(d["bytes"]).hexdigest() == att["sha256"] == hashlib.sha256(CONTENT).hexdigest(),
|
||||
"ms": round(d["elapsed"] * 1000, 1)})
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
ok = all(x["sha256_ok"] and x["instance"] != target for x in downloads) and meta["status"] == "ready"
|
||||
rounds.append({"uploaded_by": target, "stopped": target, "downloads": downloads, "pass": ok})
|
||||
print(json.dumps(rounds[-1]), flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/start-all.sh")], capture_output=True, timeout=120, check=True)
|
||||
time.sleep(4) # HAProxy: rise 2 * inter 1s
|
||||
summary = {"replicas": sorted(instances), "rounds": rounds, "pass": all(r["pass"] for r in rounds)}
|
||||
print(json.dumps({"pass": summary["pass"], "rounds": len(rounds)}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (из lab4; в lab5 upload -> 202, затем ready). Запуск на учебном стенде:
|
||||
|
||||
python3 student-tests/attachments_negative.py [--base-url http://localhost:8080] [--output evidence/attachments-negative.json]
|
||||
|
||||
Использует публичный tests/client.py: каждый ответ проверяется на код, X-Request-Id,
|
||||
X-Instance-Id и (для ошибок) формат {"error":{code,message,request_id}}. Отдельно
|
||||
проверяется, что ни один пользовательский ввод не дал 5xx. Все файлы синтетические и
|
||||
генерируются на лету (большие в Git не хранятся).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
results = []
|
||||
|
||||
|
||||
def chunk(ctype, data):
|
||||
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, raw, color_type=2, depth=8):
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Несжимаемый RGB PNG размером чуть меньше target_bytes (zlib level 0)."""
|
||||
width = 1024
|
||||
row = 1 + width * 3
|
||||
height = (target_bytes - 200) // (row + 6 * 0 + 1)
|
||||
while True:
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
data = png(width, height, zlib.compress(raw, 0))
|
||||
if len(data) <= target_bytes:
|
||||
return data
|
||||
height -= 16
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self, c):
|
||||
self.c = c
|
||||
|
||||
def case(self, name, method, path, expected, actor=None, **kw):
|
||||
try:
|
||||
r = self.c.call(method, path, expected, actor=actor, **kw)
|
||||
code = r["json"]["error"]["code"] if r["json"] and "error" in r["json"] else None
|
||||
results.append({"case": name, "expected": expected, "status": r["status"], "error_code": code, "pass": True})
|
||||
return r
|
||||
except Failure as exc:
|
||||
results.append({"case": name, "expected": expected, "error": str(exc), "pass": False})
|
||||
return None
|
||||
|
||||
def upload(self, name, actor, chat, data, expected, ctype="image/png", filename="f.png", raw_query=None):
|
||||
q = raw_query if raw_query is not None else "filename=" + quote(filename, safe="")
|
||||
return self.case(name, "POST", "/api/v1/chats/%s/attachments?%s" % (chat["id"], q), expected,
|
||||
actor=actor, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 202 else None)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=60)
|
||||
s = Suite(c)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "второй чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
|
||||
# --- позитивные контрольные ---
|
||||
ok_png = s.upload("valid PNG fixture", alice, chat, PNG, 202)
|
||||
ok_jpg = s.upload("valid JPEG", bob, chat, JPEG, 202, ctype="image/jpeg", filename="photo.jpg")
|
||||
uni = s.upload("unicode filename", alice, chat, PNG, 202, filename="фото отпуска 🙂.png")
|
||||
if uni:
|
||||
check(uni["json"]["filename"] == "фото отпуска 🙂.png", "unicode filename changed")
|
||||
def ready(r): # lab5: upload -> 202 queued, байты доступны после ready
|
||||
if r:
|
||||
c.wait_ready(alice if r["json"]["owner_id"] == alice["id"] else bob, r["json"])
|
||||
for r in (ok_png, ok_jpg):
|
||||
ready(r)
|
||||
if ok_jpg:
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % ok_jpg["json"]["id"], actor=alice)
|
||||
check(d["bytes"] == JPEG and d["headers"].get_content_type() == "image/jpeg", "jpeg download mismatch")
|
||||
check(d["headers"].get("X-Content-Type-Options") == "nosniff", "nosniff missing")
|
||||
near = noise_png(MAX_BYTES)
|
||||
big = s.upload("PNG near 10 MiB limit (%d B)" % len(near), alice, chat, near, 202, filename="big.png")
|
||||
if big:
|
||||
check(big["json"]["sha256"] == hashlib.sha256(near).hexdigest(), "big sha mismatch")
|
||||
ready(big)
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % big["json"]["id"], actor=bob)
|
||||
check(hashlib.sha256(d["bytes"]).hexdigest() == big["json"]["sha256"], "big download mismatch")
|
||||
|
||||
# --- размер и пиксели ---
|
||||
s.upload("too large: 10 MiB + 1 B", alice, chat, near + b"\0" * (MAX_BYTES + 1 - len(near)), 413)
|
||||
s.upload("pixel bomb header 100000x100000", alice, chat, png(100000, 100000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("PNG 7000x6000 = 42 Mpx (> 40 Mpx)", alice, chat, png(7000, 6000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("zlib bomb: 100x100 header, 50 MB inflated", alice, chat,
|
||||
png(100, 100, zlib.compress(b"\0" * 50_000_000, 9), color_type=0), 415)
|
||||
|
||||
# --- повреждённые изображения ---
|
||||
flipped = bytearray(PNG); flipped[5000] ^= 0xFF
|
||||
s.upload("corrupted PNG (byte flipped, bad CRC)", alice, chat, bytes(flipped), 415)
|
||||
s.upload("truncated PNG", alice, chat, PNG[:-4000], 415)
|
||||
s.upload("PNG without IEND", alice, chat, PNG[:-12], 415)
|
||||
s.upload("PNG with appended ZIP (polyglot)", alice, chat, PNG + b"PK\x03\x04" + os.urandom(64), 415)
|
||||
s.upload("truncated JPEG", alice, chat, JPEG[:len(JPEG) // 2], 415, ctype="image/jpeg")
|
||||
s.upload("JPEG header only", alice, chat, JPEG[:200], 415, ctype="image/jpeg")
|
||||
s.upload("empty body", alice, chat, b"", 415)
|
||||
|
||||
# --- подмена MIME ---
|
||||
s.upload("JPEG bytes declared image/png", alice, chat, JPEG, 415)
|
||||
s.upload("PNG bytes declared image/jpeg", alice, chat, PNG, 415, ctype="image/jpeg")
|
||||
s.upload("text declared image/png", alice, chat, b"<html><script>alert(1)</script></html>" * 4, 415)
|
||||
s.upload("GIF declared image/png", alice, chat, b"GIF89a" + os.urandom(200), 415)
|
||||
s.upload("PNG declared text/html", alice, chat, PNG, 415, ctype="text/html")
|
||||
s.upload("PNG declared image/svg+xml", alice, chat, PNG, 415, ctype="image/svg+xml")
|
||||
s.upload("multipart/form-data instead of raw", alice, chat, b"--x\r\n\r\n" + PNG + b"\r\n--x--", 415,
|
||||
ctype="multipart/form-data; boundary=x")
|
||||
|
||||
# --- опасные filename ---
|
||||
for label, query in (("../etc/passwd", "filename=" + quote("../passwd.png", safe="")),
|
||||
("slash", "filename=" + quote("a/b.png", safe="")),
|
||||
("backslash", "filename=" + quote("a\\b.png", safe="")),
|
||||
("NUL", "filename=a%00.png"),
|
||||
("newline", "filename=a%0A.png"),
|
||||
("bidi override U+202E", "filename=" + quote("gnp.exe", safe="")),
|
||||
("..", "filename=.."),
|
||||
("empty", "filename="),
|
||||
("whitespace only", "filename=%20%20"),
|
||||
("256 code points", "filename=" + quote("я" * 256, safe="")),
|
||||
("missing filename", ""),
|
||||
("filename twice", "filename=a.png&filename=b.png"),
|
||||
("invalid UTF-8", "filename=%FF%FE.png")):
|
||||
s.upload("filename: " + label, alice, chat, PNG, 400, raw_query=query)
|
||||
|
||||
# --- доступ и чужие объекты ---
|
||||
eve_att = s.upload("eve uploads to her own chat", eve, eve_chat, PNG, 202)
|
||||
s.upload("non-member uploads to alice chat", eve, chat, PNG, 404)
|
||||
s.case("upload without session", "POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 401,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
s.upload("upload to unknown chat", alice, {"id": str(uuid.uuid4())}, PNG, 404)
|
||||
if eve_att and ok_png:
|
||||
eid, aid = eve_att["json"]["id"], ok_png["json"]["id"]
|
||||
s.case("foreign attachment metadata", "GET", "/api/v1/attachments/" + eid, 404, actor=alice)
|
||||
s.case("foreign attachment content", "GET", "/api/v1/attachments/%s/content" % eid, 404, actor=alice)
|
||||
s.case("eve reads alice attachment", "GET", "/api/v1/attachments/%s/content" % aid, 404, actor=eve)
|
||||
key = lambda: {"Idempotency-Key": uuid.uuid4().hex} # noqa: E731
|
||||
s.case("message with foreign attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [eid]}, headers=key())
|
||||
s.case("message mixing own and foreign ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid, eid]}, headers=key())
|
||||
s.case("attachment of OTHER chat of the same user", "POST", "/api/v1/chats/%s/messages" % chat2["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid]}, headers=key())
|
||||
s.case("unknown attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]}, headers=key())
|
||||
s.case("malformed attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": ["not-a-uuid"]}, headers=key())
|
||||
s.case("duplicate attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [aid, aid]}, headers=key())
|
||||
s.case("11 attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, headers=key())
|
||||
s.case("attachment_ids not a list", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": aid}, headers=key())
|
||||
s.case("empty text without attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||||
actor=alice, body={"text": " "}, headers=key())
|
||||
m = s.case("empty text with attachment (bob links alice's file)", "POST",
|
||||
"/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob,
|
||||
body={"text": "", "attachment_ids": [aid]}, headers=key(), schema="Message")
|
||||
if m:
|
||||
check(m["json"]["attachment_ids"] == [aid], "attachment_ids lost")
|
||||
k = key()
|
||||
s.case("idempotent send with attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"attachment_ids": [aid], "text": "повтор"}, headers=k, schema="Message")
|
||||
s.case("same key, same body (key order changed)", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": [aid]}, headers=k, schema="Message")
|
||||
s.case("same key, different attachment_ids -> 409", "POST", "/api/v1/chats/%s/messages" % chat["id"], 409,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": []}, headers=k)
|
||||
s.case("variant=thumbnail (ready, lab5)", "GET",
|
||||
"/api/v1/attachments/%s/content?variant=thumbnail" % aid, 200, actor=bob)
|
||||
s.case("variant=bogus", "GET", "/api/v1/attachments/%s/content?variant=bogus" % aid, 400, actor=bob)
|
||||
s.case("variant=original", "GET", "/api/v1/attachments/%s/content?variant=original" % aid, 200, actor=bob)
|
||||
s.case("malformed attachment id in path", "GET", "/api/v1/attachments/zzz", 400, actor=bob)
|
||||
s.case("unknown attachment id", "GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=bob)
|
||||
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
server_errors = [r for r in results if r.get("status", 0) >= 500]
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-55s -> %s %s" % (
|
||||
r["case"], r.get("status", "-"), r.get("error_code") or r.get("error", "")))
|
||||
summary = {"cases": len(results), "failed": len(failed), "server_errors_5xx": len(server_errors),
|
||||
"pass": not failed and not server_errors}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"summary": summary, "results": results}, ensure_ascii=False, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Уровень 4: ПОСЛЕДОВАТЕЛЬНО останавливает КАЖДУЮ API-реплику под нагрузкой,
|
||||
# восстанавливая предыдущую перед следующей. Режимы:
|
||||
# stop — docker stop (SIGTERM -> graceful drain), штатная остановка/деплой;
|
||||
# kill — docker kill (SIGKILL), внезапное падение процесса без drain.
|
||||
# Результаты: evidence/failover-<mode>-<container>.json (+ .action.log).
|
||||
# Использование: scripts/failover-each.sh [stop|kill] ... (по умолчанию: stop kill)
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
MODES=${*:-stop kill}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
DURATION=${DURATION:-40}
|
||||
mkdir -p evidence
|
||||
|
||||
wait_all_up() {
|
||||
# API-контейнеры healthy и HAProxy видит их все UP (rise 2 * inter 1s).
|
||||
./scripts/start-all.sh >/dev/null
|
||||
n=$(docker compose ps -q api | wc -l | tr -d ' ')
|
||||
for _ in $(seq 1 60); do
|
||||
up=$(curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' ')
|
||||
[ "$up" -ge "$n" ] && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "HAProxy did not mark all $n api servers UP" >&2; return 1
|
||||
}
|
||||
|
||||
wait_all_up
|
||||
# Список фиксируется один раз: остановленная реплика пропала бы из `docker compose ps`.
|
||||
NAMES=$(docker compose ps --format '{{.Name}}' api | sort)
|
||||
for mode in $MODES; do
|
||||
for name in $NAMES; do
|
||||
wait_all_up
|
||||
cid=$(docker inspect -f '{{.Id}}' "$name"); short=$(echo "$cid" | cut -c1-12)
|
||||
case $mode in
|
||||
stop) action="docker stop -t 20 $cid" ;;
|
||||
kill) action="docker kill $cid" ;;
|
||||
*) echo "unknown mode $mode" >&2; exit 2 ;;
|
||||
esac
|
||||
echo "== $mode $name ($short) $(date -u +%FT%TZ)"
|
||||
out=evidence/failover-$mode-$name.json
|
||||
python3 student-tests/failover_bench.py --label "$mode $name" \
|
||||
--concurrency "$CONCURRENCY" --duration "$DURATION" --action-at 10 \
|
||||
--action "$action" --target-instance "$short" \
|
||||
--action-log "${out%.json}.action.log" --output "$out" \
|
||||
| python3 -c 'import json,sys; t=sys.stdin.read(); s=json.loads(t[:t.rindex("}")+1]); print(json.dumps({k:s[k] for k in ("baseline_ok_rps","post_action_ok_rps","capacity_ratio","errors_total","errors_by_kind","error_window_s","recovery_s","target_last_seen_s","lb_events","lost_confirmed","duplicate_texts","pass")},ensure_ascii=False)); sys.exit(0 if s["pass"] else 1)'
|
||||
echo "-- state after action:"; docker compose ps -a --format '{{.Name}} {{.Status}}' api
|
||||
done
|
||||
done
|
||||
wait_all_up
|
||||
echo "== restored: $(docker compose ps --format '{{.Name}} {{.Status}}' api | tr '\n' ';')"
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4).
|
||||
|
||||
Что делает:
|
||||
* CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения
|
||||
(с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1;
|
||||
* после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как
|
||||
требует контракт), поэтому подтверждённых дублей быть не должно;
|
||||
* на секунде --action-at запускается --action (например, docker stop/kill контейнера
|
||||
или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог;
|
||||
* параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты
|
||||
UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB);
|
||||
* в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые
|
||||
сообщения на месте, дублей нет.
|
||||
|
||||
Метрики (все времена — от старта action):
|
||||
errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв);
|
||||
error_window_s — от первой до последней ошибки после старта action;
|
||||
recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет;
|
||||
post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового;
|
||||
lb_down_detected_s — когда HAProxy пометил сервер DOWN;
|
||||
target_last_seen_s — последний ответ от остановленной реплики.
|
||||
|
||||
Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и
|
||||
стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
TIMEOUT = 2.0
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1)
|
||||
|
||||
|
||||
class Bench:
|
||||
def __init__(self, a):
|
||||
self.a = a
|
||||
self.base = a.base_url.rstrip("/")
|
||||
self.lock = threading.Lock()
|
||||
self.t0 = None
|
||||
self.stop = threading.Event()
|
||||
self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()})
|
||||
self.errors = [] # (t, kind)
|
||||
self.lat = [] # успешные задержки, с
|
||||
self.confirmed = {} # message id -> text
|
||||
self.retried_posts = 0
|
||||
self.lb_events = []
|
||||
self.inst_last_seen = {}
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def record(self, ok, dt, inst=None, ver=None, kind=None):
|
||||
t = self.now()
|
||||
with self.lock:
|
||||
b = self.per_sec[int(t)]
|
||||
if ok:
|
||||
b["ok"] += 1
|
||||
self.lat.append(dt)
|
||||
if inst:
|
||||
b["inst"][inst] += 1
|
||||
self.inst_last_seen[inst] = t
|
||||
if ver:
|
||||
b["ver"][ver] += 1
|
||||
else:
|
||||
b["err"] += 1
|
||||
self.errors.append((round(t, 3), kind))
|
||||
|
||||
def request(self, method, path, body=None, headers=None, expected=200):
|
||||
h = {"Authorization": "Bearer " + self.token}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
payload = json.loads(r.read())
|
||||
ok = r.status == expected
|
||||
self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"),
|
||||
r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status)
|
||||
return payload if ok else None
|
||||
except urllib.error.HTTPError as e:
|
||||
self.record(False, 0, kind="http_%d" % e.code)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.record(False, 0, kind=type(e).__name__)
|
||||
return None
|
||||
|
||||
def worker(self, n):
|
||||
chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
key = text = None
|
||||
i = 0
|
||||
while not self.stop.is_set():
|
||||
i += 1
|
||||
if i % 2:
|
||||
if key is None: # новый логический запрос; после ошибки ключ НЕ меняется
|
||||
key = "bench-%d-%s" % (n, uuid.uuid4().hex)
|
||||
text = "Нагрузка " + key
|
||||
else:
|
||||
with self.lock:
|
||||
self.retried_posts += 1
|
||||
msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201)
|
||||
if msg is not None:
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg["text"]
|
||||
key = None
|
||||
else:
|
||||
self.request("GET", chat_path + "?limit=20")
|
||||
|
||||
def poll_lb(self):
|
||||
prev = {}
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
with urllib.request.urlopen(self.a.stats_url, timeout=1) as r:
|
||||
rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# "))))
|
||||
head = rows[0]
|
||||
ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")}
|
||||
for row in rows[1:]:
|
||||
if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND":
|
||||
continue
|
||||
sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]]
|
||||
if sv in prev and prev[sv] != (st, addr):
|
||||
self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr,
|
||||
"from": prev[sv][0], "to": st})
|
||||
prev[sv] = (st, addr)
|
||||
except Exception: # noqa: BLE001 — статистика вспомогательная
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def history(self):
|
||||
c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", []
|
||||
while True:
|
||||
page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
if page["next_cursor"] is None:
|
||||
return items
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
def run(self):
|
||||
a = self.a
|
||||
self.client = Client(self.base, timeout=10)
|
||||
self.alice, _bob, _eve, self.chat = self.client.bootstrap()
|
||||
self.token = self.alice["token"]
|
||||
self.t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)]
|
||||
threads.append(threading.Thread(target=self.poll_lb, daemon=True))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.action_at)
|
||||
action = {"command": a.action, "started_s": round(self.now(), 3)}
|
||||
log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL
|
||||
proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT)
|
||||
rc = proc.wait(timeout=a.duration)
|
||||
action.update(finished_s=round(self.now(), 3), exit_code=rc)
|
||||
remaining = a.duration - self.now()
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
self.stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=TIMEOUT + 1)
|
||||
return self.summarize(action)
|
||||
|
||||
def summarize(self, action):
|
||||
a, t_act = self.a, action["started_s"]
|
||||
secs = sorted(self.per_sec)
|
||||
base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев
|
||||
baseline = sum(base) / len(base) if base else 0
|
||||
after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act]
|
||||
# Восстановление = конец окна ошибок: после этого момента все запросы до конца
|
||||
# прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно:
|
||||
# при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику).
|
||||
recovery = after[-1][0] if after else 0.0
|
||||
tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1]
|
||||
post = [self.per_sec[s]["ok"] for s in tail_secs]
|
||||
post_rps = sum(post) / len(post) if post else 0
|
||||
writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs)
|
||||
target = a.target_instance
|
||||
hist = self.history()
|
||||
ids = [m["id"] for m in hist]
|
||||
texts = [m["text"] for m in hist]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"],
|
||||
"instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])}
|
||||
for s in secs]
|
||||
total_ok = sum(b["ok"] for b in self.per_sec.values())
|
||||
total_err = len(self.errors)
|
||||
summary = {
|
||||
"label": a.label,
|
||||
"concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT,
|
||||
"action": action,
|
||||
"baseline_ok_rps": round(baseline, 1),
|
||||
"overall_ok_rps": round(total_ok / a.duration, 1),
|
||||
"requests_ok": total_ok, "errors_total": total_err,
|
||||
"error_rate": round(total_err / max(1, total_ok + total_err), 5),
|
||||
"errors_by_kind": dict(Counter(k for _, k in self.errors)),
|
||||
"error_window_s": [after[0][0], after[-1][0]] if after else None,
|
||||
"recovery_s": recovery,
|
||||
"post_action_ok_rps": round(post_rps, 1),
|
||||
"capacity_ratio": round(post_rps / baseline, 2) if baseline else None,
|
||||
"latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95),
|
||||
"p99": percentile(self.lat, 99)},
|
||||
"target_instance": target,
|
||||
"target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3)
|
||||
if target in self.inst_last_seen else None),
|
||||
"lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events],
|
||||
"posts_retried_same_key": self.retried_posts,
|
||||
"confirmed_messages": len(self.confirmed),
|
||||
"history_messages": len(hist), "lost_confirmed": len(lost),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"timeline": timeline,
|
||||
}
|
||||
summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0
|
||||
and summary["duplicate_texts"] == 0 and action["exit_code"] == 0
|
||||
and writes_after and recovery <= 10)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv")
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--duration", type=float, default=40)
|
||||
p.add_argument("--action-at", type=float, default=10)
|
||||
p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 <id>'")
|
||||
p.add_argument("--action-log")
|
||||
p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
s = Bench(a).run()
|
||||
brief = {k: v for k, v in s.items() if k != "timeline"}
|
||||
print(json.dumps(brief, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if s["pass"] else "FAIL")
|
||||
return 0 if s["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4).
|
||||
|
||||
Сценарий на каждый раунд:
|
||||
A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело.
|
||||
Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик,
|
||||
в истории ровно одно сообщение с этим текстом.
|
||||
B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно
|
||||
тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет.
|
||||
|
||||
Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их
|
||||
по репликам. Токены только в памяти; синтетические пользователи создаются заново.
|
||||
|
||||
python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата)
|
||||
|
||||
|
||||
def post(base, token, chat_id, key, text, barrier, out, idx):
|
||||
data = json.dumps({"text": text}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Idempotency-Key": key, "Connection": "close"})
|
||||
barrier.wait()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text)
|
||||
except urllib.error.HTTPError as e:
|
||||
out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text)
|
||||
except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку
|
||||
out[idx] = (0, repr(e), None, text)
|
||||
|
||||
|
||||
def burst(base, token, chat_id, key, texts):
|
||||
barrier = threading.Barrier(len(texts))
|
||||
out = [None] * len(texts)
|
||||
threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i))
|
||||
for i, t in enumerate(texts)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return out
|
||||
|
||||
|
||||
def history_texts(c, actor, chat):
|
||||
from urllib.parse import quote
|
||||
texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
while True:
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
if page["next_cursor"] is None:
|
||||
return texts
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rounds", type=int, default=20)
|
||||
p.add_argument("--parallel", type=int, default=16)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
c = Client(base)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
token = alice["token"]
|
||||
problems, instances = [], Counter()
|
||||
stats = {"same_body": Counter(), "conflicting_body": Counter()}
|
||||
|
||||
for rnd in range(a.rounds):
|
||||
# A) одинаковое тело
|
||||
key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex
|
||||
res = burst(base, token, chat["id"], key, [text] * a.parallel)
|
||||
stats["same_body"].update(str(r[0]) for r in res)
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
seen = {r[2] for r in res if r[2]}
|
||||
instances.update(r[2] for r in res if r[2])
|
||||
if any(r[0] != 201 for r in res) or len(ids) != 1:
|
||||
problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids)))
|
||||
if len(seen) < 2:
|
||||
problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen)))
|
||||
|
||||
# B) тот же ключ, два разных тела вперемешку
|
||||
key = "mixed-" + uuid.uuid4().hex
|
||||
t1, t2 = "Тело A " + key, "Тело B " + key
|
||||
res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2))
|
||||
stats["conflicting_body"].update(str(r[0]) for r in res)
|
||||
winners = {r[3] for r in res if r[0] == 201}
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
bad = [r[0] for r in res if r[0] not in (201, 409)]
|
||||
losers_ok = all(r[0] == 409 for r in res if r[3] not in winners)
|
||||
if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok:
|
||||
problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad))
|
||||
|
||||
texts = history_texts(c, alice, chat)
|
||||
dupes = [t for t, n in Counter(texts).items() if n > 1]
|
||||
if dupes:
|
||||
problems.append("duplicated messages in history: %d" % len(dupes))
|
||||
summary = {
|
||||
"rounds": a.rounds, "parallel_per_burst": a.parallel,
|
||||
"requests_total": a.rounds * a.parallel * 2,
|
||||
"status_counts": {k: dict(v) for k, v in stats.items()},
|
||||
"replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()),
|
||||
"messages_in_history": len(texts), "expected_messages": a.rounds * 2,
|
||||
"duplicates": len(dupes), "problems": problems,
|
||||
}
|
||||
if len(texts) != a.rounds * 2:
|
||||
problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if not problems else "FAIL")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Аудит F02: допустимые по контракту progressive JPEG ~40 Мпикс не должны ронять API.
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/progressive_upload.py \
|
||||
--base-url http://lb:8080 --output /app/evidence/progressive-upload.json
|
||||
|
||||
Файлы маленькие (~0,5–0,9 MB, гладкая картинка), но декодирование progressive JPEG требует
|
||||
буфер коэффициентов всего кадра: 4:2:0 ~140 MiB, 4:4:4 ~250 MiB (замер на Pillow 13).
|
||||
Одновременно загружаются 4 progressive 4:4:4 + 1 progressive 4:2:0 + 1 baseline: при двух
|
||||
репликах за round-robin LB на каждую приходится по 2 тяжёлых декодирования одновременно. Ожидаем:
|
||||
все 202, все ready, thumbnail 256x256. Что реплики API не были убиты (RestartCount, OOMKilled),
|
||||
проверяет хост-обёртка api_negative_lab5.py.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, "/app/tests")
|
||||
from client import Client, check # noqa: E402
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
SIDE = 6324 # 39 992 976 пикселей (< 40 000 000)
|
||||
|
||||
|
||||
def make(kind, seed):
|
||||
g = Image.radial_gradient("L").resize((SIDE, SIDE))
|
||||
img = Image.merge("RGB", (g, g.rotate(90 * seed), g.transpose(Image.Transpose.FLIP_TOP_BOTTOM)))
|
||||
kw = {"baseline": {}, "progressive_420": {"progressive": True},
|
||||
"progressive_444": {"progressive": True, "subsampling": 0}}[kind]
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "JPEG", quality=85, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://lb:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
c = Client(args.base_url, timeout=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
files = [("progressive_444", make("progressive_444", i)) for i in range(4)] + \
|
||||
[("progressive_420", make("progressive_420", 1)), ("baseline", make("baseline", 0))]
|
||||
|
||||
def up(item):
|
||||
kind, data = item
|
||||
t = time.monotonic()
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s.jpg" % (chat["id"], kind), [202, 413, 502, 503, 504],
|
||||
actor=alice, raw=data, headers={"Content-Type": "image/jpeg"}, schema="Attachment")
|
||||
return {"kind": kind, "bytes": len(data), "status": r["status"], "seconds": round(time.monotonic() - t, 2),
|
||||
"instance": r["headers"].get("X-Instance-Id"),
|
||||
"id": r["json"]["id"] if r["status"] == 202 else None,
|
||||
"error": r["json"]["error"]["code"] if r["status"] != 202 else None}
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(len(files)) as pool:
|
||||
results = list(pool.map(up, files))
|
||||
for r in results:
|
||||
print(json.dumps(r), flush=True)
|
||||
for r in results:
|
||||
check(r["status"] == 202, "%s upload: %s %s" % (r["kind"], r["status"], r["error"]))
|
||||
for r in results:
|
||||
att = c.wait_ready(bob, {"id": r["id"]}, wait_seconds=120)
|
||||
thumb = [v for v in att["variants"] if v["name"] == "thumbnail"][0]
|
||||
check((thumb["width"], thumb["height"]) == (256, 256), "thumbnail size")
|
||||
r["ready"] = True
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"side": SIDE, "pixels": SIDE * SIDE, "uploads": results},
|
||||
indent=1) + "\n")
|
||||
print("PASS: %d concurrent ~40 Mpx JPEG (progressive 4:4:4/4:2:0, baseline) -> 202 -> ready" % len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Аудит F12 и F11: разбор сообщения брокера = contracts/jobs.schema.json; версия pipeline.
|
||||
|
||||
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt rfc3339-validator
|
||||
.venv/bin/python student-tests/queue_contract_check.py --output evidence/queue-contract-check.json
|
||||
|
||||
F12: набор сообщений (валидные и контрпримеры из аудита) проверяется src/jobs.parse_message
|
||||
и jsonschema Draft 2020-12 с FormatChecker (date-time, uuid). Вердикты должны совпасть.
|
||||
F11: API с PIPELINE_VERSION=2 не стартует (понятная ошибка), а не работает «молча» неверно.
|
||||
"""
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "src"))
|
||||
import jobs # noqa: E402
|
||||
from jsonschema import Draft202012Validator, FormatChecker # noqa: E402
|
||||
|
||||
BASE = {"schema_version": 1, "job_id": "11111111-1111-4111-8111-111111111111", "type": "attachment.process.v1",
|
||||
"attachment_id": "22222222-2222-4222-8222-222222222222", "pipeline_version": 1, "attempt": 1,
|
||||
"created_at": "2026-09-01T12:00:00Z"}
|
||||
|
||||
|
||||
def variant(**kw):
|
||||
m = copy.deepcopy(BASE)
|
||||
for k, v in kw.items():
|
||||
if v is None:
|
||||
m.pop(k, None)
|
||||
else:
|
||||
m[k] = v
|
||||
return m
|
||||
|
||||
|
||||
CASES = {
|
||||
"valid minimal": variant(),
|
||||
"valid with trace context": variant(traceparent="00-" + "a" * 32 + "-" + "b" * 16 + "-01", tracestate="k=v"),
|
||||
"valid created_at with offset and fraction": variant(created_at="2026-09-01T15:00:00.123+03:00"),
|
||||
"schema_version true (audit)": variant(schema_version=True),
|
||||
"created_at date only (audit)": variant(created_at="2026-01-01"),
|
||||
"traceparent number (audit)": variant(traceparent=123),
|
||||
"tracestate 513 chars (audit)": variant(tracestate="x" * 513),
|
||||
"attempt true": variant(attempt=True),
|
||||
"attempt 0": variant(attempt=0),
|
||||
"pipeline_version 1.0": variant(pipeline_version=1.0),
|
||||
"job_id not uuid": variant(job_id="not-a-uuid"),
|
||||
"job_id uuid without hyphens": variant(job_id="11111111111141118111111111111111"),
|
||||
"extra field": variant(url="http://evil/"),
|
||||
"missing created_at": variant(created_at=None),
|
||||
"wrong type": variant(type="attachment.delete.v1"),
|
||||
"traceparent bad version": variant(traceparent="01-" + "a" * 32 + "-" + "b" * 16 + "-01"),
|
||||
"created_at no timezone": variant(created_at="2026-09-01T12:00:00"),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text())
|
||||
try:
|
||||
import rfc3339_validator # noqa: F401 (без него FormatChecker не проверяет date-time)
|
||||
formats = True
|
||||
except ImportError:
|
||||
formats = False
|
||||
validator = Draft202012Validator(schema, format_checker=FormatChecker())
|
||||
results, mismatches = [], 0
|
||||
for name, msg in CASES.items():
|
||||
schema_ok = validator.is_valid(msg)
|
||||
try:
|
||||
jobs.parse_message(json.dumps(msg).encode())
|
||||
parser_ok = True
|
||||
except jobs.InvalidMessage:
|
||||
parser_ok = False
|
||||
same = schema_ok == parser_ok
|
||||
mismatches += not same
|
||||
results.append({"case": name, "jsonschema_valid": schema_ok, "parser_valid": parser_ok, "match": same})
|
||||
print("%s %-45s schema=%-5s parser=%s" % ("PASS" if same else "FAIL", name, schema_ok, parser_ok))
|
||||
# F11
|
||||
proc = subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "-e", "PIPELINE_VERSION=2", "api"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=180)
|
||||
f11 = {"exit_code": proc.returncode,
|
||||
"message": [l for l in (proc.stdout + proc.stderr).splitlines() if "PIPELINE_VERSION" in l][-1:]}
|
||||
f11_ok = proc.returncode != 0 and bool(f11["message"])
|
||||
print("%s F11 api with PIPELINE_VERSION=2 refuses to start: %s" % ("PASS" if f11_ok else "FAIL", f11))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"date_time_format_checked": formats, "cases": results,
|
||||
"F11": f11}, ensure_ascii=False, indent=1) + "\n")
|
||||
ok = mismatches == 0 and f11_ok and formats
|
||||
print("PASS" if ok else "FAIL", "(%d cases, %d mismatches, date-time format checked: %s)" % (len(CASES), mismatches, formats))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Недоступность S3 в lab5 (переписано из lab4 по аудиту F14: там ожидался синхронный 201).
|
||||
|
||||
python3 student-tests/s3_outage.py --output evidence/s3-outage.json
|
||||
|
||||
API (как в lab4): при остановленном (`stop`) и зависшем (`pause`) S3 upload и download — быстрый
|
||||
503 unavailable с Retry-After, текстовые сообщения 201, /health/ready 200, GET метаданных 200.
|
||||
Worker (новое): задание, принятое ДО отказа S3, при обработке получает storage_unavailable и
|
||||
уходит в retry с backoff; после восстановления S3 оно доходит до ready. Если отказ длился
|
||||
дольше всех попыток — failed(retry_exhausted), и оператор делает replay (это тоже проверяется).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, ops, upload, wait_status, wait_until)
|
||||
|
||||
|
||||
def probe(c, alice, chat, att_ready, att_queued):
|
||||
out = {}
|
||||
calls = {
|
||||
"upload": ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"],
|
||||
{"raw": SAMPLE_PNG, "headers": {"Content-Type": "image/png"}}),
|
||||
"download_ready": ("GET", "/api/v1/attachments/%s/content" % att_ready["id"], {}),
|
||||
"metadata_queued": ("GET", "/api/v1/attachments/%s" % att_queued["id"], {}),
|
||||
"text_message": ("POST", "/api/v1/chats/%s/messages" % chat["id"],
|
||||
{"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}),
|
||||
"ready": ("GET", "/health/ready", {}),
|
||||
}
|
||||
for name, (method, path, kw) in calls.items():
|
||||
t = time.monotonic()
|
||||
r = c.call(method, path, [200, 201, 202, 503], actor=None if name == "ready" else alice, **kw)
|
||||
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
|
||||
"code": (r["json"] or {}).get("error", {}).get("code"),
|
||||
"retry_after": r["headers"].get("Retry-After")}
|
||||
return out
|
||||
|
||||
|
||||
def s3_healthy():
|
||||
cid = compose("ps", "-q", "s3").stdout.strip()
|
||||
import subprocess
|
||||
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
return st == "healthy"
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
log = Log("S3 outage: API answers 503 fast, accepted jobs retry and complete")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att_ready = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "before.png"))
|
||||
res = {}
|
||||
try:
|
||||
compose("stop", "worker")
|
||||
queued = upload(c, alice, chat, SAMPLE_PNG, "accepted-before-outage.png")
|
||||
log.step("worker stopped, job accepted before outage", attachment_id=queued["id"])
|
||||
for action, undo in (("stop", "start"), ("pause", "unpause")):
|
||||
compose(action, "s3")
|
||||
time.sleep(5) # S3Health (1 с) заметил отказ, данные устарели (3 с)
|
||||
pr = probe(c, alice, chat, att_ready, queued)
|
||||
res["s3_" + action] = pr
|
||||
log.step("S3 `%s` for 5 s" % action, **pr)
|
||||
check(pr["upload"]["status"] == 503 and pr["download_ready"]["status"] == 503
|
||||
and pr["text_message"]["status"] == 201 and pr["ready"]["status"] == 200
|
||||
and pr["metadata_queued"]["status"] == 200, "API during S3 %s: %s" % (action, pr))
|
||||
if action == "stop":
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "worker")
|
||||
info = wait_until(lambda: (lambda i: i if "retry_scheduled" in events(i) else None)(
|
||||
ops("inspect", queued["id"])), 60, 1, "worker retry on storage error")
|
||||
retries = [e["detail"] for e in info["events"] if e["event"] == "retry_scheduled"]
|
||||
res["worker_during_outage"] = {"events": events(info), "retries": retries}
|
||||
log.step("worker meets S3 outage -> retry with backoff", **res["worker_during_outage"])
|
||||
check(all(r["error_code"] == "storage_unavailable" for r in retries), "retry reason")
|
||||
compose(undo, "s3")
|
||||
t0 = time.monotonic()
|
||||
wait_until(s3_healthy, 120, 1, "s3 healthy")
|
||||
log.step("S3 `%s` -> healthy" % undo, seconds=round(time.monotonic() - t0, 1))
|
||||
final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 120)
|
||||
replayed = None
|
||||
if final["status"] == "failed":
|
||||
check(final["error_code"] == "retry_exhausted", "unexpected failure " + str(final["error_code"]))
|
||||
replayed = ops("replay", queued["id"], "--reason", "S3 restored")["replay"][0]["result"]
|
||||
final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 60)
|
||||
info = ops("inspect", queued["id"])
|
||||
res["accepted_job"] = {"final": final["status"], "replay": replayed, "attempts": info["jobs"][0]["attempt"],
|
||||
"events": events(info)}
|
||||
check(final["status"] == "ready", "accepted job not completed")
|
||||
log.step("job accepted before outage completed", **res["accepted_job"])
|
||||
after = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "after.png"))
|
||||
res["upload_after_recovery"] = after["status"]
|
||||
log.step("upload after recovery", status=after["status"])
|
||||
finally:
|
||||
compose("unpause", "s3", ok=False)
|
||||
compose("start", "s3", ok=False)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "worker", ok=False)
|
||||
log.save(args.output, results=res)
|
||||
print("PASS: S3 outage handled by API (503) and worker (retry), accepted work completed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка приватности bucket и ограничений ключей ВНЕ API (внутри backend-сети).
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/s3_private_check.py
|
||||
|
||||
Проверяет напрямую на S3 (минуя API и его ACL):
|
||||
* анонимные GET объекта / ListBucket / PUT -> 403;
|
||||
* ключ api: Put/Get/Delete своего тестового объекта можно; ListBucket, CreateBucket,
|
||||
DeleteBucket, PutBucketPolicy — AccessDenied; другой bucket — AccessDenied;
|
||||
* ключ worker (lab5): Get/Put/Delete можно; ListBucket, CreateBucket — AccessDenied;
|
||||
* ключ janitor: List и Delete можно; GetObject (чтение содержимого) — AccessDenied;
|
||||
* служебные порты SeaweedFS (master 9333, volume 8080, filer 8888, IAM 8111,
|
||||
Iceberg 8181, Lance 9101) из backend-сети недоступны — открыт только S3 :8333.
|
||||
Выход 0 только если все ожидания выполнены. Ключи не печатаются.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.path.insert(0, "/app/src")
|
||||
from minio import Minio # noqa: E402
|
||||
from minio.error import S3Error # noqa: E402
|
||||
|
||||
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
HOST = urlsplit(ENDPOINT).netloc
|
||||
|
||||
|
||||
def key(name):
|
||||
with open("/run/secrets/" + name) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def client(who):
|
||||
return Minio(HOST, access_key=key("s3_%s_access_key" % who), secret_key=key("s3_%s_secret_key" % who),
|
||||
secure=False, region=os.environ.get("S3_REGION", "us-east-1"))
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def expect(name, should_succeed, fn):
|
||||
try:
|
||||
fn()
|
||||
ok, got = should_succeed, "allowed"
|
||||
except S3Error as exc:
|
||||
ok, got = not should_succeed, exc.code
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok, got = False, type(exc).__name__
|
||||
results.append({"check": name, "expected": "allowed" if should_succeed else "denied", "got": got, "pass": ok})
|
||||
|
||||
|
||||
def http_status(method, url, data=None):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
api, janitor, worker = client("api"), client("janitor"), client("worker")
|
||||
probe = "originals/s3check-" + uuid.uuid4().hex
|
||||
expect("api: PutObject в свой bucket", True, lambda: api.put_object(BUCKET, probe, io.BytesIO(b"x" * 16), 16))
|
||||
for name, method, url, data in (
|
||||
("anonymous GET object", "GET", "%s/%s/%s" % (ENDPOINT, BUCKET, probe), None),
|
||||
("anonymous ListBucket", "GET", "%s/%s?list-type=2" % (ENDPOINT, BUCKET), None),
|
||||
("anonymous ListAllMyBuckets", "GET", ENDPOINT + "/", None),
|
||||
("anonymous PUT object", "PUT", "%s/%s/anon-%s" % (ENDPOINT, BUCKET, uuid.uuid4().hex), b"z")):
|
||||
code = http_status(method, url, data)
|
||||
results.append({"check": name, "expected": "403", "got": code, "pass": code in (401, 403)})
|
||||
expect("api: GetObject", True, lambda: api.get_object(BUCKET, probe).read())
|
||||
expect("api: ListBucket", False, lambda: list(api.list_objects(BUCKET, recursive=True)))
|
||||
expect("api: CreateBucket", False, lambda: api.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteBucket", False, lambda: api.remove_bucket(BUCKET))
|
||||
expect("api: PutBucketPolicy (сделать публичным)", False, lambda: api.set_bucket_policy(BUCKET, json.dumps({
|
||||
"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::%s/*" % BUCKET]}]})))
|
||||
expect("janitor: GetObject (чтение содержимого)", False, lambda: janitor.get_object(BUCKET, probe).read())
|
||||
expect("janitor: ListBucket", True, lambda: list(janitor.list_objects(BUCKET, prefix="originals/", recursive=True)))
|
||||
expect("janitor: CreateBucket", False, lambda: janitor.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("worker: GetObject (чтение staging)", True, lambda: worker.get_object(BUCKET, probe).read())
|
||||
expect("worker: PutObject (результат)", True, lambda: worker.put_object(BUCKET, probe + ".w", io.BytesIO(b"y"), 1))
|
||||
expect("worker: DeleteObject (очистка staging)", True, lambda: worker.remove_object(BUCKET, probe + ".w"))
|
||||
expect("worker: ListBucket", False, lambda: list(worker.list_objects(BUCKET, recursive=True)))
|
||||
expect("worker: CreateBucket", False, lambda: worker.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteObject (компенсация)", True, lambda: api.remove_object(BUCKET, probe))
|
||||
s3_host = HOST.split(":")[0]
|
||||
for port, role in ((9333, "master UI/API"), (8080, "volume"), (8888, "filer UI/API"), (8111, "IAM API"),
|
||||
(8181, "Iceberg"), (9101, "Lance"), (8333, "S3 API")):
|
||||
try:
|
||||
socket.create_connection((s3_host, port), timeout=2).close()
|
||||
got = "open"
|
||||
except OSError:
|
||||
got = "closed"
|
||||
want = "open" if port == 8333 else "closed"
|
||||
results.append({"check": "port %d (%s) из backend-сети" % (port, role), "expected": want, "got": got,
|
||||
"pass": got == want})
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-45s expected=%-8s got=%s" % (r["check"], r["expected"], r["got"]))
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
print(json.dumps({"checks": len(results), "failed": len(failed)}))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Аудит F03: общий срок приёма тела нельзя обойти, присылая данные по байту.
|
||||
|
||||
python3 student-tests/slow_client.py --output evidence/slow-client.json
|
||||
|
||||
На время теста API пересоздаётся с UPLOAD_TIMEOUT_SECONDS=5 и JSON_BODY_TIMEOUT_SECONDS=3
|
||||
(чтобы не ждать 60 с), затем возвращается к .env. Сырой сокет через LB:
|
||||
upload: заголовки + первые 33 байта PNG, дальше по 1 байту каждые 0,5 с (тело 5000 байт —
|
||||
без ограничения передача длилась бы ~40 мин);
|
||||
JSON: POST /users с Content-Length 200, по 1 байту каждые 0,5 с.
|
||||
Ожидаем ответ 400 invalid_request (или закрытие соединения) не позже срок + 2 с, после чего
|
||||
обычный upload снова 202 (слоты освобождены).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from lab5lib import Client, Log, SAMPLE_PNG, check, recreate, upload
|
||||
|
||||
ENV = {"UPLOAD_TIMEOUT_SECONDS": "5", "JSON_BODY_TIMEOUT_SECONDS": "3"}
|
||||
|
||||
|
||||
def drip(base, head, body_first, total_len, limit_s):
|
||||
u = urlsplit(base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=2)
|
||||
s.sendall(head + body_first)
|
||||
started = time.monotonic()
|
||||
sent = len(body_first)
|
||||
resp = b""
|
||||
while time.monotonic() - started < limit_s:
|
||||
try:
|
||||
chunk = s.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
resp += chunk
|
||||
if b"\r\n\r\n" in resp:
|
||||
break
|
||||
except socket.timeout:
|
||||
pass
|
||||
except OSError:
|
||||
break
|
||||
if sent < total_len:
|
||||
try:
|
||||
s.sendall(b"\0")
|
||||
sent += 1
|
||||
except OSError:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
elapsed = round(time.monotonic() - started, 2)
|
||||
s.close()
|
||||
status = int(resp.split(b" ", 2)[1]) if resp.startswith(b"HTTP/") else None
|
||||
body = resp.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in resp else b""
|
||||
code = None
|
||||
if body.startswith(b"{"):
|
||||
try:
|
||||
code = json.loads(body)["error"]["code"]
|
||||
except ValueError:
|
||||
pass
|
||||
return {"status": status, "code": code, "seconds": elapsed, "bytes_sent": sent, "of": total_len,
|
||||
"x_instance_id": b"x-instance-id" in resp.lower()}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("slow client vs total body deadline")
|
||||
recreate("api", ENV)
|
||||
log.step("api recreated", env=ENV)
|
||||
res = {}
|
||||
try:
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
u = urlsplit(args.base_url)
|
||||
head = ("POST /api/v1/chats/%s/attachments?filename=slow.png HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: 5000\r\n\r\n"
|
||||
% (chat["id"], u.netloc, alice["token"])).encode()
|
||||
res["upload"] = drip(args.base_url, head, SAMPLE_PNG[:33], 5000, 20)
|
||||
log.step("upload drip 1 B / 0.5 s", **res["upload"])
|
||||
check(res["upload"]["seconds"] <= 7 and res["upload"]["bytes_sent"] < 5000, "upload deadline not enforced")
|
||||
check(res["upload"]["status"] == 400 and res["upload"]["x_instance_id"], "upload: expected API 400")
|
||||
head = ("POST /api/v1/users HTTP/1.1\r\nHost: %s\r\nContent-Type: application/json\r\n"
|
||||
"Content-Length: 200\r\n\r\n" % u.netloc).encode()
|
||||
res["json"] = drip(args.base_url, head, b'{"username":', 200, 20)
|
||||
log.step("json drip 1 B / 0.5 s", **res["json"])
|
||||
check(res["json"]["seconds"] <= 5 and res["json"]["bytes_sent"] < 200, "json deadline not enforced")
|
||||
check(res["json"]["status"] == 400 and res["json"]["x_instance_id"], "json: expected API 400")
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "after-slow.png")
|
||||
res["normal_upload_after"] = att["status"]
|
||||
log.step("normal upload afterwards", status=att["status"])
|
||||
finally:
|
||||
recreate("api")
|
||||
log.step("api restored to .env configuration")
|
||||
log.save(args.output, results=res)
|
||||
print("PASS: slow clients are cut off by the total deadline")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Пик памяти API при одновременных загрузках крупных файлов (уровень 4).
|
||||
|
||||
python3 student-tests/upload_memory.py --concurrency 12 --rounds 3 --output evidence/upload-memory-c12.json
|
||||
|
||||
Гипотеза: потоковый приём (буфер 64 KiB -> безымянный временный файл), multipart PUT
|
||||
частями по 5 MiB и проверка JPEG в подпроцессе с лимитом (src/jpeg_probe.py) держат RAM
|
||||
реплики ограниченной и не зависящей линейно от числа одновременных загрузок.
|
||||
|
||||
Lab5 (аудит F16): явные критерии успеха и ненулевой код выхода при нарушении — все ответы 202
|
||||
(503 только с --allow-503), ни одного OOM-kill и перезапуска реплик, пик памяти cgroup каждой
|
||||
реплики < 90% лимита. Объём считается по размеру файла в каждой записи. В смесь входят
|
||||
несжимаемый PNG ~10 MiB, baseline JPEG и progressive JPEG 4:4:4 ~40 Мпикс (самый тяжёлый
|
||||
по памяти вход, аудит F02) — JPEG генерируются в контейнере checks (Pillow).
|
||||
|
||||
Методика: перед прогоном API-реплики перезапускаются (VmHWM считается с нуля). В каждой
|
||||
реплике фоново (docker exec ... while sleep 0.05) читаются VmRSS процесса (PID 1) и
|
||||
anon/file из cgroup memory.stat. Нагрузка — concurrency потоков, каждый грузит свой
|
||||
файл через LB; файлы: несжимаемый PNG ~9.99 MiB и (если на хосте есть Pillow) JPEG
|
||||
6000x6000 = 36 Мпикс. В конце — VmHWM (пиковый RSS процесса) и memory.peak cgroup.
|
||||
file-память cgroup — page cache временных файлов, она вытесняема и OOM не вызывает.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client # noqa: E402
|
||||
from attachments_negative import noise_png # noqa: E402
|
||||
|
||||
SAMPLER = ("while true; do r=$(grep VmRSS /proc/1/status | tr -s ' ' | cut -d' ' -f2); "
|
||||
"a=$(grep '^anon ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); "
|
||||
"f=$(grep '^file ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); echo \"$r $a $f\"; sleep 0.05; done")
|
||||
|
||||
|
||||
def sh(*cmd):
|
||||
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def containers():
|
||||
return sh("docker", "compose", "ps", "-q", "api").split()
|
||||
|
||||
|
||||
def proc_status(cid, field):
|
||||
out = sh("docker", "exec", cid, "grep", field, "/proc/1/status")
|
||||
return int(out.split()[1]) // 1024 # kB -> MiB
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self, cid):
|
||||
self.cid, self.samples = cid, []
|
||||
self.p = subprocess.Popen(["docker", "exec", cid, "sh", "-c", SAMPLER], stdout=subprocess.PIPE, text=True)
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.p.stdout:
|
||||
parts = line.split()
|
||||
if len(parts) == 3:
|
||||
self.samples.append((time.monotonic(), int(parts[0]) / 1024, int(parts[1]) / 2**20, int(parts[2]) / 2**20))
|
||||
|
||||
def stop(self):
|
||||
self.p.terminate()
|
||||
|
||||
|
||||
GEN = r"""
|
||||
import io, sys
|
||||
from PIL import Image
|
||||
kind = sys.argv[1]
|
||||
if kind == "baseline":
|
||||
im = Image.effect_noise((6000, 6000), 40).convert("RGB")
|
||||
for q in (60, 45, 30, 20):
|
||||
b = io.BytesIO(); im.save(b, "JPEG", quality=q)
|
||||
if b.tell() <= 10 * 1024 * 1024:
|
||||
break
|
||||
else:
|
||||
g = Image.radial_gradient("L").resize((6324, 6324))
|
||||
b = io.BytesIO(); Image.merge("RGB", (g, g.rotate(90), g)).save(b, "JPEG", quality=85, progressive=True, subsampling=0)
|
||||
sys.stdout.buffer.write(b.getvalue())
|
||||
"""
|
||||
|
||||
|
||||
def make_jpeg(kind):
|
||||
"""JPEG генерируется в контейнере checks (на хосте Pillow может не быть)."""
|
||||
proc = subprocess.run(["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "checks", "-c", GEN, kind],
|
||||
cwd=ROOT, capture_output=True, check=True)
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--concurrency", type=int, default=12)
|
||||
ap.add_argument("--rounds", type=int, default=3)
|
||||
ap.add_argument("--no-restart", action="store_true")
|
||||
ap.add_argument("--allow-503", action="store_true", help="считать 503 (перегрузка) допустимым ответом")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
files = [("image/png", noise_png(10 * 1024 * 1024))]
|
||||
files.append(("image/jpeg", make_jpeg("baseline")))
|
||||
files.append(("image/jpeg", make_jpeg("progressive444")))
|
||||
if not args.no_restart:
|
||||
sh("docker", "compose", "restart", "api")
|
||||
sh("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--wait", "api")
|
||||
time.sleep(4)
|
||||
c = Client(args.base_url, timeout=120)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
# прогрев: один upload каждого типа (импорт Pillow, пулы соединений)
|
||||
for ctype, data in files:
|
||||
c.call("POST", "/api/v1/chats/%s/attachments?filename=w" % chat["id"], 202, actor=alice, raw=data,
|
||||
headers={"Content-Type": ctype})
|
||||
cids = containers()
|
||||
restarts_before = sh("docker", "inspect", "-f", "{{.RestartCount}}", *cids).split()
|
||||
idle = {cid[:12]: {"rss_mib": proc_status(cid, "VmRSS"), "hwm_mib_after_warmup": proc_status(cid, "VmHWM")}
|
||||
for cid in cids}
|
||||
s3_cid = sh("docker", "compose", "ps", "-q", "s3").split()[0]
|
||||
s3_before = {"rss_mib": proc_status(s3_cid, "VmRSS"), "oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip()}
|
||||
samplers = [Sampler(cid) for cid in cids]
|
||||
s3_sampler = Sampler(s3_cid)
|
||||
time.sleep(1)
|
||||
results, lock = [], threading.Lock()
|
||||
|
||||
def worker(i):
|
||||
ctype, data = files[i % len(files)]
|
||||
t = time.monotonic()
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=m%d" % (chat["id"], i), [202, 503], actor=alice,
|
||||
raw=data, headers={"Content-Type": ctype}, schema=None)
|
||||
st, inst = r["status"], r["headers"].get("X-Instance-Id")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
st, inst = type(exc).__name__, None
|
||||
with lock:
|
||||
# Размер — в самой записи: потоки завершаются не по порядку (аудит F16).
|
||||
results.append({"type": ctype, "bytes": len(data), "status": st, "instance": inst,
|
||||
"s": round(time.monotonic() - t, 2)})
|
||||
|
||||
started = time.monotonic()
|
||||
for _ in range(args.rounds):
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
for th in threads:
|
||||
th.join()
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(1)
|
||||
for s in samplers + [s3_sampler]:
|
||||
s.stop()
|
||||
per = {}
|
||||
for cid, s in zip(cids, samplers):
|
||||
k = cid[:12]
|
||||
per[k] = dict(idle[k],
|
||||
samples=len(s.samples),
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s.samples), 1),
|
||||
peak_anon_mib=round(max(x[2] for x in s.samples), 1),
|
||||
peak_file_cache_mib=round(max(x[3] for x in s.samples), 1),
|
||||
vmhwm_mib=proc_status(cid, "VmHWM"),
|
||||
cgroup_memory_peak_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.peak")) / 2**20, 1),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20),
|
||||
uploads_served=sum(1 for r in results if r["instance"] == k))
|
||||
durations = sorted(r["s"] for r in results if r["status"] == 202)
|
||||
summary = {
|
||||
"concurrency": args.concurrency, "rounds": args.rounds,
|
||||
"files": [{"type": t, "bytes": len(d), "sha256": hashlib.sha256(d).hexdigest()[:16]} for t, d in files],
|
||||
"uploads": len(results), "status_counts": {str(k): sum(1 for r in results if r["status"] == k)
|
||||
for k in {r["status"] for r in results}},
|
||||
"megabytes_uploaded_ok": round(sum(r["bytes"] for r in results if r["status"] == 202) / 2**20, 1),
|
||||
"wall_s": round(wall, 1),
|
||||
"latency_s_p50_max": [durations[len(durations) // 2], durations[-1]] if durations else None,
|
||||
"replicas": per,
|
||||
"s3": dict(s3_before,
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
peak_anon_mib=round(max(x[2] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
restarts=int(sh("docker", "inspect", "-f", "{{.RestartCount}}", s3_cid)),
|
||||
oom_killed_after=sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip(),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", s3_cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20)),
|
||||
"oom_kills": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", *cids).split(),
|
||||
}
|
||||
allowed = {202, 503} if args.allow_503 else {202}
|
||||
restarts_after = sh("docker", "inspect", "-f", "{{.RestartCount}}", *cids).split()
|
||||
criteria = {
|
||||
"all_responses_allowed": all(r["status"] in allowed for r in results),
|
||||
"no_oom_kills": all(x == "false" for x in summary["oom_kills"]),
|
||||
"no_replica_restarts": restarts_before == restarts_after,
|
||||
"cgroup_peak_below_90pct": all(v["cgroup_memory_peak_mib"] < 0.9 * v["memory_limit_mib"] for v in per.values()),
|
||||
}
|
||||
summary["criteria"] = criteria
|
||||
summary["pass"] = all(criteria.values())
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка вариантов по контракту (запускается В КОНТЕЙНЕРЕ checks, где есть Pillow):
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/variants_check.py \
|
||||
--base-url http://lb:8080 --output /app/evidence/variants-check.json
|
||||
|
||||
Для каждого входа: ready, ровно 3 варианта, метаданные = фактическим байтам (размер, SHA-256,
|
||||
декодированные размеры, формат), оригинал неизменен. Thumbnail: JPEG, вписан в 256x256 без
|
||||
увеличения, округление вниз; EXIF orientation применена; alpha -> белый. Crop: JPEG 128x128.
|
||||
Optimized: WebP, вписан в 1280x1280 без увеличения. В вариантах нет метаданных — проверяются
|
||||
СЫРЫЕ байты (аудит F07): в JPEG нет маркеров COM, APP1 (Exif/XMP), APP2 (ICC); в WebP нет
|
||||
чанков EXIF, XMP, ICCP. Прозрачность tRNS у RGB и L (аудит F06) тоже даёт белый фон в JPEG
|
||||
и alpha=0 в WebP.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, "/app/tests")
|
||||
from client import Client, check # noqa: E402
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
FIXTURE = Path("/app/tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def fit(w, h, box):
|
||||
if w <= box and h <= box:
|
||||
return w, h
|
||||
return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box)
|
||||
|
||||
|
||||
def encode(img, fmt, **kw):
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def jpeg_markers(b):
|
||||
"""Маркеры сегментов JPEG до начала скана (SOS)."""
|
||||
out, i = [], 2
|
||||
while i + 4 <= len(b) and b[i] == 0xFF:
|
||||
m = b[i + 1]
|
||||
if m == 0xDA:
|
||||
break
|
||||
out.append(m)
|
||||
i += 2 + int.from_bytes(b[i + 2:i + 4], "big")
|
||||
return out
|
||||
|
||||
|
||||
def webp_chunks(b):
|
||||
out, i = [], 12
|
||||
while i + 8 <= len(b):
|
||||
name, size = b[i:i + 4], int.from_bytes(b[i + 4:i + 8], "little")
|
||||
out.append(name.decode("latin-1"))
|
||||
i += 8 + size + (size & 1)
|
||||
return out
|
||||
|
||||
|
||||
def no_metadata(b, fmt):
|
||||
if fmt == "JPEG":
|
||||
bad = {0xFE: "COM", 0xE1: "APP1", 0xE2: "APP2"}
|
||||
found = [bad[m] for m in jpeg_markers(b) if m in bad]
|
||||
else:
|
||||
found = [c for c in webp_chunks(b) if c.strip() in ("EXIF", "XMP", "ICCP")]
|
||||
return found
|
||||
|
||||
|
||||
def cases():
|
||||
out = [("fixture 320x200 PNG", FIXTURE, "image/png", (320, 200), None)]
|
||||
# RGBA: левая половина прозрачная -> в JPEG должна стать белой.
|
||||
rgba = Image.new("RGBA", (300, 300), (200, 20, 20, 255))
|
||||
rgba.paste((0, 0, 0, 0), (0, 0, 150, 300))
|
||||
out.append(("RGBA 300x300 half transparent", encode(rgba, "PNG"), "image/png", (300, 300), "alpha"))
|
||||
# EXIF orientation 6 (поворот 90° по часовой): хранится 400x200, показывается 200x400.
|
||||
# Верхняя половина ХРАНИМОГО кадра красная -> после поворота красной становится правая половина.
|
||||
raw = Image.new("RGB", (400, 200), (0, 0, 255))
|
||||
raw.paste((255, 0, 0), (0, 0, 400, 100))
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
exif[0x010F] = "MTUSI test camera" # Make: проверяем, что EXIF не утёк в варианты
|
||||
out.append(("JPEG 400x200 EXIF orientation=6", encode(raw, "JPEG", quality=95, exif=exif.tobytes()),
|
||||
"image/jpeg", (200, 400), "orientation"))
|
||||
# Все виды метаданных сразу: комментарий, EXIF, XMP, ICC (аудит F07).
|
||||
from PIL import ImageCms
|
||||
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
|
||||
meta = Image.new("RGB", (500, 300), (30, 90, 160))
|
||||
meta_exif = Image.Exif()
|
||||
meta_exif[0x010F] = "PRIVATE-CAMERA" # Make, без orientation
|
||||
out.append(("JPEG with COM+EXIF+XMP+ICC", encode(meta, "JPEG", quality=90, comment=b"PRIVATE-COMMENT",
|
||||
exif=meta_exif.tobytes(), icc_profile=icc,
|
||||
xmp=b"<x:xmpmeta xmlns:x='adobe:ns:meta/'>PRIVATE-XMP</x:xmpmeta>"),
|
||||
"image/jpeg", (500, 300), "metadata"))
|
||||
# tRNS у RGB и L (аудит F06): весь кадр — «прозрачный цвет».
|
||||
out.append(("RGB PNG with tRNS (fully transparent)", encode(Image.new("RGB", (300, 200), (255, 0, 0)), "PNG",
|
||||
transparency=(255, 0, 0)), "image/png", (300, 200), "alpha_full"))
|
||||
out.append(("L PNG with tRNS (fully transparent)", encode(Image.new("L", (200, 300), 0), "PNG", transparency=0),
|
||||
"image/png", (200, 300), "alpha_full"))
|
||||
out.append(("tiny PNG 10x5 (no upscale)", encode(Image.new("RGB", (10, 5), (9, 200, 9)), "PNG"),
|
||||
"image/png", (10, 5), None))
|
||||
big = Image.radial_gradient("L").resize((3000, 2000)).convert("RGB")
|
||||
out.append(("JPEG 3000x2000", encode(big, "JPEG", quality=90), "image/jpeg", (3000, 2000), None))
|
||||
tall = Image.new("RGB", (100, 1000), (50, 60, 70))
|
||||
out.append(("tall PNG 100x1000", encode(tall, "PNG"), "image/png", (100, 1000), None))
|
||||
pal = Image.new("P", (64, 64), 1)
|
||||
pal.putpalette([255, 255, 255, 10, 200, 10] + [0] * 762)
|
||||
out.append(("palette PNG with transparency", encode(pal, "PNG", transparency=1), "image/png", (64, 64), "alpha"))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://lb:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
results = []
|
||||
pending = []
|
||||
for name, data, ctype, (ow, oh), special in cases():
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=v.%s" % (chat["id"], ctype.split("/")[1]), 202,
|
||||
actor=alice, raw=data, headers={"Content-Type": ctype}, schema="Attachment")["json"]
|
||||
pending.append((name, data, ctype, ow, oh, special, att["id"]))
|
||||
for name, data, ctype, ow, oh, special, att_id in pending:
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
att = c.call("GET", "/api/v1/attachments/" + att_id, actor=bob, schema="Attachment")["json"]
|
||||
if att["status"] in ("ready", "failed") or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
check(att["status"] == "ready", "%s: status %s" % (name, att["status"]))
|
||||
r = {"case": name, "source_oriented": [ow, oh], "variants": {}}
|
||||
orig = c.call("GET", "/api/v1/attachments/%s/content" % att_id, actor=bob)
|
||||
check(orig["bytes"] == data and orig["headers"].get_content_type() == ctype, name + ": original changed")
|
||||
check(sorted(v["name"] for v in att["variants"]) == ["crop", "optimized", "thumbnail"], name + ": variants")
|
||||
expect = {"thumbnail": ("image/jpeg", "JPEG", fit(ow, oh, 256)),
|
||||
"crop": ("image/jpeg", "JPEG", (128, 128)),
|
||||
"optimized": ("image/webp", "WEBP", fit(ow, oh, 1280))}
|
||||
for v in att["variants"]:
|
||||
ct, fmt, size = expect[v["name"]]
|
||||
body = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att_id, v["name"]), actor=bob)
|
||||
b = body["bytes"]
|
||||
img = Image.open(io.BytesIO(b))
|
||||
img.load()
|
||||
check(v["content_type"] == ct and body["headers"].get_content_type() == ct, name + ": content type")
|
||||
check(img.format == fmt, name + ": real format " + str(img.format))
|
||||
check((v["width"], v["height"]) == size == img.size, "%s %s: size %s meta %s expected %s" % (
|
||||
name, v["name"], img.size, (v["width"], v["height"]), size))
|
||||
check(v["size_bytes"] == len(b) and v["sha256"] == hashlib.sha256(b).hexdigest(), name + ": checksum")
|
||||
leaked = no_metadata(b, fmt)
|
||||
check(not leaked and not img.getexif() and "icc_profile" not in img.info,
|
||||
"%s: metadata leaked into %s: %s" % (name, v["name"], leaked))
|
||||
check(b"PRIVATE" not in b, name + ": private text found in bytes of " + v["name"])
|
||||
item = {"size": list(img.size), "format": fmt, "bytes": len(b), "metadata_markers": leaked}
|
||||
if special == "alpha_full":
|
||||
if v["name"] == "optimized":
|
||||
a = img.convert("RGBA").getpixel((img.size[0] // 2, img.size[1] // 2))[3]
|
||||
check(a == 0, name + ": WebP alpha must be 0, got %d" % a)
|
||||
item["webp_alpha"] = a
|
||||
else:
|
||||
px = img.convert("RGB").getpixel((img.size[0] // 2, img.size[1] // 2))
|
||||
check(min(px) >= 245, name + ": transparent area is not white: %s" % (px,))
|
||||
item["center_rgb"] = list(px)
|
||||
if special == "alpha" and v["name"] in ("thumbnail", "crop"):
|
||||
px = img.convert("RGB").getpixel((1, img.size[1] // 2))
|
||||
check(min(px) >= 245, name + ": transparent area is not white: %s" % (px,))
|
||||
item["transparent_pixel_rgb"] = list(px)
|
||||
if special == "orientation" and v["name"] == "thumbnail":
|
||||
w, h = img.size
|
||||
left, right = img.getpixel((w // 4, h // 2)), img.getpixel((3 * w // 4, h // 2))
|
||||
check(right[0] > 200 and right[2] < 60 and left[2] > 200, name + ": orientation not applied")
|
||||
item["left_rgb"], item["right_rgb"] = list(left), list(right)
|
||||
r["variants"][v["name"]] = item
|
||||
results.append(r)
|
||||
print("PASS %-36s %s" % (name, {k: tuple(x["size"]) for k, x in r["variants"].items()}), flush=True)
|
||||
c.call("GET", "/api/v1/attachments/%s/content?variant=bogus" % pending[0][6], 400, actor=bob)
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"cases": results, "unknown_variant_status": 400},
|
||||
ensure_ascii=False, indent=1) + "\n")
|
||||
print("PASS: %d inputs, all variants match contract" % len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user