You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/08/30 15:20:05 UTC

(tooling-trusted-releases) branch sbp updated: Buffer submitted files to disk

This is an automated email from the ASF dual-hosted git repository.

sbp pushed a commit to branch sbp
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git


The following commit(s) were added to refs/heads/sbp by this push:
     new 0ac04d11 Buffer submitted files to disk
0ac04d11 is described below

commit 0ac04d11a9fd22c95ca72e5c02f5e9b83baeedd0
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Sun Aug 30 16:19:32 2026 +0100

    Buffer submitted files to disk
---
 atr/body.py                     | 143 ++++++++++++++++++++++++++++++++++++++++
 atr/docs/resource-management.md |   2 +-
 atr/server.py                   |   2 +
 tests/unit/test_body.py         | 142 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 288 insertions(+), 1 deletion(-)

diff --git a/atr/body.py b/atr/body.py
new file mode 100644
index 00000000..2b90b5b0
--- /dev/null
+++ b/atr/body.py
@@ -0,0 +1,143 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import functools
+import shutil
+import tempfile
+from collections.abc import Generator
+from typing import IO, Any
+
+import quart.formparser as formparser
+import quart.wrappers.request as request
+import werkzeug.exceptions as exceptions
+
+import atr.config as config
+import atr.paths as paths
+
+READ_CHUNK_SIZE = 65536
+SPOOL_FREE_MINIMUM = 536870912
+SPOOL_MAX_SIZE = 1048576
+
+
+class Body(request.Body):
+    def __init__(self, expected_content_length: int | None, max_content_length: int | None) -> None:
+        super().__init__(expected_content_length, max_content_length)
+        self._spool = tempfile.SpooledTemporaryFile(max_size=SPOOL_MAX_SIZE, dir=spool_dir())
+        self._closed = False
+        self._read_offset = 0
+        self._received = 0
+        self._write_offset = 0
+
+    async def __anext__(self) -> bytes:
+        if self._must_raise is not None:
+            raise self._must_raise
+        if not self._complete.is_set():
+            await self._has_data.wait()
+        if self._must_raise is not None:
+            raise self._must_raise
+        unread = self._write_offset - self._read_offset
+        if self._complete.is_set() and (unread == 0):
+            if not self._closed:
+                self._spool.truncate(0)
+            raise StopAsyncIteration()
+        self._spool.seek(self._read_offset)
+        data = self._spool.read(min(unread, READ_CHUNK_SIZE))
+        self._read_offset += len(data)
+        if self._read_offset == self._write_offset:
+            self._has_data.clear()
+        return data
+
+    def __await__(self) -> Generator[Any, None, Any]:
+        if self._must_raise is not None:
+            raise self._must_raise
+        yield from self._complete.wait().__await__()
+        if self._must_raise is not None:
+            raise self._must_raise
+        self._spool.seek(self._read_offset)
+        return self._spool.read()
+
+    def append(self, data: bytes) -> None:
+        if (data == b"") or self._closed or (self._must_raise is not None):
+            return
+        self._received += len(data)
+        if (self._max_content_length is not None) and (self._received > self._max_content_length):
+            self._must_raise = exceptions.RequestEntityTooLarge()
+            self.set_complete()
+            return
+        new_offset = self._write_offset + len(data)
+        try:
+            if new_offset > SPOOL_MAX_SIZE:
+                disk_growth = new_offset if (self._write_offset <= SPOOL_MAX_SIZE) else len(data)
+                if shutil.disk_usage(spool_dir()).free <= (spool_floor() + disk_growth):
+                    self._must_raise = exceptions.ServiceUnavailable(
+                        "Insufficient free disk space to receive the request body."
+                    )
+                    self.set_complete()
+                    return
+            self._spool.seek(self._write_offset)
+            self._spool.write(data)
+        except OSError as error:
+            self._must_raise = error
+            self.set_complete()
+            return
+        self._write_offset = new_offset
+        self._has_data.set()
+
+    def clear(self) -> None:
+        if self._closed:
+            return
+        self._read_offset = 0
+        self._write_offset = 0
+        self._spool.seek(0)
+        self._spool.truncate()
+
+    def close(self) -> None:
+        self._closed = True
+        self._spool.close()
+
+
+class Request(request.Request):
+    body_class = Body
+    body: Body
+
+    async def close(self) -> None:
+        await super().close()
+        self.body.close()
+
+    def make_form_data_parser(self) -> formparser.FormDataParser:
+        parser = super().make_form_data_parser()
+        parser.stream_factory = part_stream_factory
+        return parser
+
+
+def part_stream_factory(
+    total_content_length: int | None,
+    content_type: str | None,
+    filename: str | None,
+    content_length: int | None = None,
+) -> IO[bytes]:
+    return tempfile.TemporaryFile(dir=spool_dir())
+
+
+@functools.cache
+def spool_dir() -> str:
+    return str(paths.get_tmp_dir())
+
+
+@functools.cache
+def spool_floor() -> int:
+    return SPOOL_FREE_MINIMUM + config.get().MAX_CONTENT_LENGTH
diff --git a/atr/docs/resource-management.md b/atr/docs/resource-management.md
index 8a7b92b6..bbc8af83 100644
--- a/atr/docs/resource-management.md
+++ b/atr/docs/resource-management.md
@@ -59,7 +59,7 @@ The SSH server, in the application process, allows, per minute, 100 connections
 
 ## Limits
 
