From 54099e1da3b9eddc6746655d848c2083b6680d38 Mon Sep 17 00:00:00 2001 From: Artyom Date: Fri, 30 Oct 2026 08:53:39 +0300 Subject: [PATCH] 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) Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27 --- src/messenger/main.py | 1 + src/messenger/shared/entrypoints/config.py | 1 + src/messenger/shared/entrypoints/pipeline.py | 51 +++++++++++++++++--- student-tests/api/test_attachments.py | 14 +++++- student-tests/api/test_timeout.py | 51 +++++++++++++++++++- student-tests/fakes.py | 9 ++-- 6 files changed, 115 insertions(+), 12 deletions(-) diff --git a/src/messenger/main.py b/src/messenger/main.py index d2c00e9f..f19c8b65 100644 --- a/src/messenger/main.py +++ b/src/messenger/main.py @@ -137,6 +137,7 @@ def create_app( guard=guard, instance=platform.instance_id, limits=((UPLOAD_PATH, attachments.max_upload_bytes),), + min_rate=transport.min_transfer_rate_bytes, ) errors.install(app, logger, ERROR_CODES, challenge_for, platform.instance_id) app.include_router(health.router) diff --git a/src/messenger/shared/entrypoints/config.py b/src/messenger/shared/entrypoints/config.py index 84e4c1d1..05f3cb40 100644 --- a/src/messenger/shared/entrypoints/config.py +++ b/src/messenger/shared/entrypoints/config.py @@ -7,3 +7,4 @@ class TransportSettings(Settings): docs: bool = False max_body_bytes: int = Field(default=1_048_576, ge=4_096) request_timeout_seconds: float = Field(default=8.0, gt=0, le=300) + min_transfer_rate_bytes: int = Field(default=131_072, ge=1_024) diff --git a/src/messenger/shared/entrypoints/pipeline.py b/src/messenger/shared/entrypoints/pipeline.py index 10bee132..17714272 100644 --- a/src/messenger/shared/entrypoints/pipeline.py +++ b/src/messenger/shared/entrypoints/pipeline.py @@ -58,8 +58,44 @@ async def send_error( await send({"type": "http.response.body", "body": body}) +class Pace: + __slots__ = ("_deadline", "_moved", "_opened", "_rate", "_timeout") + + def __init__(self, deadline: asyncio.Timeout, timeout: float, rate: float) -> None: + self._deadline = deadline + self._timeout = timeout + self._rate = rate + self._opened = asyncio.get_running_loop().time() + self._moved = 0 + + def around(self, receive: Receive, send: Send) -> tuple[Receive, Send]: + async def paced_receive() -> Message: + return self._count(await receive()) + + async def paced_send(message: Message) -> None: + await send(self._count(message)) + + return paced_receive, paced_send + + def _count(self, message: Message) -> Message: + if size := len(message.get("body", b"")): + self._moved += size + moved = min(asyncio.get_running_loop().time(), self._opened + self._moved / self._rate) + self._deadline.reschedule(moved + self._timeout) + return message + + class RequestPipeline: - __slots__ = ("_app", "_guard", "_instance", "_limits", "_logger", "_max_bytes", "_timeout") + __slots__ = ( + "_app", + "_guard", + "_instance", + "_limits", + "_logger", + "_max_bytes", + "_min_rate", + "_timeout", + ) def __init__( self, @@ -70,12 +106,14 @@ class RequestPipeline: guard: Guard, instance: str, limits: BodyLimits = (), + min_rate: float = 131_072, ) -> None: self._app = app self._logger = logger self._max_bytes = max_bytes self._limits = limits self._timeout = timeout + self._min_rate = min_rate self._guard = guard self._instance = instance.encode() @@ -86,9 +124,7 @@ class RequestPipeline: incoming = header(scope, HEADER_BYTES) request_id = incoming[:MAX_REQUEST_ID] if incoming else uuid4().hex - state = scope.setdefault("state", {}) - state["request_id"] = request_id - state["actor"] = None + scope.setdefault("state", {}).update(request_id=request_id, actor=None) started = time.perf_counter() status_holder = [500] answered = [False] @@ -119,10 +155,11 @@ class RequestPipeline: rejection: Rejection | None = None try: - async with asyncio.timeout(self._timeout): - rejection = self._oversized(scope, limit) or await self._guard(scope) + async with asyncio.timeout(self._timeout) as deadline: + rejection = await self._guard(scope) or self._oversized(scope, limit) if rejection is None: - await self._app(scope, limited_receive, wrapped_send) + pace = Pace(deadline, self._timeout, self._min_rate) + await self._app(scope, *pace.around(limited_receive, wrapped_send)) except Unavailable as error: self._logger.warning( "dependency.unavailable", diff --git a/student-tests/api/test_attachments.py b/student-tests/api/test_attachments.py index 9f4ad41c..b29bd54e 100644 --- a/student-tests/api/test_attachments.py +++ b/student-tests/api/test_attachments.py @@ -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)) diff --git a/student-tests/api/test_timeout.py b/student-tests/api/test_timeout.py index 9118d660..7be7ab0c 100644 --- a/student-tests/api/test_timeout.py +++ b/student-tests/api/test_timeout.py @@ -4,10 +4,13 @@ from contextlib import asynccontextmanager from httpx import AsyncClient -from conftest import keyed, make_chat, register, resolve, running_app +from conftest import actor, keyed, make_chat, register, resolve, running_app, scalar +from fakes import MemoryObjectStorage +from messenger.attachments.application.ports import ObjectStorage from messenger.messaging.application import handlers from messenger.messaging.domain.events import MessagePosted from messenger.shared.application.messagebus import EventBus +from pictures import SAMPLE, png MARKER = "текст-который-не-должен-утечь-при-таймауте" @@ -95,3 +98,49 @@ async def test_healthcheck_stays_fast(client: AsyncClient) -> None: started = loop.time() assert (await client.get("/health/live")).status_code == 200 assert loop.time() - started < 1.0 + + +async def trickled(data: bytes, size: int, delay: float) -> AsyncIterator[bytes]: + for start in range(0, len(data), size): + await asyncio.sleep(delay) + yield data[start : start + size] + + +async def upload(client: AsyncClient, user: dict, chat: dict, body: AsyncIterator[bytes]): + return await client.post( + f"/api/v1/chats/{chat['id']}/attachments?filename=slow.png", + content=body, + headers={**actor(user), "Content-Type": "image/png"}, + ) + + +async def test_steady_slow_transfer_outlives_the_request_timeout() -> None: + picture = png(16, 16, size=1 << 20) + async with running_app(request_timeout_seconds=0.4, min_transfer_rate_bytes=16_384) as client: + alice, chat = await prepared(client) + loop = asyncio.get_running_loop() + started = loop.time() + uploaded = await upload(client, alice, chat, trickled(picture, 65_536, 0.1)) + assert uploaded.status_code == 201, uploaded.text + assert loop.time() - started > 1.0 + store = await resolve(client, ObjectStorage) + assert isinstance(store, MemoryObjectStorage) + store.delay = 0.1 + started = loop.time() + content = await client.get( + f"/api/v1/attachments/{uploaded.json()['id']}/content", headers=actor(alice) + ) + assert (content.status_code, content.content) == (200, picture) + assert loop.time() - started > 1.0 + + +async def test_body_slower_than_the_minimal_rate_is_cut() -> None: + async with running_app(request_timeout_seconds=0.3, min_transfer_rate_bytes=1 << 20) as client: + alice, chat = await prepared(client) + before = await scalar("SELECT count(*) FROM attachments") + loop = asyncio.get_running_loop() + started = loop.time() + response = await upload(client, alice, chat, trickled(SAMPLE, 4_096, 0.1)) + assert (response.status_code, response.json()["error"]["code"]) == (503, "unavailable") + assert loop.time() - started < 1.0 + assert await scalar("SELECT count(*) FROM attachments") == before diff --git a/student-tests/fakes.py b/student-tests/fakes.py index 12a3eaaf..2572fc8d 100644 --- a/student-tests/fakes.py +++ b/student-tests/fakes.py @@ -1,3 +1,4 @@ +import asyncio from collections.abc import AsyncIterator, Awaitable, Callable, Sequence from datetime import UTC, datetime, timedelta from typing import Any @@ -30,18 +31,20 @@ class FrozenClock: return self._current -async def pieces(data: bytes, size: int = 65_536) -> AsyncIterator[bytes]: +async def pieces(data: bytes, size: int = 65_536, delay: float = 0.0) -> AsyncIterator[bytes]: for start in range(0, len(data), size): + await asyncio.sleep(delay) yield data[start : start + size] class MemoryObjectStorage: - __slots__ = ("after_page", "after_put", "failing", "modified", "objects") + __slots__ = ("after_page", "after_put", "delay", "failing", "modified", "objects") def __init__(self) -> None: self.objects: dict[str, tuple[bytes, str]] = {} self.modified: dict[str, datetime] = {} self.failing = False + self.delay = 0.0 self.after_put: Callable[[str], Awaitable[None]] | None = None self.after_page: Callable[[], Awaitable[None]] | None = None @@ -74,7 +77,7 @@ class MemoryObjectStorage: if key not in self.objects: raise ObjectMissingError(key) data = self.objects[key][0] - return ObjectContent(size=len(data), chunks=pieces(data)) + return ObjectContent(size=len(data), chunks=pieces(data, delay=self.delay)) async def delete(self, key: str) -> None: self.objects.pop(key, None)