forked from mtusi2026/mtusi2026lab4
исправила замечания
This commit is contained in:
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
- Автор, группа: Никифорова Екатерина, БВТ2301
|
- Автор, группа: Никифорова Екатерина, БВТ2301
|
||||||
- Целевая оценка: **4** (уровни 3 и 4, трек 5 не заявлен)
|
- Целевая оценка: **4** (уровни 3 и 4, трек 5 не заявлен)
|
||||||
- Commit/PR: https://gitea.privcloud.tech/eqktrin/mtusi2026lab4/pulls (PR после публикации)
|
- Commit/PR: https://gitea.privcloud.tech/mtusi2026lab4/pulls (PR после публикации)
|
||||||
- Источники, библиотеки, помощь ИИ: FastAPI 0.115, Uvicorn 0.30,
|
- Источники, библиотеки, помощь ИИ: FastAPI 0.115, Uvicorn 0.30,
|
||||||
PostgreSQL 17.6, Valkey 8.1.3, Silo (`pgsty/silo` — поддерживаемый форк
|
PostgreSQL 17.6, Valkey 8.1.3, Silo (`pgsty/silo` — поддерживаемый форк
|
||||||
MinIO: официальные образы MinIO удалены с Docker Hub и Quay в 2025),
|
MinIO: официальные образы MinIO удалены с Docker Hub и Quay в 2025),
|
||||||
|
|||||||
+42
-36
@@ -1,5 +1,6 @@
|
|||||||
"""Логика вложений: проверка изображений, загрузка в S3, компенсация."""
|
"""Логика вложений: проверка изображений, загрузка в S3, компенсация."""
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
@@ -11,59 +12,67 @@ log = logging.getLogger("attachments")
|
|||||||
|
|
||||||
ALLOWED_FORMATS = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
ALLOWED_FORMATS = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||||
|
|
||||||
# PIL отказывается читать изображение с числом пикселей больше лимита,
|
# PIL отказывается читать изображение с числом пикселей больше лимита.
|
||||||
# ещё до полной распаковки — это защита от decompression bomb.
|
|
||||||
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
|
||||||
|
|
||||||
|
# Ограничиваем одновременные декодирования, чтобы пик RAM
|
||||||
|
# (≤ MAX_IMAGE_PIXELS × 4 байт на каждое) укладывался в mem_limit контейнера.
|
||||||
|
_decode_slots = threading.BoundedSemaphore(3)
|
||||||
|
|
||||||
|
|
||||||
def validate_filename(filename):
|
def validate_filename(filename):
|
||||||
"""Отображаемое имя; ключ S3 формирует сервер."""
|
"""Отображаемое имя; ключ S3 формирует сервер.
|
||||||
|
|
||||||
|
Запрещены / \\ NUL и любые control-символы 0x00–0x1F и DEL 0x7F.
|
||||||
|
"""
|
||||||
if not isinstance(filename, str) or not (1 <= len(filename) <= 255):
|
if not isinstance(filename, str) or not (1 <= len(filename) <= 255):
|
||||||
raise bad_request("Некорректное имя файла")
|
raise bad_request("Некорректное имя файла")
|
||||||
if any(c in filename for c in ("/", "\\", "\x00")) or any(ord(c) < 0x20 for c in filename):
|
for c in filename:
|
||||||
raise bad_request("Недопустимое имя файла")
|
if c in ("/", "\\", "\x00") or ord(c) < 0x20 or ord(c) == 0x7F:
|
||||||
|
raise bad_request("Недопустимое имя файла")
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def _inspect_image(fileobj):
|
def _inspect_image(fileobj):
|
||||||
"""Формат и размеры из заголовка, затем целостность через verify().
|
"""Полная валидация: заголовок → лимиты → load().
|
||||||
|
|
||||||
verify() не декодирует пиксели, только проверяет CRC/структуру.
|
load() декодирует IDAT (PNG) / энтропийные данные (JPEG). Битый поток
|
||||||
|
даёт OSError('broken data stream') → 415. Память ограничена
|
||||||
|
MAX_IMAGE_PIXELS × 4 байт и семафором _decode_slots.
|
||||||
"""
|
"""
|
||||||
try:
|
with _decode_slots:
|
||||||
with Image.open(fileobj) as img:
|
try:
|
||||||
fmt = img.format
|
with Image.open(fileobj) as img:
|
||||||
width, height = img.size
|
fmt = img.format
|
||||||
img.verify()
|
width, height = img.size
|
||||||
except UnidentifiedImageError:
|
if fmt not in ALLOWED_FORMATS:
|
||||||
raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения")
|
raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG")
|
||||||
except Image.DecompressionBombError:
|
if width <= 0 or height <= 0:
|
||||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||||||
except Exception:
|
if width * height > config.MAX_IMAGE_PIXELS:
|
||||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||||
|
# Полное декодирование: проверяет целостность IDAT-потока,
|
||||||
if fmt not in ALLOWED_FORMATS:
|
# а не только CRC чанков (как verify()).
|
||||||
raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG")
|
img.load()
|
||||||
if width <= 0 or height <= 0:
|
return ALLOWED_FORMATS[fmt]
|
||||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
except UnidentifiedImageError:
|
||||||
if width * height > config.MAX_IMAGE_PIXELS:
|
raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения")
|
||||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
except Image.DecompressionBombError:
|
||||||
return ALLOWED_FORMATS[fmt]
|
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||||
|
except (OSError, SyntaxError, ValueError):
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение")
|
||||||
|
finally:
|
||||||
|
fileobj.seek(0)
|
||||||
|
|
||||||
|
|
||||||
def inspect_image_file(fileobj, total_bytes):
|
def inspect_image_file(fileobj, total_bytes):
|
||||||
"""Проверяет уже прочитанное тело. Возвращает фактический content_type.
|
"""Проверяет уже прочитанное тело. Возвращает фактический content_type."""
|
||||||
|
|
||||||
fileobj должен быть seekable; после вызова позиция = 0.
|
|
||||||
"""
|
|
||||||
if total_bytes == 0:
|
if total_bytes == 0:
|
||||||
raise bad_request("Пустой файл")
|
raise bad_request("Пустой файл")
|
||||||
if total_bytes > config.MAX_UPLOAD_BYTES:
|
if total_bytes > config.MAX_UPLOAD_BYTES:
|
||||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||||
fileobj.seek(0)
|
fileobj.seek(0)
|
||||||
content_type = _inspect_image(fileobj)
|
return _inspect_image(fileobj)
|
||||||
fileobj.seek(0)
|
|
||||||
return content_type
|
|
||||||
|
|
||||||
|
|
||||||
def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, content_type):
|
def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, content_type):
|
||||||
@@ -84,7 +93,6 @@ def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, con
|
|||||||
s3.put_object(object_key, fileobj, content_type, content_length=total_bytes)
|
s3.put_object(object_key, fileobj, content_type, content_length=total_bytes)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log.warning("S3 PUT failed for %s: %s", attachment_id, type(exc).__name__)
|
log.warning("S3 PUT failed for %s: %s", attachment_id, type(exc).__name__)
|
||||||
# Компенсация: удаляем возможный частичный объект.
|
|
||||||
s3.delete_object(object_key)
|
s3.delete_object(object_key)
|
||||||
with db.connection() as conn:
|
with db.connection() as conn:
|
||||||
repo.mark_attachment_failed(conn, attachment_id, "storage_unavailable")
|
repo.mark_attachment_failed(conn, attachment_id, "storage_unavailable")
|
||||||
@@ -94,8 +102,6 @@ def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, con
|
|||||||
with db.connection() as conn:
|
with db.connection() as conn:
|
||||||
ready = repo.mark_attachment_ready(conn, attachment_id)
|
ready = repo.mark_attachment_ready(conn, attachment_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
# Объект уже в S3, но COMMIT в БД не прошёл → orphan-pending.
|
|
||||||
# scripts/reconcile_s3.py найдёт и удалит после grace period.
|
|
||||||
log.error("S3 object %s left orphaned after DB failure", object_key)
|
log.error("S3 object %s left orphaned after DB failure", object_key)
|
||||||
raise
|
raise
|
||||||
if ready is None:
|
if ready is None:
|
||||||
|
|||||||
+15
-16
@@ -1,28 +1,34 @@
|
|||||||
"""Логика идемпотентности для POST запросов."""
|
"""Логика идемпотентности для POST запросов."""
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
from .errors import ApiError, bad_request
|
from .errors import ApiError, bad_request
|
||||||
|
|
||||||
|
# Контракт: ASCII [A-Za-z0-9._:-]{1,128}
|
||||||
|
_IDEM_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||||
|
|
||||||
|
|
||||||
def get_request_hash(data: dict) -> str:
|
def get_request_hash(data: dict) -> str:
|
||||||
"""Хеш тела запроса, независимый от порядка ключей."""
|
"""Хеш тела, независимый от порядка ключей.
|
||||||
return hashlib.sha256(json.dumps(data, sort_keys=True).encode("utf-8")).hexdigest()
|
|
||||||
|
Отсутствующий attachment_ids семантически равен [] — нормализуем,
|
||||||
|
иначе {"text":"x"} и {"text":"x","attachment_ids":[]} дают разные хеши.
|
||||||
|
"""
|
||||||
|
normalized = dict(data)
|
||||||
|
normalized.setdefault("attachment_ids", [])
|
||||||
|
return hashlib.sha256(json.dumps(normalized, sort_keys=True).encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_hash: str):
|
def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_hash: str):
|
||||||
"""
|
|
||||||
Блокирует ключ идемпотентности через advisory lock в PostgreSQL.
|
|
||||||
"""
|
|
||||||
if not key:
|
if not key:
|
||||||
raise bad_request("Missing Idempotency-Key")
|
raise bad_request("Missing Idempotency-Key")
|
||||||
if not isinstance(key, str) or not (1 <= len(key) <= 128):
|
if not _IDEM_KEY_RE.fullmatch(key):
|
||||||
raise bad_request("Invalid Idempotency-Key format")
|
raise bad_request("Invalid Idempotency-Key format")
|
||||||
|
|
||||||
# Берем блокировку на уровне БД по хешу ключа.
|
|
||||||
lock_id = f"{user_id}:{method}:{path}:{key}"
|
lock_id = f"{user_id}:{method}:{path}:{key}"
|
||||||
conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (lock_id,))
|
conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (lock_id,))
|
||||||
|
|
||||||
# Проверяем, есть ли уже такой ключ
|
|
||||||
row = conn.execute("""
|
row = conn.execute("""
|
||||||
SELECT request_hash, status_code, response_body
|
SELECT request_hash, status_code, response_body
|
||||||
FROM idempotency_keys
|
FROM idempotency_keys
|
||||||
@@ -30,22 +36,16 @@ def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_has
|
|||||||
""", (user_id, method, path, key)).fetchone()
|
""", (user_id, method, path, key)).fetchone()
|
||||||
|
|
||||||
if row:
|
if row:
|
||||||
# Ключ уже существует
|
|
||||||
if row["request_hash"] != req_hash:
|
if row["request_hash"] != req_hash:
|
||||||
raise ApiError(409, "conflict", "Idempotency-Key conflict: body differs")
|
raise ApiError(409, "conflict", "Idempotency-Key conflict: body differs")
|
||||||
|
|
||||||
# Если запрос уже был успешно обработан, возвращаем сохраненный ответ
|
|
||||||
if row["status_code"] is not None and row["response_body"] is not None:
|
if row["status_code"] is not None and row["response_body"] is not None:
|
||||||
return False, json.loads(row["response_body"])
|
return False, json.loads(row["response_body"])
|
||||||
|
|
||||||
# Если status_code пустой, значит первая транзакция упала. Разрешаем перезапись.
|
|
||||||
return True, None
|
return True, None
|
||||||
|
|
||||||
return True, None
|
return True, None
|
||||||
|
|
||||||
|
|
||||||
def save_result(conn, user_id: str, method: str, path: str, key: str, req_hash: str, status_code: int, response_body: dict):
|
def save_result(conn, user_id, method, path, key, req_hash, status_code, response_body):
|
||||||
"""Сохраняет результат выполнения запроса для будущих повторных вызовов."""
|
|
||||||
conn.execute("""
|
conn.execute("""
|
||||||
INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body)
|
INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||||
@@ -55,7 +55,6 @@ def save_result(conn, user_id: str, method: str, path: str, key: str, req_hash:
|
|||||||
|
|
||||||
|
|
||||||
def cleanup(conn, ttl_seconds: int):
|
def cleanup(conn, ttl_seconds: int):
|
||||||
"""Оппортунистическая очистка старых ключей (через подзапрос, т.к. DELETE LIMIT в PG нет)."""
|
|
||||||
conn.execute("""
|
conn.execute("""
|
||||||
DELETE FROM idempotency_keys
|
DELETE FROM idempotency_keys
|
||||||
WHERE (user_id, method, path, key) IN (
|
WHERE (user_id, method, path, key) IN (
|
||||||
|
|||||||
+3
-3
@@ -2,8 +2,8 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from . import cursor, security
|
from . import cursor, security
|
||||||
from .errors import bad_request
|
|
||||||
from .sessions import fmt_ts
|
from .sessions import fmt_ts
|
||||||
|
from .errors import bad_request, not_found
|
||||||
|
|
||||||
|
|
||||||
def username_exists(conn, username):
|
def username_exists(conn, username):
|
||||||
@@ -90,14 +90,14 @@ def insert_message(conn, chat_id, sender_id, text, attachment_ids=None):
|
|||||||
"""Создаёт сообщение и связывает вложения в одной транзакции."""
|
"""Создаёт сообщение и связывает вложения в одной транзакции."""
|
||||||
attachment_ids = attachment_ids or []
|
attachment_ids = attachment_ids or []
|
||||||
if attachment_ids:
|
if attachment_ids:
|
||||||
# Все вложения должны принадлежать этому чату и быть ready.
|
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""SELECT id, status FROM attachments
|
"""SELECT id, status FROM attachments
|
||||||
WHERE id = ANY(%s) AND chat_id = %s""",
|
WHERE id = ANY(%s) AND chat_id = %s""",
|
||||||
(attachment_ids, chat_id)).fetchall()
|
(attachment_ids, chat_id)).fetchall()
|
||||||
by_id = {r["id"]: r for r in rows}
|
by_id = {r["id"]: r for r in rows}
|
||||||
if len(by_id) != len(attachment_ids):
|
if len(by_id) != len(attachment_ids):
|
||||||
raise bad_request("Неизвестное вложение")
|
# Чужое или неизвестное вложение — 404 (не раскрывать существование).
|
||||||
|
raise not_found()
|
||||||
for att_id in attachment_ids:
|
for att_id in attachment_ids:
|
||||||
if by_id[att_id]["status"] == "failed":
|
if by_id[att_id]["status"] == "failed":
|
||||||
raise bad_request("Нельзя прикрепить failed-вложение")
|
raise bad_request("Нельзя прикрепить failed-вложение")
|
||||||
|
|||||||
@@ -47,7 +47,11 @@ def _rid(request):
|
|||||||
|
|
||||||
def error_response(request, status, code, message, headers=None):
|
def error_response(request, status, code, message, headers=None):
|
||||||
rid = _rid(request)
|
rid = _rid(request)
|
||||||
out = {"X-Request-Id": rid, "Cache-Control": "no-store"}
|
out = {
|
||||||
|
"X-Request-Id": rid,
|
||||||
|
"X-Instance-Id": INSTANCE_ID,
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
}
|
||||||
out.update(headers or {})
|
out.update(headers or {})
|
||||||
return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out)
|
return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out)
|
||||||
|
|
||||||
@@ -131,8 +135,14 @@ def live():
|
|||||||
|
|
||||||
@app.get("/health/ready")
|
@app.get("/health/ready")
|
||||||
def ready():
|
def ready():
|
||||||
db.ping()
|
try:
|
||||||
s3.ping()
|
db.ping()
|
||||||
|
except Exception:
|
||||||
|
raise ApiError(503, "unavailable", "PostgreSQL недоступен")
|
||||||
|
try:
|
||||||
|
s3.ping()
|
||||||
|
except Exception:
|
||||||
|
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Негативные сценарии вложений. Запускается против запущенного стенда."""
|
"""Негативные сценарии вложений. Запускается против запущенного стенда."""
|
||||||
|
import struct
|
||||||
import sys
|
import sys
|
||||||
import uuid
|
import uuid
|
||||||
|
import zlib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
@@ -13,6 +15,17 @@ from client import Client, Failure, arguments, check, run # noqa: E402
|
|||||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||||
|
|
||||||
|
|
||||||
|
def make_broken_png():
|
||||||
|
"""PNG с корректными CRC чанков, но битым потоком IDAT."""
|
||||||
|
def chunk(t, d):
|
||||||
|
c = t + d
|
||||||
|
return struct.pack(">I", len(d)) + c + struct.pack(">I", zlib.crc32(c) & 0xFFFFFFFF)
|
||||||
|
ihdr = struct.pack(">IIBBBBB", 64, 64, 8, 2, 0, 0, 0)
|
||||||
|
# Валидный zlib-заголовок + мусор: decompress() упадёт.
|
||||||
|
bad_idat = b"\x78\x9c" + b"\xff" * 100
|
||||||
|
return PNG_MAGIC + chunk(b"IHDR", ihdr) + chunk(b"IDAT", bad_idat) + chunk(b"IEND", b"")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
args = arguments("Lab4 attachment negative tests")
|
args = arguments("Lab4 attachment negative tests")
|
||||||
c = Client(args.base_url, args.ca_file)
|
c = Client(args.base_url, args.ca_file)
|
||||||
@@ -23,42 +36,49 @@ def main():
|
|||||||
base = "/api/v1/chats/%s/attachments" % chat["id"]
|
base = "/api/v1/chats/%s/attachments" % chat["id"]
|
||||||
png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||||
|
|
||||||
# 1. Слишком большой файл: 10 MiB + 1 байт, Content-Length сразу отвергается.
|
# 1. Слишком большой файл.
|
||||||
big = PNG_MAGIC + b"\x00" * (10485760)
|
big = PNG_MAGIC + b"\x00" * 10485760
|
||||||
r = c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big,
|
c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big,
|
||||||
headers={"Content-Type": "image/png"})
|
headers={"Content-Type": "image/png"})
|
||||||
check(r["status"] == 413, "oversize not rejected")
|
|
||||||
|
|
||||||
# 2. Подмена MIME: объявляем image/png, а байты не PNG.
|
# 2. Подмена MIME.
|
||||||
r = c.call("POST", base + "?filename=x.png", 415, actor=alice,
|
c.call("POST", base + "?filename=x.png", 415, actor=alice,
|
||||||
raw=b"not an image at all",
|
raw=b"not an image at all", headers={"Content-Type": "image/png"})
|
||||||
headers={"Content-Type": "image/png"})
|
|
||||||
check(r["status"] == 415, "mime mismatch not rejected")
|
|
||||||
|
|
||||||
# 3. Повреждённый PNG: валидный заголовок, битая структура.
|
# 3. Повреждённый PNG (валидный заголовок, битая структура).
|
||||||
broken = png_fixture[:20] + b"\x00" * 32 + png_fixture[52:]
|
broken = png_fixture[:20] + b"\x00" * 32 + png_fixture[52:]
|
||||||
c.call("POST", base + "?filename=broken.png", 415, actor=alice, raw=broken,
|
c.call("POST", base + "?filename=broken.png", 415, actor=alice, raw=broken,
|
||||||
headers={"Content-Type": "image/png"})
|
headers={"Content-Type": "image/png"})
|
||||||
|
|
||||||
# 4. Опасное имя файла. URL-кодируем: NUL, /, \ в URL напрямую запрещены
|
# 3b. PNG с корректными CRC, но битым IDAT — ловится только load().
|
||||||
# клиентом (http.client), но после декодирования сервер обязан отклонить.
|
c.call("POST", base + "?filename=broken-idat.png", 415, actor=alice,
|
||||||
for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.png"):
|
raw=make_broken_png(), headers={"Content-Type": "image/png"})
|
||||||
|
|
||||||
|
# 4. Опасные имена: path traversal, \, NUL, DEL 0x7F, control 0x01.
|
||||||
|
for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.png",
|
||||||
|
"a\x7fb.png", "a\x01b.png"):
|
||||||
c.call("POST", base + "?filename=" + quote(bad, safe=""), 400, actor=alice,
|
c.call("POST", base + "?filename=" + quote(bad, safe=""), 400, actor=alice,
|
||||||
raw=png_fixture, headers={"Content-Type": "image/png"})
|
raw=png_fixture, headers={"Content-Type": "image/png"})
|
||||||
|
|
||||||
# 5. Чужой чат: eve не участник — 404 до чтения тела.
|
# 5. Чужой чат — 404 до чтения тела.
|
||||||
c.call("POST", base + "?filename=sample.png", 404, actor=eve,
|
c.call("POST", base + "?filename=sample.png", 404, actor=eve,
|
||||||
raw=png_fixture, headers={"Content-Type": "image/png"})
|
raw=png_fixture, headers={"Content-Type": "image/png"})
|
||||||
|
|
||||||
# 6. Сослаться на чужое вложение в сообщении.
|
# 6. Сослаться на чужое вложение — 404 (не 400).
|
||||||
foreign = c.call("POST", "/api/v1/chats/%s/attachments?filename=s.png" % other_chat["id"],
|
foreign = c.call("POST", "/api/v1/chats/%s/attachments?filename=s.png" % other_chat["id"],
|
||||||
201, actor=bob, raw=png_fixture,
|
201, actor=bob, raw=png_fixture,
|
||||||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||||
actor=alice,
|
actor=alice,
|
||||||
body={"text": "hi", "attachment_ids": [foreign["id"]]},
|
body={"text": "hi", "attachment_ids": [foreign["id"]]},
|
||||||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||||
|
|
||||||
|
# 6b. Случайный UUID вложения — тоже 404.
|
||||||
|
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "hi", "attachment_ids": [str(uuid.uuid4())]},
|
||||||
|
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||||
|
|
||||||
# 7. Чтение чужого attachment_id — 404 на metadata и bytes.
|
# 7. Чтение чужого attachment_id — 404 на metadata и bytes.
|
||||||
c.call("GET", "/api/v1/attachments/" + foreign["id"], 404, actor=eve)
|
c.call("GET", "/api/v1/attachments/" + foreign["id"], 404, actor=eve)
|
||||||
c.call("GET", "/api/v1/attachments/" + foreign["id"] + "/content", 404, actor=eve)
|
c.call("GET", "/api/v1/attachments/" + foreign["id"] + "/content", 404, actor=eve)
|
||||||
@@ -68,7 +88,22 @@ def main():
|
|||||||
c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice)
|
c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice)
|
||||||
c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice)
|
c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice)
|
||||||
|
|
||||||
print("PASS: 8 negative attachment scenarios")
|
# 9. Идемпотентность: {"text":"x"} и {"text":"x","attachment_ids":[]} равны.
|
||||||
|
key = uuid.uuid4().hex
|
||||||
|
m1 = c.message(alice, chat, "idem-normalize", key=key)["json"]
|
||||||
|
m2 = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "idem-normalize", "attachment_ids": []},
|
||||||
|
headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||||
|
check(m1["id"] == m2["id"], "idempotency: attachment_ids=[] must equal absent")
|
||||||
|
|
||||||
|
# 10. Idempotency-Key с пробелом — 400.
|
||||||
|
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||||||
|
actor=alice,
|
||||||
|
body={"text": "x"},
|
||||||
|
headers={"Idempotency-Key": "contains space"})
|
||||||
|
|
||||||
|
print("PASS: 10 negative attachment scenarios")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user