From ec9d1b6e3141029770eec773642f73a967ad102a Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 08:27:14 -0600 Subject: [PATCH] fix(lab-ops-hub): validate and bound the /crawl request-body read (#7036) --- pkgs/lab-ops-hub/container/app.py | 58 ++++++++- .../test/test_container_validate.py | 110 ++++++++++++++++++ 2 files changed, 166 insertions(+), 2 deletions(-) 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"Thello") + cls.server = HTTPServer(("127.0.0.1", 0), app.Handler) + cls.port = cls.server.server_address[1] + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + app.validate_crawl_url = cls._orig_validate + app._fetch_crawl = cls._orig_fetch + + def raw_request(self, head, body_prefix=b"", hold_seconds=0.0, read_timeout=5.0): + """Send one raw request; return (status, raw response bytes). + + body_prefix is sent immediately; the socket is then held open + for hold_seconds (the wedge posture) before reading.""" + with socket.create_connection(("127.0.0.1", self.port), timeout=read_timeout) as sock: + sock.sendall(head) + if body_prefix: + sock.sendall(body_prefix) + if hold_seconds: + time.sleep(hold_seconds) + sock.settimeout(read_timeout) + chunks = [] + try: + while True: + chunk = sock.recv(65536) + if not chunk: + break + chunks.append(chunk) + except socket.timeout: + raise AssertionError("server did not answer promptly") + raw = b"".join(chunks) + status = int(raw.split(b" ", 2)[1]) + return status, raw + + def post_head(self, length_header): + lines = [b"POST /crawl HTTP/1.0", b"Host: 127.0.0.1"] + if length_header is not None: + lines.append(b"Content-Length: " + length_header) + return b"\r\n".join(lines) + b"\r\n\r\n" + + def assert_get_still_answers(self): + status, _ = self.raw_request(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n") + self.assertEqual(status, 200) + + def test_negative_length_gets_prompt_400(self): + status, raw = self.raw_request( + self.post_head(b"-1"), body_prefix=b'{"url":', hold_seconds=0.2) + self.assertEqual(status, 400) + self.assertIn(b"Content-Length", raw) + self.assert_get_still_answers() + + def test_oversized_length_gets_prompt_400(self): + status, raw = self.raw_request( + self.post_head(str(app._CRAWL_REQUEST_MAX_BODY_BYTES + 1).encode()), + body_prefix=b'{"url":', hold_seconds=0.2) + self.assertEqual(status, 400) + self.assertIn(b"Content-Length", raw) + self.assert_get_still_answers() + + def test_non_numeric_length_gets_400(self): + status, raw = self.raw_request(self.post_head(b"abc")) + self.assertEqual(status, 400) + self.assertIn(b"invalid Content-Length", raw) + self.assert_get_still_answers() + + def test_missing_length_gets_400(self): + status, raw = self.raw_request(self.post_head(None)) + self.assertEqual(status, 400) + self.assertIn(b"missing Content-Length", raw) + self.assert_get_still_answers() + + def test_stalled_in_cap_body_times_out_and_server_recovers(self): + orig = app._CRAWL_REQUEST_READ_TIMEOUT_SECONDS + app._CRAWL_REQUEST_READ_TIMEOUT_SECONDS = 1 + try: + status, _ = self.raw_request( + self.post_head(b"100"), body_prefix=b'{"url": "x"', read_timeout=8.0) + finally: + app._CRAWL_REQUEST_READ_TIMEOUT_SECONDS = orig + self.assertEqual(status, 408) + self.assert_get_still_answers() + + def test_well_formed_control_still_200(self): + body = json.dumps({"url": "http://example.com/"}).encode() + status, raw = self.raw_request( + self.post_head(str(len(body)).encode()), body_prefix=body) + self.assertEqual(status, 200) + self.assertIn(b'"status_code": 200', raw) + self.assert_get_still_answers() + + if __name__ == "__main__": unittest.main()