Check the token before the declared size and pace the request deadline

The pipeline now runs the guard first, so an anonymous upload with a too
large Content-Length gets 401 with WWW-Authenticate, as the contract
asks; the guard does not read the body, so 413 still comes before the
first body byte for an authenticated client.

The single request deadline cut slow but steady uploads and downloads:
a client slower than about 1.3 MB/s could not move 10 MiB in 8 s. Each
body chunk the application receives or sends now moves the deadline to
min(now, start + moved / MIN_TRANSFER_RATE_BYTES) + REQUEST_TIMEOUT,
128 KiB/s by default, like mod_reqtimeout with a ceiling: a steady
transfer lives as long as it moves, a stalled or crawling body is cut
after the request timeout as before, and the work after the last body
byte still gets at most the request timeout. The pipeline's own error
responses bypass the pacing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 08:53:39 +03:00
co-authored by Claude Opus 5.5
parent 96e934ed8f
commit 54099e1da3
6 changed files with 115 additions and 12 deletions
+13 -1
View File
@@ -7,7 +7,7 @@ from uuid import uuid4
import pytest
from httpx import AsyncClient, Response
from conftest import actor, make_chat, register, resolve, scalar
from conftest import actor, make_chat, register, resolve, running_app, scalar
from fakes import MemoryObjectStorage
from messenger.attachments.application.ports import ObjectStorage
from pictures import GIF, JPEG, SAMPLE, WEBP, png
@@ -124,6 +124,18 @@ async def test_access_is_checked_before_content(client: AsyncClient) -> None:
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
async def test_token_is_checked_before_the_declared_size() -> None:
async with running_app(max_upload_bytes=4096) as http:
alice, _, _, chat = await trio(http)
oversized = png(16, 16, size=8192)
anonymous = await http.post(
f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", content=oversized, headers=PNG
)
assert anonymous.status_code == 401
assert anonymous.headers["www-authenticate"] == 'Bearer realm="messenger"'
assert (await upload(http, alice, chat, oversized)).status_code == 413
async def test_exact_limit_is_accepted(client: AsyncClient) -> None:
alice, _, _, chat = await trio(client)
response = await upload(client, alice, chat, png(16, 16, size=LIMIT))