#!/usr/bin/env python3 """Level 4 для lab4: негативные сценарии, компенсация, эксперимент с параллельными загрузками. Запуск: python student-tests/lab4_test_level4.py --base-url http://localhost:8080 """ import hashlib import io import os import subprocess import sys import threading import time import urllib.error import urllib.parse import urllib.request import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client, Failure, arguments, check, run # noqa: E402 ROOT = Path(__file__).resolve().parents[1] SAMPLE = ROOT / "tests" / "fixtures" / "sample.png" API_CONTAINER = os.environ.get("API_CONTAINER", "") def _raw_upload(c: Client, actor, chat_id: str, filename: str, data: bytes, ctype: str): # filename кодируем, иначе urllib откажется формировать URL с control-символами # (NUL, CR, LF, TAB). Сервер получит их в декодированном виде и вернёт 400. qs = urllib.parse.urlencode({"filename": filename}, quote_via=urllib.parse.quote) url = c.base + "/api/v1/chats/" + chat_id + "/attachments?" + qs req = urllib.request.Request( url, data=data, method="POST", headers={ "Authorization": "Bearer " + actor["token"], "Content-Type": ctype, }, ) try: with c.opener.open(req, timeout=15) as resp: import json as _json return resp.code, _json.loads(resp.read()), resp.headers except urllib.error.HTTPError as e: import json as _json body = e.read() try: return e.code, _json.loads(body), e.headers except Exception: return e.code, None, e.headers def _upload(c, actor, chat, data, filename="sample.png", ctype="image/png"): return _raw_upload(c, actor, chat["id"], filename, data, ctype) def test_oversize(c): alice, bob, eve, chat = c.bootstrap() big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10_485_761) status, body, _h = _upload(c, alice, chat, big) check(status == 413, "oversize upload must be 413, got %s" % status) def test_corrupted_image(c): alice, bob, eve, chat = c.bootstrap() bad = b"\x89PNG\r\n\x1a\n" + b"not-a-real-png" * 100 status, body, _h = _upload(c, alice, chat, bad) check(status == 415, "corrupted PNG must be 415, got %s" % status) def test_mime_spoof(c): alice, bob, eve, chat = c.bootstrap() status, body, _h = _upload(c, alice, chat, b"hello, not an image" * 10, ctype="image/png") check(status == 415, "spoofed MIME must be 415, got %s" % status) def test_bad_filename(c): alice, bob, eve, chat = c.bootstrap() data = SAMPLE.read_bytes() for bad in ("../evil.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", " "): status, body, _h = _upload(c, alice, chat, data, filename=bad) check(status == 400, "bad filename %r must be 400, got %s" % (bad, status)) def test_foreign_attachment_and_cross_chat(c): alice, bob, eve, chat = c.bootstrap() chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Второй", "member_ids": [alice["id"], eve["id"]]}, schema="Chat")["json"] data = SAMPLE.read_bytes() status, att, _h = _upload(c, alice, chat2, data) check(status == 201, "upload to chat2 must be 201, got %s" % status) att_id = att["id"] c.call("GET", "/api/v1/attachments/" + att_id, 404, actor=bob) c.call("GET", "/api/v1/attachments/" + att_id + "/content", 404, actor=bob) c.call( "POST", "/api/v1/chats/" + chat["id"] + "/messages", 404, actor=bob, body={"text": "", "attachment_ids": [att_id]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) def test_attachment_belongs_to_chat(c): alice, bob, eve, chat = c.bootstrap() other = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Другой", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"] data = SAMPLE.read_bytes() status, att, _h = _upload(c, alice, chat, data) check(status == 201, "upload to chat must be 201") c.call( "POST", "/api/v1/chats/" + other["id"] + "/messages", 404, actor=alice, body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) def test_compensation_on_db_failure(c): """Проверяем компенсацию при сбое INSERT метаданных после S3 PUT. Патчим storage.create_attachment внутри контейнера API через docker exec, затем вызываем загрузку. Ожидаем 503 и отсутствие orphan-объекта в bucket (проверяется вручную через mc ls; здесь тест лишь подтверждает 503). """ if not API_CONTAINER: print(" SKIP: API_CONTAINER не задан, компенсация не проверяется автоматически") return alice, bob, eve, chat = c.bootstrap() data = SAMPLE.read_bytes() # Патч-скрипт в контейнере: ломаем storage.create_attachment для последнего вызова. patch = ( "import os,sys,builtins\n" "sys.path.insert(0,'/app/src')\n" "from app.storage import postgres as P\n" "orig = P.PostgresStorage.create_attachment\n" "def boom(self, att, key):\n" " raise RuntimeError('patched_db_failure')\n" "P.PostgresStorage.create_attachment = boom\n" "# Оставляем процесс жить до сигнала из файла-флага\n" "import time, pathlib\n" "pathlib.Path('/tmp/compensation_ready').write_text('1')\n" "time.sleep(30)\n" ) # Запускаем патч в фоне внутри api-контейнера proc = subprocess.Popen( ["docker", "exec", "-d", API_CONTAINER, "python", "-c", patch], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) proc.wait(timeout=10) time.sleep(2) # Чистим флаг subprocess.run( ["docker", "exec", API_CONTAINER, "rm", "-f", "/tmp/compensation_ready"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: status, body, _h = _upload(c, alice, chat, data) # Ожидаем 503 (или 500 — у нас обработчик оборачивает в 503 при компенсации). check(status in (500, 503), "compensation expected 5xx, got %s" % status) print(" compensation: got %s, S3-object should be deleted" % status) finally: # Убиваем патч-процесс subprocess.run( ["docker", "exec", API_CONTAINER, "pkill", "-f", "patched_db_failure"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) # Перезапуск api для сброса патча cids = subprocess.run( ["docker", "ps", "--filter", "label=com.docker.compose.service=api", "--format", "{{.ID}}"], capture_output=True, text=True, ).stdout.split() for cid in cids: subprocess.run(["docker", "restart", cid], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Ждём готовности deadline = time.monotonic() + 60 while time.monotonic() < deadline: try: c.call("GET", "/health/ready", 200) break except Failure: time.sleep(1) def test_parallel_uploads_memory(c): """Уровень 4: ≥10 одновременных загрузок с измерением пика RSS.""" alice, bob, eve, chat = c.bootstrap() data = SAMPLE.read_bytes() barrier = threading.Barrier(10) errors = [] def one(_): local = Client(c.base, timeout=30) barrier.wait() try: status, att, _h = _upload(local, alice, chat, data) if status != 201: errors.append("status=%s" % status) except Exception as exc: # noqa: BLE001 errors.append(type(exc).__name__) def rss(): if not API_CONTAINER: return None try: out = subprocess.run( ["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", API_CONTAINER], capture_output=True, text=True, timeout=10, ) used = out.stdout.strip().split("/")[0].strip() if used.endswith("MiB"): return float(used[:-3]) if used.endswith("GiB"): return float(used[:-3]) * 1024 except Exception: return None return None peak = {"value": 0.0} stop = threading.Event() def sampler(): while not stop.is_set(): v = rss() if v and v > peak["value"]: peak["value"] = v time.sleep(0.2) sampler_thread = threading.Thread(target=sampler, daemon=True) sampler_thread.start() with ThreadPoolExecutor(max_workers=10) as pool: list(pool.map(one, range(10))) stop.set() sampler_thread.join(timeout=2) check(not errors, "parallel uploads errors: %s" % errors[:3]) print(" параллельных загрузок: 10, пик RSS=%s MiB" % peak["value"]) if peak["value"]: check(peak["value"] < 400, "peak RSS %s MiB слишком высок" % peak["value"]) def main(): args = arguments("Lab4 level 4 checks") c = Client(args.base_url, args.ca_file) print("=== oversize ===") test_oversize(c) print("PASS: oversize -> 413") print("=== corrupted image ===") test_corrupted_image(c) print("PASS: corrupted -> 415") print("=== spoofed MIME ===") test_mime_spoof(c) print("PASS: spoofed MIME -> 415") print("=== bad filename ===") test_bad_filename(c) print("PASS: bad filename -> 400") print("=== foreign attachment / cross-chat ===") test_foreign_attachment_and_cross_chat(c) print("PASS: foreign -> 404, cross-chat -> 404") print("=== attachment belongs to chat ===") test_attachment_belongs_to_chat(c) print("PASS: attachment from другой чат -> 404") print("=== compensation on DB failure ===") test_compensation_on_db_failure(c) print("PASS: compensation scenario") print("=== parallel uploads memory ===") test_parallel_uploads_memory(c) print("PASS: 10 parallel uploads under memory limit") print("PASS: all lab4 level-4 checks passed") if __name__ == "__main__": run(main)