-From [`config`](/ref/atr/config.py): `MAX_CONTENT_LENGTH` (512 MB) caps declared or buffered bodies (chunked multipart can evade it, hence a proxy cap too), `UPLOAD_BODY_TIMEOUT` (3600s), `MAX_EXTRACT_SIZE` (2 GB), `MAX_SESSION_AGE` (72 hours), and `ACCOUNT_CHECK_INTERVAL` (300s).
+From [`config`](/ref/atr/config.py): `MAX_CONTENT_LENGTH` (512 MiB) caps declared or received bodies, `UPLOAD_BODY_TIMEOUT` (3600s), `MAX_EXTRACT_SIZE` (2 GiB), `MAX_SESSION_AGE` (72 hours), and `ACCOUNT_CHECK_INTERVAL` (300s). Request bodies over 1 MiB are written to the state temporary directory, and such writes are refused with a 503 if they would leave no more than 512 MiB of disk space plus the maximum body size free. Multipart part submissions and concurrent writers can temporarily [...]
 
 As enforced, the defaults (100 a minute, 1000 an hour) apply per endpoint, keyed by web session user or client address, in process memory, and reset by restarts. Announce and vote start get five an hour, vote cast 60, and key, token, and similar endpoints ten. API wide 500 an hour and website token route limits are declared but appear to be unenforced. Sessions last 72 hours.
 
diff --git a/atr/server.py b/atr/server.py
index 7127855d..5e7a6667 100644
--- a/atr/server.py
+++ b/atr/server.py
@@ -50,6 +50,7 @@ import werkzeug.routing as routing
 import atr
 import atr.analysis as analysis
 import atr.blueprints as blueprints
+import atr.body as body
 import atr.cache as cache
 import atr.config as config
 import atr.constants as constants
@@ -157,6 +158,7 @@ def _app_create_base(app_config: type[config.AppConfig]) -> base.QuartApp:
         token_file="secrets/generated/apptoken.txt",
         basic_auth=False,
     )
+    app.request_class = body.Request
     app.jinja_environment = template.SyncEnvironment
     # ASFQuart sets secret_key from apptoken.txt, or generates a new one
     # We must preserve this because from_object will overwrite it
