fix: address attachments verify findings

- keep one upload body in memory: BytesIO + getvalue() without copy,
  fixed glibc mmap threshold in the image (no realloc copy on growth)
- stop PNG inflate at expected size + 1 byte
- reject filename that is not valid UTF-8 after percent-decoding (400)
- failure stand: env limit variables do not change attachment limits;
  history with attachment_ids while S3 is stopped
- drop dead constants; restate "old image on new schema" scenario

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 02:16:49 +03:00
co-authored by Claude Opus 5.5
parent 8dc925e8ca
commit dba40bc325
23 changed files with 398 additions and 47 deletions
+18 -10
View File
@@ -1,4 +1,5 @@
import hashlib
import io
import time
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, AsyncExitStack
@@ -190,22 +191,29 @@ class AttachmentService:
body: AsyncIterator[bytes],
log: AbstractLogger,
) -> bytes:
"""Тело целиком; больше лимита — 413 сразу, без дочитывания."""
buffer = bytearray()
"""Тело целиком; больше лимита — 413 сразу, без дочитывания.
Блоки копятся в `BytesIO`, а `getvalue()` отдаёт `bytes` над его
же буфером, без копии: в памяти одно тело и блок чтения (спек
«Лимит размера до чтения тела»). Именно `bytes`, а не
`bytearray`: botocore оборачивает тело `PutObject` в `BytesIO`, и
`bytes` он не копирует, а `bytearray` копирует. Рост буфера без
копии в образе даёт `MALLOC_MMAP_THRESHOLD_` (`Dockerfile`;
design, решение 6).
"""
buffer = io.BytesIO()
size = 0
try:
async for chunk in body:
if len(buffer) + len(chunk) > ATTACHMENT_MAX_BYTES:
log.info(
"Rejected attachment",
reason="size",
size=len(buffer) + len(chunk),
)
size += len(chunk)
if size > ATTACHMENT_MAX_BYTES:
log.info("Rejected attachment", reason="size", size=size)
raise exceptions.PayloadTooLarge
buffer += chunk
buffer.write(chunk)
except exceptions.UploadInterrupted:
log.info("Rejected attachment", reason="interrupted")
raise
return bytes(buffer)
return buffer.getvalue()
async def get_attachment(
self,