This commit is contained in:
caramelteawithmint
2026-11-13 18:18:57 +03:00
parent 09e26c3c5a
commit a72f814e65
8 changed files with 574 additions and 62 deletions
+126 -6
View File
@@ -1,3 +1,116 @@
# name: mtusi-messenger
# x-api-base: &api-base
# build: .
# environment:
# - DATABASE_URL_FILE=/run/secrets/database_url
# - SESSION_TTL_SECONDS=3600
# - S3_ENDPOINT=http://minio:9000
# - S3_ACCESS_KEY=minioadmin
# - S3_SECRET_KEY=minioadmin
# - S3_BUCKET=messenger-attachments
# secrets:
# - database_url
# depends_on:
# postgres:
# condition: service_healthy
# minio:
# condition: service_healthy
# migrate:
# condition: service_completed_successfully
# services:
# postgres:
# image: postgres:16-alpine
# environment:
# POSTGRES_USER: messenger
# POSTGRES_PASSWORD: messenger
# POSTGRES_DB: messenger
# healthcheck:
# test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
# interval: 5s
# timeout: 3s
# retries: 5
# volumes:
# - pgdata:/var/lib/postgresql/data
# minio:
# image: pgsty/silo:latest
# command: server /data --console-address ":9001"
# environment:
# MINIO_ROOT_USER: minioadmin
# MINIO_ROOT_PASSWORD: minioadmin
# volumes:
# - miniodata:/data
# healthcheck:
# test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
# interval: 5s
# timeout: 3s
# retries: 5
# minio-init:
# image: pgsty/silo:latest
# depends_on:
# minio:
# condition: service_healthy
# entrypoint: >
# /bin/sh -c "
# mc alias set myminio http://minio:9000 minioadmin minioadmin;
# mc mb myminio/messenger-attachments --ignore-existing;
# mc anonymous set none myminio/messenger-attachments;
# exit 0;
# "
# migrate:
# build: .
# command: ["python", "scripts/migrate.py"]
# environment:
# - DATABASE_URL_FILE=/run/secrets/database_url
# secrets:
# - database_url
# depends_on:
# postgres:
# condition: service_healthy
# api1:
# <<: *api-base
# environment:
# - INSTANCE_ID=api-1
# - DATABASE_URL_FILE=/run/secrets/database_url
# - SESSION_TTL_SECONDS=3600
# - S3_ENDPOINT=http://minio:9000
# - S3_ACCESS_KEY=minioadmin
# - S3_SECRET_KEY=minioadmin
# - S3_BUCKET=messenger-attachments
# api2:
# <<: *api-base
# environment:
# - INSTANCE_ID=api-2
# - DATABASE_URL_FILE=/run/secrets/database_url
# - SESSION_TTL_SECONDS=3600
# - S3_ENDPOINT=http://minio:9000
# - S3_ACCESS_KEY=minioadmin
# - S3_SECRET_KEY=minioadmin
# - S3_BUCKET=messenger-attachments
# load_balancer:
# image: nginx:1.27-alpine
# ports:
# - "8080:8080"
# volumes:
# - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
# depends_on:
# - api1
# - api2
# secrets:
# database_url:
# file: ./secrets/database_url
# volumes:
# pgdata:
# miniodata:
name: mtusi-messenger
x-api-base: &api-base
@@ -6,8 +119,8 @@ x-api-base: &api-base
- DATABASE_URL_FILE=/run/secrets/database_url
- SESSION_TTL_SECONDS=3600
- S3_ENDPOINT=http://minio:9000
- S3_ACCESS_KEY=minioadmin
- S3_SECRET_KEY=minioadmin
- S3_ACCESS_KEY=api-user
- S3_SECRET_KEY=api-secret-key-12345
- S3_BUCKET=messenger-attachments
secrets:
- database_url
@@ -47,17 +160,24 @@ services:
interval: 5s
timeout: 3s
retries: 5
# Порт 9000 (API) и 9001 (Консоль) НЕ пробрасываем наружу, чтобы админка была закрыта.
# Контейнеры общаются по внутренней сети Docker.
minio-init:
image: pgsty/silo:latest
depends_on:
minio:
condition: service_healthy
volumes:
- ./infra/minio-policy.json:/tmp/minio-policy.json:ro
entrypoint: >
/bin/sh -c "
mc alias set myminio http://minio:9000 minioadmin minioadmin;
mc mb myminio/messenger-attachments --ignore-existing;
mc anonymous set none myminio/messenger-attachments;
mc admin user add myminio api-user api-secret-key-12345 || true;
mc admin policy create myminio api-policy /tmp/minio-policy.json || true;
mc admin policy attach myminio api-policy --user api-user || true;
exit 0;
"
@@ -79,8 +199,8 @@ services:
- DATABASE_URL_FILE=/run/secrets/database_url
- SESSION_TTL_SECONDS=3600
- S3_ENDPOINT=http://minio:9000
- S3_ACCESS_KEY=minioadmin
- S3_SECRET_KEY=minioadmin
- S3_ACCESS_KEY=api-user
- S3_SECRET_KEY=api-secret-key-12345
- S3_BUCKET=messenger-attachments
api2:
@@ -90,8 +210,8 @@ services:
- DATABASE_URL_FILE=/run/secrets/database_url
- SESSION_TTL_SECONDS=3600
- S3_ENDPOINT=http://minio:9000
- S3_ACCESS_KEY=minioadmin
- S3_SECRET_KEY=minioadmin
- S3_ACCESS_KEY=api-user
- S3_SECRET_KEY=api-secret-key-12345
- S3_BUCKET=messenger-attachments
load_balancer:
+17
View File
@@ -0,0 +1,17 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::messenger-attachments",
"arn:aws:s3:::messenger-attachments/*"
]
}
]
}
+2
View File
@@ -0,0 +1,2 @@
@echo off
docker compose restart
+9
View File
@@ -0,0 +1,9 @@
@echo off
if "%TARGET_INSTANCE_ID%"=="api-1" (
docker compose stop api1
) else if "%TARGET_INSTANCE_ID%"=="api-2" (
docker compose stop api2
) else (
echo Unknown instance
exit /b 1
)
+27 -14
View File
@@ -1,6 +1,27 @@
import io
from PIL import Image
# import io
# from PIL import Image
# def detect_image_type(data: bytes) -> str | None:
# if data.startswith(b"\x89PNG\r\n\x1a\n"):
# return "image/png"
# if data.startswith(b"\xff\xd8\xff"):
# return "image/jpeg"
# return None
# def check_image(data: bytes, allowed_types: list[str]) -> tuple[str, int, int]:
# content_type = detect_image_type(data)
# if not content_type or content_type not in allowed_types:
# raise ValueError("Invalid or unsupported image type")
# try:
# with Image.open(io.BytesIO(data)) as img:
# width, height = img.size
# if width * height > 40_000_000:
# raise ValueError("Too many pixels")
# except Exception as e:
# raise ValueError(f"Broken image: {e}")
# return content_type, width, height
def detect_image_type(data: bytes) -> str | None:
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
@@ -8,17 +29,9 @@ def detect_image_type(data: bytes) -> str | None:
return "image/jpeg"
return None
def check_image(data: bytes, allowed_types: list[str]) -> tuple[str, int, int]:
content_type = detect_image_type(data)
def check_image(first_bytes: bytes, allowed_types: list[str]) -> tuple[str, int, int]:
content_type = detect_image_type(first_bytes)
if not content_type or content_type not in allowed_types:
raise ValueError("Invalid or unsupported image type")
try:
with Image.open(io.BytesIO(data)) as img:
width, height = img.size
if width * height > 40_000_000:
raise ValueError("Too many pixels")
except Exception as e:
raise ValueError(f"Broken image: {e}")
return content_type, width, height
return content_type, 0, 0
+240 -41
View File
@@ -1,5 +1,177 @@
# import hashlib
# import io
# import uuid
# from fastapi import APIRouter, Depends, Request, Query
# from fastapi.responses import StreamingResponse
# from psycopg.rows import dict_row
# from ..db import transaction, connection
# from ..errors import ApiError
# from ..s3 import upload_fileobj, download_fileobj
# from ..image_check import check_image
# from ..serializers import iso_z
# from .sessions import require_actor
# router = APIRouter(prefix="/api/v1")
# MAX_SIZE = 10 * 1024 * 1024
# @router.post("/chats/{chat_id}/attachments", status_code=201)
# async def upload_attachment(
# chat_id: str,
# request: Request,
# filename: str = Query(..., max_length=255),
# actor: dict = Depends(require_actor),
# ):
# try:
# uuid.UUID(chat_id)
# except ValueError:
# raise ApiError(400, "invalid_request", "Неверный chat_id")
# if "/" in filename or "\\" in filename or "\0" in filename:
# raise ApiError(400, "invalid_request", "Опасное имя файла")
# # Читаем тело запроса (raw bytes)
# content = await request.body()
# if len(content) > MAX_SIZE:
# raise ApiError(413, "payload_too_large", "Файл слишком большой")
# if len(content) == 0:
# raise ApiError(400, "invalid_request", "Пустой файл")
# try:
# content_type, width, height = check_image(content, ["image/png", "image/jpeg"])
# except ValueError as e:
# if "pixels" in str(e):
# raise ApiError(413, "payload_too_large", "Слишком много пикселей")
# raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат")
# # Проверяем доступ
# with connection() as conn:
# with conn.cursor() as cur:
# cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, actor["user_id"]))
# if cur.fetchone() is None:
# raise ApiError(404, "not_found", "Чат не найден")
# sha256 = hashlib.sha256(content).hexdigest()
# object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
# # Загружаем в S3
# try:
# upload_fileobj(io.BytesIO(content), object_key, content_type)
# except Exception as e:
# print(f"S3 error: {e}")
# raise ApiError(503, "unavailable", "S3 недоступен")
# # Сохраняем в базу
# with transaction() as conn:
# with conn.cursor(row_factory=dict_row) as cur:
# cur.execute(
# """
# INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
# VALUES (%s, %s, %s, %s, %s, %s, %s)
# RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at
# """,
# (chat_id, actor["user_id"], filename, content_type, len(content), sha256, object_key),
# )
# att = cur.fetchone()
# return {
# "id": str(att["id"]),
# "chat_id": str(att["chat_id"]),
# "owner_id": str(att["owner_id"]),
# "filename": att["filename"],
# "content_type": att["content_type"],
# "size_bytes": att["size_bytes"],
# "sha256": att["sha256"],
# "status": "ready",
# "variants": [],
# "error_code": None,
# "created_at": iso_z(att["created_at"]),
# "updated_at": iso_z(att["created_at"]),
# }
# @router.get("/attachments/{attachment_id}")
# def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
# try:
# uuid.UUID(attachment_id)
# except ValueError:
# raise ApiError(400, "invalid_request", "Неверный id")
# with connection() as conn:
# with conn.cursor(row_factory=dict_row) as cur:
# cur.execute(
# """
# SELECT a.*, 1 as exists
# FROM attachments a
# JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
# WHERE a.id = %s
# """,
# (actor["user_id"], attachment_id)
# )
# att = cur.fetchone()
# if att is None:
# raise ApiError(404, "not_found", "Вложение не найдено")
# return {
# "id": str(att["id"]),
# "chat_id": str(att["chat_id"]),
# "owner_id": str(att["owner_id"]),
# "filename": att["filename"],
# "content_type": att["content_type"],
# "size_bytes": att["size_bytes"],
# "sha256": att["sha256"],
# "status": "ready",
# "variants": [],
# "error_code": None,
# "created_at": iso_z(att["created_at"]),
# "updated_at": iso_z(att["created_at"]),
# }
# @router.get("/attachments/{attachment_id}/content")
# def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
# try:
# uuid.UUID(attachment_id)
# except ValueError:
# raise ApiError(400, "invalid_request", "Неверный id")
# with connection() as conn:
# with conn.cursor(row_factory=dict_row) as cur:
# cur.execute(
# """
# SELECT a.object_key, a.content_type, a.filename
# FROM attachments a
# JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
# WHERE a.id = %s
# """,
# (actor["user_id"], attachment_id)
# )
# att = cur.fetchone()
# if att is None:
# raise ApiError(404, "not_found", "Вложение не найдено")
# try:
# body = download_fileobj(att["object_key"])
# except Exception:
# raise ApiError(503, "unavailable", "S3 недоступен")
# def iter_body():
# yield from body.iter_chunks(1024 * 1024)
# return StreamingResponse(
# iter_body(),
# media_type=att["content_type"],
# headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'}
# )
import hashlib
import io
import tempfile
import uuid
from fastapi import APIRouter, Depends, Request, Query
@@ -8,7 +180,7 @@ from psycopg.rows import dict_row
from ..db import transaction, connection
from ..errors import ApiError
from ..s3 import upload_fileobj, download_fileobj
from ..s3 import upload_fileobj, download_fileobj, delete_file
from ..image_check import check_image
from ..serializers import iso_z
from .sessions import require_actor
@@ -33,49 +205,76 @@ async def upload_attachment(
if "/" in filename or "\\" in filename or "\0" in filename:
raise ApiError(400, "invalid_request", "Опасное имя файла")
# Читаем тело запроса (raw bytes)
content = await request.body()
if len(content) > MAX_SIZE:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
if len(content) == 0:
raise ApiError(400, "invalid_request", "Пустой файл")
try:
content_type, width, height = check_image(content, ["image/png", "image/jpeg"])
except ValueError as e:
if "pixels" in str(e):
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат")
# Проверяем доступ
# Проверяем доступ к чату
with connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, actor["user_id"]))
cur.execute(
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
(chat_id, actor["user_id"]),
)
if cur.fetchone() is None:
raise ApiError(404, "not_found", "Чат не найден")
sha256 = hashlib.sha256(content).hexdigest()
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
sha256 = hashlib.sha256()
size = 0
first_chunk = b""
# Загружаем в S3
# Читаем потоково во временный файл (чтобы не забивать RAM)
with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_SIZE:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
if not first_chunk:
first_chunk = chunk[:16] # для детекта MIME
sha256.update(chunk)
spooled.write(chunk)
if size == 0:
raise ApiError(400, "invalid_request", "Пустой файл")
# Полная проверка картинки через Pillow
try:
spooled.seek(0)
content = spooled.read()
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
from PIL import Image
Image.open(io.BytesIO(content)).verify()
except Exception:
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый или битый формат")
sha256_hex = sha256.hexdigest()
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
# Загружаем в S3
try:
spooled.seek(0)
upload_fileobj(spooled, object_key, content_type)
except Exception as e:
print(f"S3 error: {e}")
raise ApiError(503, "unavailable", "S3 недоступен")
# Сохраняем в БД (с компенсацией)
try:
upload_fileobj(io.BytesIO(content), object_key, content_type)
with transaction() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at
""",
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
)
att = cur.fetchone()
except Exception as e:
print(f"S3 error: {e}")
raise ApiError(503, "unavailable", "S3 недоступен")
# Сохраняем в базу
with transaction() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at
""",
(chat_id, actor["user_id"], filename, content_type, len(content), sha256, object_key),
)
att = cur.fetchone()
# КОМПЕНСАЦИЯ: удаляем из S3, если БД упала
print(f"DB failed, compensating S3: {e}")
try:
delete_file(object_key)
except Exception as s3_e:
print(f"Failed to compensate S3: {s3_e}")
raise ApiError(500, "internal_error", "Ошибка сохранения")
return {
"id": str(att["id"]),
@@ -104,15 +303,15 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
SELECT a.*, 1 as exists
SELECT a.*
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s
""",
(actor["user_id"], attachment_id)
(actor["user_id"], attachment_id),
)
att = cur.fetchone()
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
@@ -148,7 +347,7 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s
""",
(actor["user_id"], attachment_id)
(actor["user_id"], attachment_id),
)
att = cur.fetchone()
@@ -166,5 +365,5 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)
return StreamingResponse(
iter_body(),
media_type=att["content_type"],
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'}
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'},
)
+40 -1
View File
@@ -1,7 +1,38 @@
# import boto3
# from botocore.config import Config
# from .config import get_settings
# def get_s3_client():
# s = get_settings()
# return boto3.client(
# "s3",
# endpoint_url=s.s3_endpoint,
# aws_access_key_id=s.s3_access_key,
# aws_secret_access_key=s.s3_secret_key,
# region_name=s.s3_region,
# config=Config(signature_version="s3v4"),
# )
# def upload_fileobj(fileobj, key: str, content_type: str):
# client = get_s3_client()
# s = get_settings()
# client.upload_fileobj(
# fileobj,
# s.s3_bucket,
# key,
# ExtraArgs={"ContentType": content_type},
# )
# def download_fileobj(key: str):
# client = get_s3_client()
# s = get_settings()
# obj = client.get_object(Bucket=s.s3_bucket, Key=key)
# return obj["Body"]
import boto3
from botocore.config import Config
from .config import get_settings
def get_s3_client():
s = get_settings()
return boto3.client(
@@ -13,6 +44,7 @@ def get_s3_client():
config=Config(signature_version="s3v4"),
)
def upload_fileobj(fileobj, key: str, content_type: str):
client = get_s3_client()
s = get_settings()
@@ -23,8 +55,15 @@ def upload_fileobj(fileobj, key: str, content_type: str):
ExtraArgs={"ContentType": content_type},
)
def download_fileobj(key: str):
client = get_s3_client()
s = get_settings()
obj = client.get_object(Bucket=s.s3_bucket, Key=key)
return obj["Body"]
return obj["Body"]
def delete_file(key: str):
client = get_s3_client()
s = get_settings()
client.delete_object(Bucket=s.s3_bucket, Key=key)
+113
View File
@@ -0,0 +1,113 @@
import base64
import io
import json
import os
import random
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
def req(method, path, data=None, headers=None, raw=None):
r = urllib.request.Request(BASE_URL + path, method=method)
if headers:
for k, v in headers.items():
r.add_header(k, v)
if data:
r.add_header("Content-Type", "application/json")
r.data = json.dumps(data).encode("utf-8")
if raw:
r.data = raw
try:
with urllib.request.urlopen(r) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def setup():
u = "test4_" + str(random.randint(1000, 9999))
_, body = req("POST", "/api/v1/users", {"username": u, "display_name": "Тест", "password": "testpassword1234"})
user = json.loads(body)
cred = base64.b64encode((u + ":testpassword1234").encode()).decode()
_, body = req("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
token = json.loads(body)["token"]
headers = {"Authorization": "Bearer " + token}
_, body = req("POST", "/api/v1/chats", {"title": "Тестовый чат", "member_ids": [user["id"]]}, headers)
chat = json.loads(body)
return user, chat, headers
def main():
user, chat, headers = setup()
print(f"Пользователь {user['id']} и чат {chat['id']} созданы.")
chat_url = f"/api/v1/chats/{chat['id']}/attachments"
# 1. Слишком большой файл (11 МБ)
print("1. Тест: слишком большой файл...")
big_data = b"\x89PNG\r\n\x1a\n" + b"A" * (11 * 1024 * 1024)
status, _ = req("POST", chat_url + "?filename=big.png", headers={**headers, "Content-Type": "image/png"}, raw=big_data)
assert status == 413, f"Ожидали 413, получили {status}"
print(" OK (413)")
# 2. Битый файл (MIME PNG, но внутри мусор)
print("2. Тест: битый файл...")
broken_data = b"\x89PNG\r\n\x1a\n" + b"broken data"
status, _ = req("POST", chat_url + "?filename=broken.png", headers={**headers, "Content-Type": "image/png"}, raw=broken_data)
assert status == 415, f"Ожидали 415, получили {status}"
print(" OK (415)")
# 3. Подмена MIME (говорим image/png, а внутри текст)
print("3. Тест: подмена MIME...")
text_data = b"Hello, this is not an image!"
status, _ = req("POST", chat_url + "?filename=fake.png", headers={**headers, "Content-Type": "image/png"}, raw=text_data)
assert status == 415, f"Ожидали 415, получили {status}"
print(" OK (415)")
# 4. Опасное имя файла (path traversal)
print("4. Тест: опасное имя файла...")
with open("tests/fixtures/sample.png", "rb") as f:
valid_png = f.read()
status, _ = req("POST", chat_url + "?filename=../../etc/passwd", headers={**headers, "Content-Type": "image/png"}, raw=valid_png)
assert status == 400, f"Ожидали 400, получили {status}"
print(" OK (400)")
# 5. Успешная загрузка (чтобы проверить доступ)
print("5. Тест: успешная загрузка...")
status, body = req("POST", chat_url + "?filename=ok.png", headers={**headers, "Content-Type": "image/png"}, raw=valid_png)
assert status == 201, f"Ожидали 201, получили {status}"
att = json.loads(body)
print(f" OK (201), ID: {att['id']}")
# 6. Чужой доступ
print("6. Тест: чужой доступ...")
u_eve = "eve_" + str(random.randint(1000, 9999))
req("POST", "/api/v1/users", {"username": u_eve, "display_name": "Eve", "password": "testpassword1234"})
cred_eve = base64.b64encode((u_eve + ":testpassword1234").encode()).decode()
_, body = req("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred_eve})
token_eve = json.loads(body)["token"]
headers_eve = {"Authorization": "Bearer " + token_eve}
status, _ = req("GET", f"/api/v1/attachments/{att['id']}", headers=headers_eve)
assert status == 404, f"Ожидали 404 (чужой), получили {status}"
print(" OK (404)")
# 7. Нагрузочный тест (10 параллельных загрузок)
print("7. Тест: 10 параллельных загрузок (проверка RAM)...")
def upload_worker():
status, _ = req("POST", chat_url + "?filename=parallel.png", headers={**headers, "Content-Type": "image/png"}, raw=valid_png)
return status
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(lambda _: upload_worker(), range(10)))
assert all(s == 201 for s in results), f"Не все загрузки успешны: {results}"
print(" OK (все 10 успешно)")
print("\nPASS: Уровень 4 пройден! (Все негативные тесты и нагрузка работают)")
if __name__ == "__main__":
main()