diff --git a/tests/unit/test_body.py b/tests/unit/test_body.py
new file mode 100644
index 00000000..c7d815b1
--- /dev/null
+++ b/tests/unit/test_body.py
@@ -0,0 +1,142 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import asyncio
+import io
+import tempfile
+import types
+
+import pytest
+import quart
+import quart.datastructures as datastructures
+import werkzeug.exceptions as exceptions
+
+import atr.body as body
+
+
+@pytest.fixture
+def state_tmp(monkeypatch, tmp_path):
+    monkeypatch.setattr(body, "spool_dir", lambda: str(tmp_path))
+    return tmp_path
+
+
+async def test_body_append_after_close(state_tmp):
+    b = body.Body(None, None)
+    b.append(b"data")
+    b.close()
+    b.append(b"more")
+
+
+async def test_body_await_retains(state_tmp):
+    b = body.Body(None, None)
+    b.append(b"alpha")
+    b.set_complete()
+    assert await b == b"alpha"
+    assert await b == b"alpha"
+
+
+async def test_body_iterate_then_await(state_tmp):
+    b = body.Body(None, None)
+    b.append(b"alpha")
+    b.append(b"beta")
+    b.set_complete()
+    chunks = [chunk async for chunk in b]
+    assert b"".join(chunks) == b"alphabeta"
+    assert await b == b""
+
+
+async def test_body_limit_known_length(state_tmp):
+    b = body.Body(20, 10)
+    with pytest.raises(exceptions.RequestEntityTooLarge):
+        await b
+
+
+async def test_body_limit_wakes_reader(state_tmp):
+    b = body.Body(None, 10)
+    b.append(b"x" * 6)
+    assert await anext(b) == b"x" * 6
+    task = asyncio.ensure_future(anext(b))
+    await asyncio.sleep(0)
+    b.append(b"x" * 5)
+    with pytest.raises(exceptions.RequestEntityTooLarge):
+        await task
+
+
+async def test_body_low_disk_refused(state_tmp, monkeypatch):
+    calls = []
+
+    def fake_disk_usage(path):
+        calls.append(path)
+        return types.SimpleNamespace(free=body.spool_floor() + body.SPOOL_MAX_SIZE)
+
+    monkeypatch.setattr(body.shutil, "disk_usage", fake_disk_usage)
+    b = body.Body(None, None)
+    b.append(b"x" * body.SPOOL_MAX_SIZE)
+    assert calls == []
+    b.append(b"x")
+    with pytest.raises(exceptions.ServiceUnavailable) as exc_info:
+        await anext(b)
+    assert "disk space" in exc_info.value.description
+
+
+async def test_body_spools_to_disk(state_tmp, monkeypatch):
+    calls = []
+    original = tempfile.TemporaryFile
+
+    def recorder(*args, **kwargs):
+        calls.append(kwargs)
+        return original(*args, **kwargs)
+
+    monkeypatch.setattr(body.shutil, "disk_usage", lambda path: types.SimpleNamespace(free=body.spool_floor() * 4))
+    monkeypatch.setattr(tempfile, "TemporaryFile", recorder)
+    b = body.Body(None, None)
+    payload = b"x" * (body.SPOOL_MAX_SIZE + 1)
+    b.append(payload)
+    b.set_complete()
+    chunks = [chunk async for chunk in b]
+    assert len(calls) == 1
+    assert calls[0]["dir"] == str(state_tmp)
+    assert all(len(chunk) <= body.READ_CHUNK_SIZE for chunk in chunks)
+    assert b"".join(chunks) == payload
+    assert b._spool.seek(0, io.SEEK_END) == 0
+
+
+async def test_request_multipart(state_tmp):
+    app = quart.Quart(__name__)
+    app.request_class = body.Request
+    received = {}
+
+    @app.post("/upload")
+    async def upload():
+        files = await quart.request.files
+        fs = files["file"]
+        received["body"] = quart.request.body
+        received["content"] = fs.stream.read()
+        received["stream"] = fs.stream
+        return ""
+
+    payload = b"z" * 200000
+    client = app.test_client()
+    response = await client.post(
+        "/upload",
+        files={"file": datastructures.FileStorage(io.BytesIO(payload), filename="a.bin")},
+    )
+    assert response.status_code == 200
+    assert received["content"] == payload
+    assert received["body"]._spool.closed
+    assert received["stream"].closed
+    assert not isinstance(received["stream"], tempfile.SpooledTemporaryFile)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org