forked from mtusi2026/mtusi2026lab4
feat: add private attachments and safe reconciliation experiment
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
"""Synchronous attachment intake: bounded spool, full image validation, durable intent."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import unicodedata
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .domain import Failure, timestamp
|
||||
from .postgres import public
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
# Check dimensions before decoding. Pillow's own hard bomb threshold remains active.
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
PUBLIC_FIELDS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"status",
|
||||
"error_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
)
|
||||
|
||||
|
||||
def filename_valid(name):
|
||||
if not isinstance(name, str) or not 1 <= len(name) <= 255 or not name.strip():
|
||||
raise Failure(400, "Неверное имя файла")
|
||||
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in name):
|
||||
raise Failure(400, "Неверное имя файла")
|
||||
return name
|
||||
|
||||
|
||||
def validate_image(fileobj, declared_type):
|
||||
if declared_type not in {"image/png", "image/jpeg"}:
|
||||
raise Failure(415, "Ожидается PNG или JPEG")
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
width, height = image.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format)
|
||||
if actual != declared_type:
|
||||
raise Failure(415, "Формат изображения не соответствует MIME")
|
||||
image.verify()
|
||||
# verify() alone does not decode IDAT/JPEG scan data.
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
image.load()
|
||||
if actual == "image/jpeg":
|
||||
# libjpeg emits a warning but Pillow accepts e.g. a half scan with a
|
||||
# forged EOI. djpeg's nonzero warning exit rejects that corruption.
|
||||
fileobj.seek(0)
|
||||
try:
|
||||
decoded = subprocess.run(
|
||||
["djpeg", "-strict", "-maxmemory", "192m", "-outfile", "/dev/null"],
|
||||
stdin=fileobj,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
|
||||
if decoded.returncode:
|
||||
raise Failure(415, "Повреждённое изображение")
|
||||
fileobj.seek(0)
|
||||
return actual, width, height
|
||||
except Image.DecompressionBombError:
|
||||
raise Failure(413, "Слишком много пикселей") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise Failure(415, "Повреждённое изображение") from None
|
||||
|
||||
|
||||
def metadata_public(row):
|
||||
return {**public({k: row[k] for k in PUBLIC_FIELDS}), "variants": []}
|
||||
|
||||
|
||||
class AttachmentService:
|
||||
def __init__(self, store, storage):
|
||||
self.store = store
|
||||
self.storage = storage
|
||||
|
||||
def upload(self, actor, cid, filename, content_type, fileobj, size):
|
||||
filename_valid(filename)
|
||||
if not 1 <= size <= MAX_BYTES:
|
||||
raise Failure(413 if size > MAX_BYTES else 415, "Неверный размер изображения")
|
||||
validate_image(fileobj, content_type)
|
||||
digest = hashlib.file_digest(fileobj, "sha256").hexdigest()
|
||||
aid = str(uuid4())
|
||||
key = "original/" + aid
|
||||
now = timestamp()
|
||||
with self.store.connection() as conn:
|
||||
self.store._chat(conn, actor, cid)
|
||||
conn.execute(
|
||||
"INSERT INTO upload_intents(id,object_key,created_at) VALUES (%s,%s,%s)",
|
||||
(aid, key, now),
|
||||
)
|
||||
# Keep the intent locked throughout PUT/finalization: reconciler skips live
|
||||
# uploads even if a slow request crosses the grace boundary.
|
||||
with self.store.connection() as conn, conn.transaction():
|
||||
intent = conn.execute(
|
||||
"SELECT id FROM upload_intents WHERE id=%s FOR UPDATE", (aid,)
|
||||
).fetchone()
|
||||
if not intent:
|
||||
raise Failure(503, "Загрузка больше не активна")
|
||||
self.storage.put(key, fileobj, size, content_type)
|
||||
if os.getenv("UPLOAD_FAULT") == "after_put":
|
||||
raise Failure(503, "Учебный сбой после записи файла")
|
||||
row = conn.execute(
|
||||
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
|
||||
"status,error_code,created_at,updated_at,object_key) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,'ready',NULL,%s,%s,%s) RETURNING *",
|
||||
(aid, cid, actor, filename, content_type, size, digest, now, now, key),
|
||||
).fetchone()
|
||||
conn.execute("DELETE FROM upload_intents WHERE id=%s", (aid,))
|
||||
# Never delete S3 on an ambiguous COMMIT: the transaction may have committed.
|
||||
if os.getenv("UPLOAD_FAULT") == "after_commit":
|
||||
raise Failure(503, "Учебный сбой после фиксации")
|
||||
return metadata_public(row)
|
||||
|
||||
def metadata(self, actor, aid):
|
||||
with self.store.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
|
||||
"WHERE a.id=%s AND m.user_id=%s",
|
||||
(aid, actor),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise Failure(404, "Объект не найден")
|
||||
return metadata_public(row)
|
||||
|
||||
def content(self, actor, aid, variant="original"):
|
||||
with self.store.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
|
||||
"WHERE a.id=%s AND m.user_id=%s",
|
||||
(aid, actor),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise Failure(404, "Объект не найден")
|
||||
if row["status"] != "ready":
|
||||
raise Failure(409, "Вложение не готово")
|
||||
if variant != "original":
|
||||
raise Failure(404, "Вариант не найден")
|
||||
return self.storage.get(row["object_key"])
|
||||
Reference in New Issue
Block a user