Serve attachment upload, metadata and download through the API

Add the adapters behind the attachments ports: PostgreSQL for the
pending and ready rows, with a foreign key violation on the chat member
turned into 404; Pillow that opens only PNG and JPEG, refuses a type
that differs from Content-Type, checks the pixel count from the header
before any decoding, verifies PNG chunks and decodes JPEG at 1/8 scale
in a worker thread under a semaphore; and S3 on aiobotocore with path
style, SigV4, short timeouts and checksums only when required. botocore
sends Expect: 100-continue for streamed bodies and RustFS behind the
Docker port proxy never answers it, so the PUT hung until the read
timeout; the handler that adds the header is unregistered.

The HTTP layer streams the raw body into the use case, returns the
contract Attachment and streams the original back with its content
type and length and no redirect. The request pipeline takes a body
limit per route, so uploads may carry 10 MiB while JSON stays at 1 MiB.
main.py wires the zone and answers its membership port from the
messaging chat directory.

Tests run the API with an in-memory object store: download by another
member, 404 for strangers, the exact 10 MiB limit and one byte over it
with Content-Length and chunked, 40 MP and above, spoofed and truncated
images, unsupported types, dangerous names, the variant, a failing
store and a lost object.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 20:44:32 +03:00
co-authored by Claude Opus 5.5
parent 76c9673ab3
commit 00826a40d3
21 changed files with 1334 additions and 15 deletions
+20
View File
@@ -0,0 +1,20 @@
from pydantic import Field, SecretStr
from messenger.shared.config import Settings
UPLOAD_BYTES_MAX = 10_485_760
IMAGE_PIXELS_MAX = 40_000_000
class AttachmentsSettings(Settings):
s3_endpoint: str = "http://s3:9000"
s3_region: str = "us-east-1"
s3_bucket: str = Field(default="messenger-attachments", min_length=3)
s3_access_key_id: SecretStr = Field(min_length=3)
s3_secret_access_key: SecretStr = Field(min_length=8)
s3_connect_timeout_seconds: float = Field(default=1.0, gt=0, le=30)
s3_read_timeout_seconds: float = Field(default=2.0, gt=0, le=60)
s3_max_attempts: int = Field(default=2, ge=1, le=5)
max_upload_bytes: int = Field(default=UPLOAD_BYTES_MAX, ge=1, le=UPLOAD_BYTES_MAX)
max_image_pixels: int = Field(default=IMAGE_PIXELS_MAX, ge=1, le=IMAGE_PIXELS_MAX)
image_check_concurrency: int = Field(default=2, ge=1, le=16)
@@ -0,0 +1,16 @@
from messenger.attachments.domain.errors import (
AttachmentNotFound,
ChatNotFound,
InvalidFilename,
PayloadTooLarge,
UnsupportedImage,
)
from messenger.shared.domain.errors import DomainError
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
InvalidFilename: ("invalid_request", 400),
ChatNotFound: ("not_found", 404),
AttachmentNotFound: ("not_found", 404),
PayloadTooLarge: ("payload_too_large", 413),
UnsupportedImage: ("unsupported_media_type", 415),
}
@@ -0,0 +1,66 @@
import re
from typing import Annotated, Literal
from uuid import UUID
from dishka.integrations.fastapi import FromDishka, inject
from fastapi import APIRouter, Query, Request, status
from fastapi.responses import StreamingResponse
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import UploadAttachment
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
from messenger.attachments.entrypoints.schemas import AttachmentOut
from messenger.shared.entrypoints.actor import Actor
UPLOAD_PATH = re.compile(r"/api/v1/chats/[^/]+/attachments/?")
CONTENT_HEADERS = {"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"}
uploads_router = APIRouter(prefix="/api/v1/chats/{chat_id}/attachments", tags=["attachments"])
attachments_router = APIRouter(prefix="/api/v1/attachments", tags=["attachments"])
@uploads_router.post("", status_code=status.HTTP_201_CREATED)
@inject
async def upload_attachment(
chat_id: UUID,
actor: Actor,
request: Request,
bus: FromDishka[AttachmentsCommandBus],
filename: Annotated[str | None, Query()] = None,
) -> AttachmentOut:
attachment = await bus.execute(
UploadAttachment(
owner_id=actor,
chat_id=chat_id,
filename=filename,
content_type=request.headers.get("content-type"),
body=request.stream(),
)
)
return AttachmentOut.of(attachment)
@attachments_router.get("/{attachment_id}")
@inject
async def read_attachment(
attachment_id: UUID,
actor: Actor,
query: FromDishka[GetAttachment],
) -> AttachmentOut:
return AttachmentOut.of(await query(attachment_id, actor))
@attachments_router.get("/{attachment_id}/content")
@inject
async def download_attachment(
attachment_id: UUID,
actor: Actor,
query: FromDishka[OpenAttachment],
_variant: Annotated[Literal["original"], Query(alias="variant")] = "original",
) -> StreamingResponse:
attachment, content = await query(attachment_id, actor)
return StreamingResponse(
content.chunks,
media_type=attachment.content_type,
headers={**CONTENT_HEADERS, "Content-Length": str(content.size)},
)
@@ -0,0 +1,91 @@
from collections.abc import AsyncIterator
from dishka import Provider, Scope, provide
from messenger.attachments.application.bus import AttachmentsCommandBus
from messenger.attachments.application.commands import UploadAttachment
from messenger.attachments.application.handlers import UploadAttachmentHandler
from messenger.attachments.application.ports import (
AttachmentDirectory,
AttachmentsUnitOfWork,
ChatMembership,
ImageInspector,
ObjectStorage,
)
from messenger.attachments.application.queries import GetAttachment, OpenAttachment
from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.infrastructure.images import PillowImageInspector
from messenger.attachments.infrastructure.postgres import (
PostgresAttachmentDirectory,
PostgresAttachmentsUnitOfWork,
)
from messenger.attachments.infrastructure.s3 import S3ObjectStorage, s3_client
from messenger.shared.application.commands import Command
from messenger.shared.application.messagebus import CommandHandler
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
from messenger.shared.infrastructure.postgres import Database
class AttachmentsProvider(Provider):
def __init__(self, settings: AttachmentsSettings) -> None:
super().__init__()
self._settings = settings
@provide(scope=Scope.APP)
def settings(self) -> AttachmentsSettings:
return self._settings
@provide(scope=Scope.APP)
async def storage(self, settings: AttachmentsSettings) -> AsyncIterator[ObjectStorage]:
async with s3_client(
endpoint=settings.s3_endpoint,
region=settings.s3_region,
access_key_id=settings.s3_access_key_id.get_secret_value(),
secret_access_key=settings.s3_secret_access_key.get_secret_value(),
connect_timeout=settings.s3_connect_timeout_seconds,
read_timeout=settings.s3_read_timeout_seconds,
max_attempts=settings.s3_max_attempts,
) as client:
yield S3ObjectStorage(client, settings.s3_bucket)
@provide(scope=Scope.APP)
def images(self, settings: AttachmentsSettings) -> ImageInspector:
return PillowImageInspector(settings.max_image_pixels, settings.image_check_concurrency)
@provide(scope=Scope.APP)
def directory(self, database: Database) -> AttachmentDirectory:
return PostgresAttachmentDirectory(database)
@provide(scope=Scope.REQUEST)
def unit_of_work(self, database: Database) -> AttachmentsUnitOfWork:
return PostgresAttachmentsUnitOfWork(database)
@provide(scope=Scope.REQUEST)
def attachment(
self, directory: AttachmentDirectory, membership: ChatMembership
) -> GetAttachment:
return GetAttachment(directory, membership)
@provide(scope=Scope.REQUEST)
def content(
self, attachment: GetAttachment, storage: ObjectStorage, logger: Logger
) -> OpenAttachment:
return OpenAttachment(attachment, storage, logger)
@provide(scope=Scope.REQUEST)
def command_bus(
self,
uow: AttachmentsUnitOfWork,
membership: ChatMembership,
images: ImageInspector,
storage: ObjectStorage,
publisher: EventPublisher,
clock: Clock,
ids: IdGenerator,
settings: AttachmentsSettings,
) -> AttachmentsCommandBus:
handler = UploadAttachmentHandler(
uow, membership, images, storage, clock=clock, ids=ids, limit=settings.max_upload_bytes
)
handlers: dict[type[Command], CommandHandler] = {UploadAttachment: handler}
return AttachmentsCommandBus(handlers, uow, publisher)
@@ -0,0 +1,20 @@
from messenger.attachments.domain.events import AttachmentStored
from messenger.shared.application.ports import Logger
LOG_FIELDS = frozenset({"attachment_id", "chat_id", "actor_id", "size_bytes"})
class AttachmentsJournal:
__slots__ = ("_logger",)
def __init__(self, logger: Logger) -> None:
self._logger = logger
async def on_attachment_stored(self, event: AttachmentStored) -> None:
self._logger.info(
"audit.attachment_stored",
attachment_id=str(event.attachment_id),
chat_id=str(event.chat_id),
actor_id=str(event.owner_id),
size_bytes=event.size_bytes,
)
@@ -0,0 +1,36 @@
from datetime import datetime
from typing import Literal
from uuid import UUID
from pydantic import BaseModel
from messenger.attachments.domain.models import Attachment
class AttachmentOut(BaseModel):
id: UUID
chat_id: UUID
owner_id: UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: Literal["ready"] = "ready"
variants: tuple[()] = ()
error_code: None = None
created_at: datetime
updated_at: datetime
@classmethod
def of(cls, attachment: Attachment) -> AttachmentOut:
return cls(
id=attachment.id,
chat_id=attachment.chat_id,
owner_id=attachment.owner_id,
filename=attachment.filename.value,
content_type=attachment.content_type,
size_bytes=attachment.size_bytes,
sha256=attachment.sha256,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
)
@@ -0,0 +1,49 @@
import asyncio
import warnings
from io import BytesIO
from PIL import Image
from messenger.attachments.domain.errors import PayloadTooLarge, UnsupportedImage
from messenger.attachments.domain.values import ImageInfo, ImageKind
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
JPEG_SCALE = 8
class PillowImageInspector:
__slots__ = ("_max_pixels", "_slots")
def __init__(self, max_pixels: int, concurrency: int) -> None:
self._max_pixels = max_pixels
self._slots = asyncio.Semaphore(concurrency)
warnings.simplefilter("error", Image.DecompressionBombWarning)
async def inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
async with self._slots:
return await asyncio.to_thread(self._inspect, data, declared)
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
try:
image = Image.open(BytesIO(data), formats=tuple(KINDS))
except BOMBS as error:
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
except Exception as error:
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
with image:
kind = KINDS[str(image.format)]
width, height = image.size
if kind is not declared:
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
if width * height > self._max_pixels:
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
try:
if kind is ImageKind.JPEG:
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
image.load()
else:
image.verify()
except Exception as error:
raise UnsupportedImage("изображение повреждено или обрезано") from error
return ImageInfo(kind, width, height)
@@ -0,0 +1,98 @@
from uuid import UUID
from asyncpg import ForeignKeyViolationError, Record
from messenger.attachments.domain.errors import ChatNotFound
from messenger.attachments.domain.models import Attachment, AttachmentStatus
from messenger.attachments.domain.values import Filename, ImageInfo, ImageKind
from messenger.shared.infrastructure.postgres import (
Connection,
Database,
EventSource,
PostgresUnitOfWork,
)
INSERT = """
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
width, height, object_key, status, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
"""
MARK = "UPDATE attachments SET status = $2, updated_at = $3 WHERE id = $1 AND status = 'pending'"
READY = """
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height,
object_key, status, created_at, updated_at
FROM attachments
WHERE id = $1 AND status = 'ready'
"""
def attachment_of(row: Record) -> Attachment:
return Attachment(
id=row["id"],
chat_id=row["chat_id"],
owner_id=row["owner_id"],
filename=Filename(row["filename"]),
image=ImageInfo(ImageKind(row["content_type"]), row["width"], row["height"]),
size_bytes=row["size_bytes"],
sha256=row["sha256"],
object_key=row["object_key"],
status=AttachmentStatus(row["status"]),
created_at=row["created_at"],
updated_at=row["updated_at"],
)
class PostgresAttachmentRepository:
__slots__ = ("_connection", "_seen")
def __init__(self, connection: Connection, seen: list[EventSource]) -> None:
self._connection = connection
self._seen = seen
async def add(self, attachment: Attachment) -> None:
try:
await self._connection.execute(
INSERT,
attachment.id,
attachment.chat_id,
attachment.owner_id,
attachment.filename.value,
attachment.content_type,
attachment.size_bytes,
attachment.sha256,
attachment.image.width,
attachment.image.height,
attachment.object_key,
attachment.status.value,
attachment.created_at,
attachment.updated_at,
)
except ForeignKeyViolationError as error:
raise ChatNotFound("чат не найден") from error
self._seen.append(attachment)
async def save(self, attachment: Attachment) -> None:
await self._connection.execute(
MARK, attachment.id, attachment.status.value, attachment.updated_at
)
self._seen.append(attachment)
class PostgresAttachmentsUnitOfWork(PostgresUnitOfWork):
__slots__ = ()
@property
def attachments(self) -> PostgresAttachmentRepository:
return PostgresAttachmentRepository(self.connection, self.seen)
class PostgresAttachmentDirectory:
__slots__ = ("_database",)
def __init__(self, database: Database) -> None:
self._database = database
async def ready(self, attachment_id: UUID) -> Attachment | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(READY, attachment_id)
return None if row is None else attachment_of(row)
@@ -0,0 +1,89 @@
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
from aiobotocore.session import get_session
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from botocore.handlers import add_expect_header
from messenger.attachments.application.errors import ObjectMissingError
from messenger.attachments.application.ports import ObjectContent
from messenger.shared.application.errors import Unavailable
CHUNK_BYTES = 64 * 1024
MISSING = frozenset({"NoSuchKey", "404", "NotFound"})
FAILURES = (BotoCoreError, ClientError, OSError, TimeoutError)
def missing(error: Exception) -> bool:
return isinstance(error, ClientError) and error.response.get("Error", {}).get("Code") in MISSING
@asynccontextmanager
async def s3_client(
*,
endpoint: str,
region: str,
access_key_id: str,
secret_access_key: str,
connect_timeout: float,
read_timeout: float,
max_attempts: int,
) -> AsyncIterator[Any]:
config = Config(
region_name=region,
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=connect_timeout,
read_timeout=read_timeout,
retries={"mode": "standard", "max_attempts": max_attempts},
max_pool_connections=32,
request_checksum_calculation="when_required",
response_checksum_validation="when_required",
)
async with get_session().create_client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key,
config=config,
) as client:
client.meta.events.unregister("before-call.s3", add_expect_header)
yield client
class S3ObjectStorage:
__slots__ = ("_bucket", "_client")
def __init__(self, client: Any, bucket: str) -> None:
self._client = client
self._bucket = bucket
async def put(self, key: str, data: bytes, content_type: str) -> None:
try:
await self._client.put_object(
Bucket=self._bucket, Key=key, Body=data, ContentType=content_type
)
except FAILURES as error:
raise Unavailable("S3 недоступно") from error
async def open(self, key: str) -> ObjectContent:
try:
response = await self._client.get_object(Bucket=self._bucket, Key=key)
except FAILURES as error:
if missing(error):
raise ObjectMissingError(key) from error
raise Unavailable("S3 недоступно") from error
return ObjectContent(size=response["ContentLength"], chunks=self._chunks(response["Body"]))
async def delete(self, key: str) -> None:
try:
await self._client.delete_object(Bucket=self._bucket, Key=key)
except FAILURES as error:
raise Unavailable("S3 недоступно") from error
async def _chunks(self, body: Any) -> AsyncIterator[bytes]:
async with body as stream:
async for chunk in stream.iter_chunks(CHUNK_BYTES):
yield chunk
+45 -4
View File
@@ -1,10 +1,19 @@
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from uuid import UUID
from dishka import make_async_container
from dishka import Provider, Scope, make_async_container, provide
from dishka.integrations.fastapi import FastapiProvider, setup_dishka
from fastapi import FastAPI
from messenger.attachments.application.ports import ChatMembership
from messenger.attachments.config import AttachmentsSettings
from messenger.attachments.domain.events import AttachmentStored
from messenger.attachments.entrypoints.errors import ERROR_CODES as ATTACHMENT_ERRORS
from messenger.attachments.entrypoints.http import UPLOAD_PATH, attachments_router, uploads_router
from messenger.attachments.entrypoints.ioc import AttachmentsProvider
from messenger.attachments.entrypoints.journal import LOG_FIELDS as ATTACHMENT_FIELDS
from messenger.attachments.entrypoints.journal import AttachmentsJournal
from messenger.identity.config import IdentitySettings
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
from messenger.identity.entrypoints.authentication import challenge_for, guard
@@ -14,6 +23,7 @@ from messenger.identity.entrypoints.http import sessions_router
from messenger.identity.entrypoints.ioc import IdentityProvider
from messenger.identity.entrypoints.journal import LOG_FIELDS as IDENTITY_FIELDS
from messenger.identity.entrypoints.journal import IdentityJournal
from messenger.messaging.application.ports import ChatDirectory
from messenger.messaging.config import MessagingSettings
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.entrypoints.errors import ERROR_CODES as MESSAGING_ERRORS
@@ -32,8 +42,26 @@ from messenger.shared.infrastructure.logging import PLATFORM_FIELDS, StructlogLo
TRANSPORT_FIELDS = frozenset({"dropped_total", "queue", "instance"})
LOG_FIELDS = PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS
ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS}
LOG_FIELDS = (
PLATFORM_FIELDS | TRANSPORT_FIELDS | IDENTITY_FIELDS | MESSAGING_FIELDS | ATTACHMENT_FIELDS
)
ERROR_CODES = {**IDENTITY_ERRORS, **MESSAGING_ERRORS, **ATTACHMENT_ERRORS}
class MessagingMembership:
__slots__ = ("_chats",)
def __init__(self, chats: ChatDirectory) -> None:
self._chats = chats
async def is_member(self, chat_id: UUID, user_id: UUID) -> bool:
return await self._chats.chat_for_member(chat_id, user_id) is not None
class ZoneLinks(Provider):
@provide(scope=Scope.APP)
def membership(self, chats: ChatDirectory) -> ChatMembership:
return MessagingMembership(chats)
def wire_events(bus: EventBus, logger: Logger) -> None:
@@ -46,23 +74,33 @@ def wire_events(bus: EventBus, logger: Logger) -> None:
bus.subscribe(ChatCreated, messaging.on_chat_created)
bus.subscribe(MessagePosted, messaging.on_message_posted)
attachments = AttachmentsJournal(logger)
bus.subscribe(AttachmentStored, attachments.on_attachment_stored)
def create_app(
*,
platform: PlatformSettings | None = None,
transport: TransportSettings | None = None,
identity: IdentitySettings | None = None,
messaging: MessagingSettings | None = None,
attachments: AttachmentsSettings | None = None,
overrides: Sequence[Provider] = (),
) -> FastAPI:
platform = platform or PlatformSettings()
transport = transport or TransportSettings()
identity = identity or IdentitySettings()
messaging = messaging or MessagingSettings()
attachments = attachments or AttachmentsSettings()
logger = StructlogLogger(level=platform.log_level, allowed_fields=LOG_FIELDS)
container = make_async_container(
PlatformProvider(platform, logger),
IdentityProvider(identity),
MessagingProvider(messaging),
AttachmentsProvider(attachments),
ZoneLinks(),
FastapiProvider(),
*overrides,
)
@asynccontextmanager
@@ -93,6 +131,7 @@ def create_app(
timeout=transport.request_timeout_seconds,
guard=guard,
instance=platform.instance_id,
limits=((UPLOAD_PATH, attachments.max_upload_bytes),),
)
errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id)
app.include_router(health.router)
@@ -100,5 +139,7 @@ def create_app(
app.include_router(sessions_router)
app.include_router(chats_router)
app.include_router(messages_router)
app.include_router(uploads_router)
app.include_router(attachments_router)
setup_dishka(container, app)
return app
+12 -2
View File
@@ -1,4 +1,5 @@
import asyncio
import re
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
@@ -22,6 +23,7 @@ class Rejection:
type Guard = Callable[[Scope], Awaitable[Rejection | None]]
type BodyLimits = tuple[tuple[re.Pattern[str], int], ...]
HEADER_BYTES = REQUEST_ID_HEADER.lower().encode()
INSTANCE_BYTES = INSTANCE_ID_HEADER.lower().encode()
@@ -56,7 +58,7 @@ async def send_error(
class RequestPipeline:
__slots__ = ("_app", "_guard", "_instance", "_logger", "_max_bytes", "_timeout")
__slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout")
def __init__(
self,
@@ -66,10 +68,12 @@ class RequestPipeline:
timeout: float,
guard: Guard,
instance: str,
limits: BodyLimits = (),
) -> None:
self._app = app
self._logger = logger
self._max_bytes = max_bytes
self._limits = limits
self._timeout = timeout
self._guard = guard
self._instance = instance.encode()
@@ -103,7 +107,7 @@ class RequestPipeline:
await send(message)
declared = header(scope, b"content-length")
if declared.isdigit() and int(declared) > self._max_bytes:
if declared.isdigit() and int(declared) > self._limit(scope["path"]):
await send_error(wrapped_send, 413, "payload_too_large", request_id)
self._log(scope, status_holder[0], request_id, started)
return
@@ -150,6 +154,12 @@ class RequestPipeline:
)
self._log(scope, status_holder[0], request_id, started)
def _limit(self, path: str) -> int:
for pattern, limit in self._limits:
if pattern.fullmatch(path):
return limit
return self._max_bytes
def _route(self, scope: Scope) -> str:
route = scope.get("route")
return getattr(route, "path", scope["path"])