From 412b465b855953f676f36b0476ef94ecaf122cd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=85=D0=B2=D0=B0=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=A0=D0=B5?= =?UTF-8?q?=D0=BC=D0=BE=D0=B2=D0=B8=D1=87?= Date: Fri, 2 Oct 2026 13:24:51 +0300 Subject: [PATCH] Add bounded private image upload with safe S3 persistence --- REPORT.md | 16 ++- evidence/upload-memory-2026-10-02.csv | 7 ++ migrations/005_attachment_owner.sql | 2 + requirements.txt | 2 + scripts/measure-upload-memory.py | 93 +++++++++++++++++ src/api.py | 10 +- src/attachments.py | 126 ++++++++++++++++++++++++ src/main.py | 3 +- student-tests/fixtures/sample.jpg | Bin 0 -> 633 bytes student-tests/test_attachment_upload.py | 63 ++++++++++++ student-tests/test_database.py | 2 +- student-tests/test_s3_outage.py | 46 +++++++++ student-tests/test_upload_failure.py | 68 +++++++++++++ 13 files changed, 430 insertions(+), 8 deletions(-) create mode 100644 evidence/upload-memory-2026-10-02.csv create mode 100644 migrations/005_attachment_owner.sql create mode 100644 scripts/measure-upload-memory.py create mode 100644 student-tests/fixtures/sample.jpg create mode 100644 student-tests/test_attachment_upload.py create mode 100644 student-tests/test_s3_outage.py create mode 100644 student-tests/test_upload_failure.py diff --git a/REPORT.md b/REPORT.md index 332286d..2b0a83e 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,7 +1,7 @@ # Отчёт — лабораторная 4 - Автор, группа: Самохвалов Андрей Ремович, БПИ-2302. -- Целевая оценка: 5, трек 2 «Согласованность двух хранилищ». Пока реализованы перенос lab3 и приватное S3; остальные блоки выполняются далее. +- Целевая оценка: 5, трек 2 «Согласованность двух хранилищ». Реализованы перенос lab3, приватное S3 и ограниченный синхронный upload; download, связь с сообщением и reconciler выполняются далее. - Ветка: `solution/bpi2302-samohvalov`; commit/PR указываются после публикации. - Источники: `README.md`, `COURSE.md`, `contracts/README.md`, `contracts/openapi.json`, публичные тесты, [MinIO release](https://github.com/minio/minio/releases/tag/RELEASE.2025-10-15T17-29-55Z), [образ](https://hub.docker.com/r/alpine/minio/tags), документация MinIO для IAM. Python/FastAPI, PostgreSQL, MinIO Python SDK; проект подготовлен с помощью ИИ Codex с локальной проверкой ниже. @@ -15,7 +15,7 @@ python3 scripts/setup-local-secrets.py docker compose --env-file .env config --quiet docker compose --env-file .env up -d --build --wait --scale api=2 make check -# make test — после реализации upload в следующем блоке +# make test — после реализации download/связи с сообщением в следующем блоке ``` `setup-local-secrets.py` создаёт отсутствующие secret-файлы с правами 0600 и не перезаписывает существующие. Миграции выполняет одноразовый `migrate` под PostgreSQL advisory lock. `s3-volume-init` задаёт владельца нового volume, затем MinIO стартует без root; одноразовый `s3-bootstrap` идемпотентно создаёт закрытый bucket и две ограниченные учётные записи. Повторный `docker compose --env-file .env run --rm s3-bootstrap` безопасен. Для остановки — `docker compose --env-file .env down` без `-v`; для намеренного удаления **только учебных данных** после проверки — `docker compose --env-file .env down -v`. @@ -36,7 +36,9 @@ make check | `s3-bootstrap` | одноразовый MinIO Client | завершение 0 | root и создаваемые ограниченные credentials | | `s3-volume-init` | одноразовая настройка владельца volume | завершение 0 | секретов нет | -`infra/minio-api-policy.json` разрешает только операции над объектами одного bucket и чтение его location; создание bucket, изменение IAM и административные операции не разрешены. Отдельная maintenance policy добавляет list для будущей сверки. Bucket не имеет анонимного чтения. Приватность bucket не заменяет проверку членства в чате на API: эта проверка добавляется в блоках upload/download. +`infra/minio-api-policy.json` разрешает только операции над объектами одного bucket и чтение его location; создание bucket, изменение IAM и административные операции не разрешены. Отдельная maintenance policy добавляет list для будущей сверки. Bucket не имеет анонимного чтения. Приватность bucket не заменяет проверку членства в чате на API: upload уже проверяет членство до чтения тела; download получит такую же проверку в следующем блоке. + +Upload читает raw body в `SpooledTemporaryFile` с порогом RAM 1 MiB и останавливается после 10 MiB; проверяет формат и MIME через Pillow, до декодирования отклоняет свыше 40 млн пикселей, затем полностью проверяет PNG/JPEG. Имя файла применяется только для отображения, object key — случайный UUID в `originals/`. S3 PUT предшествует INSERT/COMMIT в PostgreSQL; `201 ready` возвращается лишь после обоих успехов. При достоверной ошибке до COMMIT объект удаляется. Если подтверждение COMMIT потеряно, удалять небезопасно: объект остаётся кандидатом для сверки после grace period. Если и компенсационное DELETE отказало, key записывается во внутренний лог; U5 добавит повторяемый reconciler. Клиенту при ошибке зависимости приходит `503`, а прозрачный retry POST не выполняется. Для S3 заданы connect/read timeouts 2/10 с без внутренних повторов; `/health/ready` проверяет БД и доступ к приватному S3 через разрешённый HEAD отсутствующего probe key. ## Доказательства критериев @@ -45,11 +47,15 @@ make check | Перенос lab3 | Compose ×2, текстовая часть `make test`, `make test-persistence`, адресный failover обеих реплик | Текстовый API совместим, прежний токен/сообщение после restart; восстановление записи после остановки каждой реплики 3,123 и 3,149 с | локальные тесты U1; полный smoke остановился на ещё не реализованном upload | | Приватный S3 и bootstrap | `docker compose run --rm s3-bootstrap` дважды; `docker compose exec -T api python - < student-tests/test_storage_bootstrap.py` | Два повтора завершились 0; S3 PUT/GET ограниченным API пользователем совпадают по байтам, анонимный GET — 403, создание чужого bucket — AccessDenied | `evidence/storage-bootstrap-2026-10-02.txt` | | Миграция и транзакции | `docker compose exec -T api python - < student-tests/test_database.py`; `... test_auth.py` | Миграции 1–4 применены повторяемо, 2 DB и 3 auth теста PASS | `evidence/storage-bootstrap-2026-10-02.txt` | +| Raw PNG/JPEG upload и ограничения | `BASE_URL=http://localhost:8084 python3 -m unittest discover -s student-tests -p 'test_attachment_upload.py' -v` | 4 набора PASS: PNG/JPEG `201 ready`, корректные hash/size/type; 10 MiB+1 и >40 млн px — 413; повреждение/MIME spoof — 415; опасное имя — 400, чужой чат — 404 | `student-tests/test_attachment_upload.py`, синтетический JPEG fixture | +| Отказ S3 | `docker compose stop s3`; `docker compose exec -T api python - < student-tests/test_s3_outage.py`; `docker compose start s3` | При реально остановленном S3 readiness=503, upload=503, число metadata строк не изменилось; S3 восстановлен и healthy | `student-tests/test_s3_outage.py` | +| Промежуток S3/БД и обрыв потока | `docker compose exec -T api python - < student-tests/test_upload_failure.py` | PUT failure не вызывает SQL; ошибка БД до INSERT вызывает компенсацию DELETE; оборванный поток не начинает PUT. Неоднозначный COMMIT оставляет объект для сверки | `student-tests/test_upload_failure.py` | +| Ограничение RAM | `BASE_URL=http://localhost:8084 python3 scripts/measure-upload-memory.py` | 10/10 одновременных upload одного PNG 9 441 653 байт, 10 разных ready ID и верный SHA-256, 6,145 с; sampled peak API-1/2 114,7/115,5 MiB при лимите 256 MiB | `evidence/upload-memory-2026-10-02.csv` | ## Эксперименты и отказы -Запись S3/БД, компенсация после ошибки, ACL, failover файла, параллельные upload и reconciler ещё должны быть проверены. Пока `GET /health/ready` отражает обязательную PostgreSQL зависимость, а готовность MinIO проверяет Compose при запуске; после появления attachment path доступность S3 будет явно учтена в сценариях. +Граница PUT/COMMIT проверена fault-инъекциями; полный reconciler и проверка восстановления при неизвестном результате COMMIT выполняются в U5/U6. Замер RAM проводился на локальном Colima/arm64, 2 CPU и 2 GiB, API ×2 с 0,5 CPU/256 MiB на экземпляр, 10 потоков с барьером старта. CSV содержит baseline и два Docker stats снимка во время 6,145 с серии: peak означает максимум **наблюдённых** снимков, а не точный аппаратный high-water mark. Все 10 ответов 201 имели уникальные ID и совпадающий SHA-256. Создание body по `os.urandom` оставляет воспроизводимыми размер/разрешение/алгоритм, но не конкретные байты и hash между прогонами. ## Ограничения и следующие шаги -Полный `make test` сейчас ожидаемо получает 415 на `POST attachments`: синхронный upload, скачивание и привязка ещё не реализованы. Проверки уровня 4 и трека 5 не заявляются завершёнными до отдельных fault tests и воспроизводимых измерений. Один MinIO/PostgreSQL/LB и один Docker-host остаются одиночными точками отказа. Локальный HTTP допустим только для изолированного стенда с синтетическими данными; удалённой демонстрации нужен TLS. +Полный `make test` пока останавливается на последующих маршрутах attachment metadata/content и привязке к сообщению; U4 реализует их отдельно. Проверки уровня 4 и трека 5 не заявляются завершёнными до повторяемой сверки. Один MinIO/PostgreSQL/LB и один Docker-host остаются одиночными точками отказа. Локальный HTTP допустим только для изолированного стенда с синтетическими данными; удалённой демонстрации нужен TLS. diff --git a/evidence/upload-memory-2026-10-02.csv b/evidence/upload-memory-2026-10-02.csv new file mode 100644 index 0000000..7fe6b47 --- /dev/null +++ b/evidence/upload-memory-2026-10-02.csv @@ -0,0 +1,7 @@ +seconds,container,used_mib,limit_mib +0,mtusi2026lab4-api-1,48.58,256.0 +0,mtusi2026lab4-api-2,51.2,256.0 +2.129,mtusi2026lab4-api-1,114.7,256.0 +2.129,mtusi2026lab4-api-2,115.5,256.0 +4.141,mtusi2026lab4-api-1,114.7,256.0 +4.141,mtusi2026lab4-api-2,115.5,256.0 diff --git a/migrations/005_attachment_owner.sql b/migrations/005_attachment_owner.sql new file mode 100644 index 0000000..6db4290 --- /dev/null +++ b/migrations/005_attachment_owner.sql @@ -0,0 +1,2 @@ +ALTER TABLE attachments ADD COLUMN owner_id uuid NOT NULL REFERENCES users(id); +ALTER TABLE attachments ADD COLUMN updated_at timestamptz NOT NULL DEFAULT clock_timestamp(); diff --git a/requirements.txt b/requirements.txt index 882107d..c1ae3df 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,5 @@ psycopg[binary,pool]==3.2.12 psycopg-pool==3.3.3 argon2-cffi==25.1.0 minio==7.2.20 +Pillow==11.3.0 +urllib3==2.8.0 diff --git a/scripts/measure-upload-memory.py b/scripts/measure-upload-memory.py new file mode 100644 index 0000000..53a2be4 --- /dev/null +++ b/scripts/measure-upload-memory.py @@ -0,0 +1,93 @@ +"""Ten concurrent bounded PNG uploads plus Docker memory samples; BASE_URL overrides localhost:8080.""" + +import csv +import hashlib +import os +import re +import struct +import subprocess +import sys +import threading +import time +import zlib +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client # noqa: E402 + +API_NAMES = ("mtusi2026lab4-api-1", "mtusi2026lab4-api-2") +EVIDENCE = ROOT / "evidence/upload-memory-2026-10-02.csv" + + +def png_chunk(name: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + name + data + struct.pack(">I", zlib.crc32(name + data)) + + +def large_png() -> bytes: + width, height = 2048, 1536 + rows = b"".join(b"\0" + os.urandom(width * 3) for _ in range(height)) + return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + png_chunk(b"IDAT", zlib.compress(rows, 1)) + png_chunk(b"IEND", b"") + + +def mib(text: str) -> float: + match = re.fullmatch(r"([0-9.]+)(B|KiB|MiB|GiB)", text.strip()) + if not match: + raise ValueError("unexpected Docker memory unit") + return float(match.group(1)) * {"B": 1 / 1048576, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}[match.group(2)] + + +def memory_samples(elapsed: float) -> list[tuple[float, str, float, float]]: + command = ["rtk", "proxy", "docker", "stats", "--no-stream", "--format", "{{.Name}},{{.MemUsage}}", *API_NAMES] + output = subprocess.run(command, check=True, capture_output=True, text=True, timeout=10).stdout + rows = [] + for line in output.splitlines(): + name, usage = line.split(",", 1) + used, limit = usage.split("/", 1) + rows.append((round(elapsed, 3), name, round(mib(used), 3), round(mib(limit), 3))) + if len(rows) != 2: + raise AssertionError("expected two API container memory samples") + return rows + + +def main() -> None: + client = Client(timeout=60) + actor, _, _, chat = client.bootstrap() + data = large_png() + if len(data) > 10 * 1024 * 1024: + raise AssertionError("synthetic PNG exceeds upload limit") + expected_hash = hashlib.sha256(data).hexdigest() + barrier = threading.Barrier(10) + + def send(index: int) -> dict: + barrier.wait(timeout=10) + result = Client(timeout=60).call( + "POST", f"/api/v1/chats/{chat['id']}/attachments?filename=load-{index}.png", 201, + actor=actor, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment", + )["json"] + if result["sha256"] != expected_hash or result["size_bytes"] != len(data): + raise AssertionError("upload bytes/hash mismatch") + return result + + start = time.monotonic() + rows = memory_samples(0) + with ThreadPoolExecutor(max_workers=10) as workers: + futures = [workers.submit(send, index) for index in range(10)] + while not all(future.done() for future in futures): + rows.extend(memory_samples(time.monotonic() - start)) + results = [future.result() for future in futures] + rows.extend(memory_samples(time.monotonic() - start)) + if len({result["id"] for result in results}) != 10: + raise AssertionError("uploads did not create ten unique attachments") + EVIDENCE.parent.mkdir(exist_ok=True) + with EVIDENCE.open("w", newline="") as target: + writer = csv.writer(target, lineterminator="\n") + writer.writerow(("seconds", "container", "used_mib", "limit_mib")) + writer.writerows(rows) + peaks = {name: max(row[2] for row in rows if row[1] == name) for name in API_NAMES} + print(f"PASS: 10/10 uploads; PNG={len(data)} bytes; elapsed={time.monotonic()-start:.3f}s; peaks={peaks}; evidence={EVIDENCE.name}") + + +if __name__ == "__main__": + main() diff --git a/src/api.py b/src/api.py index 4d2965c..cef93bd 100644 --- a/src/api.py +++ b/src/api.py @@ -6,6 +6,7 @@ from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from .auth import basic_credentials, bearer_token +from .attachments import storage_ready, upload from .models import CreateChat, CreateMessage, CreateUser from .store import store @@ -19,7 +20,9 @@ def live(): @router.get("/health/ready") def ready(): - return store.ready() + result = store.ready() + storage_ready() + return result @router.post("/api/v1/users", status_code=201) @@ -78,6 +81,11 @@ def get_chat(chat_id: UUID, actor: dict = Depends(current_user)): return store.chat(actor["id"], str(chat_id)) +@router.post("/api/v1/chats/{chat_id}/attachments", status_code=201) +async def upload_attachment(chat_id: UUID, request: Request, filename: str = Query(...), actor: dict = Depends(current_user)): + return await upload(request, str(chat_id), actor["id"], filename) + + @router.post("/api/v1/chats/{chat_id}/messages", status_code=201) def create_message(chat_id: UUID, body: CreateMessage, request: Request, actor: dict = Depends(current_user)): key = request.headers.get("Idempotency-Key") diff --git a/src/attachments.py b/src/attachments.py index 8f4e3c6..de08798 100644 --- a/src/attachments.py +++ b/src/attachments.py @@ -1,13 +1,29 @@ """Private S3 access shared by attachment routes and maintenance jobs.""" +import asyncio +import hashlib +import logging import os +import unicodedata from functools import lru_cache from pathlib import Path +from tempfile import SpooledTemporaryFile +from uuid import UUID, uuid4 +from fastapi import HTTPException, Request from minio import Minio +from minio.error import S3Error +from PIL import Image, UnidentifiedImageError +from urllib3 import PoolManager, Retry, Timeout + +from .store import connection, store, timestamp BUCKET = "messenger-attachments" +MAX_BYTES = 10 * 1024 * 1024 +MAX_PIXELS = 40_000_000 +Image.MAX_IMAGE_PIXELS = MAX_PIXELS +logger = logging.getLogger(__name__) def secret(name: str) -> str: @@ -22,4 +38,114 @@ def storage() -> Minio: secret_key=secret("S3_SECRET_ACCESS_KEY"), secure=False, region="us-east-1", + http_client=PoolManager(timeout=Timeout(connect=2, read=10), retries=Retry(total=0)), ) + + +def storage_ready() -> None: + try: + storage().stat_object(BUCKET, "health/ready-probe") + except S3Error as exc: + if exc.code != "NoSuchKey": + raise HTTPException(503) from None + except Exception: + raise HTTPException(503) from None + + +def attachment_view(row: dict) -> dict: + return { + "id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), + "filename": row["filename"], "content_type": row["content_type"], + "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"], + "variants": [], "error_code": row["error_code"], + "created_at": timestamp(row["created_at"]), "updated_at": timestamp(row["updated_at"]), + } + + +def validate_filename(filename: str) -> None: + if not 1 <= len(filename) <= 255 or filename in {".", ".."}: + raise HTTPException(400) + if any(char in "/\\" or unicodedata.category(char) == "Cc" for char in filename): + raise HTTPException(400) + + +def validate_image(stream, declared_type: str) -> str: + try: + with Image.open(stream) as image: + actual_type = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format) + if actual_type is None or actual_type != declared_type: + raise HTTPException(415) + if image.width * image.height > MAX_PIXELS: + raise HTTPException(413) + image.verify() + stream.seek(0) + with Image.open(stream) as image: + image.load() + return actual_type + except Image.DecompressionBombError: + raise HTTPException(413) from None + except (UnidentifiedImageError, OSError, ValueError, SyntaxError): + raise HTTPException(415) from None + + +def persist_attachment(chat_id: str, actor_id: str, filename: str, content_type: str, size: int, sha256: str, stream) -> dict: + attachment_id = uuid4() + object_key = f"originals/{attachment_id}" + stream.seek(0) + try: + storage().put_object(BUCKET, object_key, stream, size, content_type=content_type) + except Exception: + logger.exception("S3 upload failed for attachment %s", attachment_id) + raise HTTPException(503) from None + + commit_uncertain = False + try: + with connection() as conn: + row = conn.execute( + "INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) " + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s) " + "RETURNING id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at", + (attachment_id, UUID(chat_id), UUID(actor_id), filename, object_key, content_type, size, sha256), + ).fetchone() + commit_uncertain = True + except Exception: + if commit_uncertain: + # The COMMIT may have succeeded despite a lost acknowledgment. Reconciliation decides later. + logger.error("Attachment commit outcome unknown; retain object %s for reconciliation", object_key) + else: + try: + storage().remove_object(BUCKET, object_key) + except Exception: + logger.exception("Orphan cleanup failed for object %s", object_key) + raise + return attachment_view(row) + + +async def upload(request: Request, chat_id: str, actor_id: str, filename: str) -> dict: + await asyncio.to_thread(store.chat, actor_id, chat_id) + validate_filename(filename) + declared_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + if declared_type not in {"image/png", "image/jpeg"}: + raise HTTPException(415) + length = request.headers.get("content-length") + if length is not None: + try: + if int(length) > MAX_BYTES: + raise HTTPException(413) + except ValueError: + raise HTTPException(400) from None + + with SpooledTemporaryFile(max_size=1024 * 1024) as stream: + digest = hashlib.sha256() + size = 0 + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_BYTES: + raise HTTPException(413) + stream.write(chunk) + digest.update(chunk) + stream.seek(0) + validate_image(stream, declared_type) + return await asyncio.to_thread( + persist_attachment, chat_id, actor_id, filename, declared_type, size, digest.hexdigest(), stream + ) diff --git a/src/main.py b/src/main.py index bcac75f..26dea4b 100644 --- a/src/main.py +++ b/src/main.py @@ -37,7 +37,8 @@ def error_response(request: Request, status: int, extra_headers: dict | None = N @app.middleware("http") async def request_contract(request: Request, call_next): request.state.request_id = str(uuid4()) - if request.method == "POST" and request.url.path.startswith("/api/v1/") and request.url.path != "/api/v1/auth/sessions": + is_upload = request.url.path.startswith("/api/v1/chats/") and request.url.path.endswith("/attachments") + if request.method == "POST" and request.url.path.startswith("/api/v1/") and request.url.path != "/api/v1/auth/sessions" and not is_upload: media_type, _, charset = request.headers.get("content-type", "").lower().partition(";") if media_type.strip() != "application/json" or (charset and charset.strip() != "charset=utf-8"): return error_response(request, 415) diff --git a/student-tests/fixtures/sample.jpg b/student-tests/fixtures/sample.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c3d7571f257c5c3bffdfa8b4b70c56070bf5a2c4 GIT binary patch literal 633 zcmex=^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<c1}I=;VrF4wW9Q)H;sz?% zD!{d!pzFb!U9xX3zTPI5o8roG<0MW4oqZMDikqloVbuf*=gfJ(V&YTRE(2~ znmD<{#3dx9RMpfqG__1j&CD$#!{;oGMf+Ml`TxHO0FAZJxBvhE literal 0 HcmV?d00001 diff --git a/student-tests/test_attachment_upload.py b/student-tests/test_attachment_upload.py new file mode 100644 index 0000000..277e1fe --- /dev/null +++ b/student-tests/test_attachment_upload.py @@ -0,0 +1,63 @@ +"""Black-box upload and validation checks; BASE_URL defaults to localhost:8080.""" + +import hashlib +import struct +import sys +import unittest +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 # noqa: E402 + + +PNG = (ROOT / "tests/fixtures/sample.png").read_bytes() +JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes() + + +class UploadTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.client = Client() + cls.alice, _, cls.eve, cls.chat = cls.client.bootstrap() + cls.path = f"/api/v1/chats/{cls.chat['id']}/attachments" + + def upload(self, content=PNG, media_type="image/png", filename="sample.png", expected=201, actor=None): + return self.client.call( + "POST", self.path + "?filename=" + quote(filename, safe=""), expected, + actor=actor or self.alice, raw=content, headers={"Content-Type": media_type}, + schema="Attachment" if expected == 201 else None, + ) + + def test_png_and_jpeg(self): + for content, media_type, filename in ((PNG, "image/png", "sample.png"), (JPEG, "image/jpeg", "sample.jpg")): + attachment = self.upload(content, media_type, filename)["json"] + self.assertEqual(attachment["status"], "ready") + self.assertEqual(attachment["owner_id"], self.alice["id"]) + self.assertEqual(attachment["chat_id"], self.chat["id"]) + self.assertEqual(attachment["content_type"], media_type) + self.assertEqual(attachment["size_bytes"], len(content)) + self.assertEqual(attachment["sha256"], hashlib.sha256(content).hexdigest()) + + def test_rejects_oversized_and_oversized_pixels(self): + self.upload(b"x" * (10 * 1024 * 1024 + 1), expected=413) + changed = bytearray(PNG) + changed[16:24] = struct.pack(">II", 6325, 6325) + changed[29:33] = struct.pack(">I", zlib.crc32(changed[12:29])) + self.upload(bytes(changed), expected=413) + + def test_rejects_invalid_image_and_mime_spoofing(self): + self.upload(PNG[:-10], expected=415) + self.upload(PNG, "image/jpeg", expected=415) + self.upload(b"not an image", expected=415) + + def test_rejects_unsafe_names_and_outsider(self): + for name in ("../bad.png", "folder\\bad.png", "bad\x00name.png", "bad\nname.png", ""): + self.upload(filename=name, expected=400) + self.upload(expected=404, actor=self.eve) + + +if __name__ == "__main__": + unittest.main() diff --git a/student-tests/test_database.py b/student-tests/test_database.py index 13067ee..ede3b89 100644 --- a/student-tests/test_database.py +++ b/student-tests/test_database.py @@ -31,7 +31,7 @@ class DatabaseTests(unittest.TestCase): def test_migration_and_unique_username_race(self): with psycopg.connect(URL) as conn: versions = conn.execute("SELECT version FROM schema_migrations").fetchall() - self.assertEqual(versions, [(1,), (2,), (3,), (4,)]) + self.assertEqual(versions, [(1,), (2,), (3,), (4,), (5,)]) name = "u_" + uuid4().hex[:16] def register(_): diff --git a/student-tests/test_s3_outage.py b/student-tests/test_s3_outage.py new file mode 100644 index 0000000..963548c --- /dev/null +++ b/student-tests/test_s3_outage.py @@ -0,0 +1,46 @@ +"""Run inside an API container while S3 is stopped; no secrets are printed.""" + +import io +import unittest +from urllib.error import HTTPError +from urllib.request import Request, urlopen +from uuid import uuid4 + +from PIL import Image + +from src.db import pool +from src.store import store + + +def status(path: str, data: bytes | None = None, headers: dict | None = None) -> int: + request = Request("http://127.0.0.1:8080" + path, data=data, headers=headers or {}, method="POST" if data is not None else "GET") + try: + with urlopen(request, timeout=15) as response: + return response.status + except HTTPError as error: + return error.code + + +class S3OutageTests(unittest.TestCase): + def test_unavailable_without_false_ready_or_metadata(self): + username = "s3_outage_" + uuid4().hex[:16] + user = store.register(username, "S3 outage", "Test-password-123") + session = store.create_session(username, "Test-password-123") + chat = store.create_chat(user["id"], "S3 outage", [user["id"]]) + with pool().connection() as conn: + before = conn.execute("SELECT count(*) AS n FROM attachments WHERE chat_id=%s", (chat["id"],)).fetchone()["n"] + data = io.BytesIO() + Image.new("RGB", (4, 3), (20, 60, 120)).save(data, format="PNG") + self.assertEqual(status("/health/ready"), 503) + self.assertEqual( + status(f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png", data.getvalue(), + {"Content-Type": "image/png", "Authorization": "Bearer " + session["token"]}), + 503, + ) + with pool().connection() as conn: + after = conn.execute("SELECT count(*) AS n FROM attachments WHERE chat_id=%s", (chat["id"],)).fetchone()["n"] + self.assertEqual(after, before) + + +if __name__ == "__main__": + unittest.main() diff --git a/student-tests/test_upload_failure.py b/student-tests/test_upload_failure.py new file mode 100644 index 0000000..663d5cf --- /dev/null +++ b/student-tests/test_upload_failure.py @@ -0,0 +1,68 @@ +"""Run inside an API image: python - < student-tests/test_upload_failure.py.""" + +import asyncio +import io +import unittest +from contextlib import contextmanager +from unittest.mock import Mock, patch +from uuid import uuid4 + +from fastapi import HTTPException + +from src import attachments + + +class UploadFailureTests(unittest.TestCase): + def test_post_put_database_failure_compensates(self): + client = Mock() + with patch.object(attachments, "storage", return_value=client), patch.object( + attachments, "connection", side_effect=HTTPException(503) + ): + with self.assertRaises(HTTPException) as failure: + attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) + self.assertEqual(failure.exception.status_code, 503) + key = client.put_object.call_args.args[1] + client.remove_object.assert_called_once_with(attachments.BUCKET, key) + + def test_s3_failure_does_not_touch_database(self): + client = Mock() + client.put_object.side_effect = OSError("simulated outage") + with patch.object(attachments, "storage", return_value=client), patch.object(attachments, "connection") as db: + with self.assertRaises(HTTPException) as failure: + attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) + self.assertEqual(failure.exception.status_code, 503) + db.assert_not_called() + + def test_ambiguous_commit_keeps_object_for_reconciliation(self): + @contextmanager + def ambiguous_commit(): + connection = Mock() + connection.execute.return_value.fetchone.return_value = {} + yield connection + raise HTTPException(503) + + client = Mock() + with patch.object(attachments, "storage", return_value=client), patch.object( + attachments, "connection", side_effect=ambiguous_commit + ): + with self.assertRaises(HTTPException) as failure: + attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) + self.assertEqual(failure.exception.status_code, 503) + client.remove_object.assert_not_called() + + def test_interrupted_request_never_starts_s3_put(self): + class Interrupted: + headers = {"content-type": "image/png"} + + async def stream(self): + yield b"partial" + raise OSError("client disconnected") + + with patch.object(attachments.store, "chat"), patch.object(attachments, "storage") as client: + with self.assertRaises(OSError): + asyncio.run(attachments.upload(Interrupted(), str(uuid4()), str(uuid4()), "test.png")) + client.assert_not_called() + + +if __name__ == "__main__": + unittest.main()