diff --git a/pkgs/lab-ops-hub/container/app.py b/pkgs/lab-ops-hub/container/app.py index 61a12912a5..c0ec8808ae 100644 --- a/pkgs/lab-ops-hub/container/app.py +++ b/pkgs/lab-ops-hub/container/app.py @@ -1358,6 +1358,13 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): _CRAWL_MAX_BODY_BYTES = 2_000_000 _CRAWL_READ_CHUNK_BYTES = 65_536 +# Request-side bounds for POST /crawl (#7036): the payload is a small +# {"url": ...} JSON object, and the server is single-threaded, so the +# declared Content-Length is validated before any read and the read +# itself runs under one absolute deadline. +_CRAWL_REQUEST_MAX_BODY_BYTES = 65_536 +_CRAWL_REQUEST_READ_TIMEOUT_SECONDS = 10 + def _fetch_crawl(url): # Fetch a validated URL and return (status, body capped at 2 MB). One @@ -1470,12 +1477,51 @@ def _send(self, code, payload): def do_GET(self): self._send(200, {"ok": True, "service": "labops-crawler"}) + def _read_request_body(self, length): + # Read exactly `length` bytes under one absolute deadline + # (#7036): a client that declares an in-cap length but stalls + # mid-body must not wedge this single-threaded server. + deadline = time.monotonic() + _CRAWL_REQUEST_READ_TIMEOUT_SECONDS + chunks = [] + remaining = length + try: + while remaining > 0: + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError("request body read timed out") + self.connection.settimeout(left) + chunk = self.rfile.read(min(remaining, _CRAWL_READ_CHUNK_BYTES)) + if not chunk: + raise ValueError("request body ended before Content-Length bytes arrived") + chunks.append(chunk) + remaining -= len(chunk) + finally: + self.connection.settimeout(None) + return b"".join(chunks) + def do_POST(self): if self.path != "/crawl": return self._send(404, {"error": "POST /crawl only"}) + # Validate Content-Length before reading a single byte (#7036): + # the old code trusted it outright — a negative length reads + # until EOF and an oversized one waits for a body that may + # never finish, and either wedges every later request behind + # this single-threaded server. + raw_length = self.headers.get("content-length") + if raw_length is None: + return self._send(400, {"error": "missing Content-Length"}) try: - length = int(self.headers.get("content-length", "0")) - url = json.loads(self.rfile.read(length))["url"] + length = int(raw_length) + except ValueError: + return self._send(400, {"error": f"invalid Content-Length: {raw_length!r}"}) + if length < 0 or length > _CRAWL_REQUEST_MAX_BODY_BYTES: + return self._send( + 400, + {"error": f"Content-Length {length} out of range: " + f"0..{_CRAWL_REQUEST_MAX_BODY_BYTES}"}, + ) + try: + url = json.loads(self._read_request_body(length))["url"] try: # Fetch the validated form: identical to the request # except for a percent-encoded host, which is fetched @@ -1500,6 +1546,14 @@ def do_POST(self): "text": text[:20000], }, ) + except TimeoutError: + # The stalled-body case (#7036): answer if the socket still + # takes it, and either way the handler returns so the + # server answers the next request. + try: + self._send(408, {"error": "request body read timed out"}) + except Exception: # noqa: BLE001 - the client may be gone + pass except Exception as e: # noqa: BLE001 - surface any crawl failure as JSON self._send(502, {"error": str(e)}) diff --git a/pkgs/lab-ops-hub/test/test_container_validate.py b/pkgs/lab-ops-hub/test/test_container_validate.py index 1ab048ccee..5194580880 100644 --- a/pkgs/lab-ops-hub/test/test_container_validate.py +++ b/pkgs/lab-ops-hub/test/test_container_validate.py @@ -5,9 +5,13 @@ # dependency): `python3 -m unittest discover -s test -p "test_*.py"` from # pkgs/lab-ops-hub. import importlib.util +import json import pathlib +import socket +import threading import time import unittest +from http.server import HTTPServer _APP_PATH = pathlib.Path(__file__).resolve().parent.parent / "container" / "app.py" _spec = importlib.util.spec_from_file_location("labops_container_app", _APP_PATH) @@ -2137,5 +2141,111 @@ def test_transport_failure_still_raises(self): app._fetch_crawl("http://127.0.0.1:1/nope") +class TestCrawlContentLength(unittest.TestCase): + """#7036: POST /crawl validates Content-Length before reading and + bounds the body read, so a malformed or stalled body cannot wedge + the single-threaded server. The Handler runs over a real socket + with validate_crawl_url / _fetch_crawl stubbed at the module.""" + + @classmethod + def setUpClass(cls): + cls._orig_validate = app.validate_crawl_url + cls._orig_fetch = app._fetch_crawl + app.validate_crawl_url = lambda url: url + app._fetch_crawl = lambda url: (200, b"