From b73b1ade23805be93e7e0cc056c258652b4a0db3 Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Tue, 10 Nov 2026 17:06:03 +0100 Subject: fix(server): read a refused POST body before answering A POST refused before its body was read (403, 401, 404, a wrong type or size) closed the socket on unread bytes; the kernel reset it and the client saw a broken pipe instead of the answer. test_upload_limits hit this about once in 40 runs (BrokenPipeError), and it slipped into the previous commit's suite run. _refuse reads up to 1 MiB of the body first; 0 failures in 300 runs of the affected tests after. Co-Authored-By: Claude Opus 5.5 --- deckit/server.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) (limited to 'deckit/server.py') diff --git a/deckit/server.py b/deckit/server.py index f3e1976..9246e54 100644 --- a/deckit/server.py +++ b/deckit/server.py @@ -238,29 +238,41 @@ class Handler(BaseHTTPRequestHandler): return self._send(200, file.read_bytes(), ctype, cache=file.suffix in (".woff2", ".svg")) self._send(404) + def _refuse(self, code, body=b""): + """Answer without using the request body, after reading it (up to + 1 MiB): closing on unread bytes resets the connection, and the + client sees a broken pipe instead of this answer.""" + try: + length = int(self.headers.get("Content-Length", 0) or 0) + except ValueError: + length = 0 + if length > 0: + self.rfile.read(min(length, 1 << 20)) + return self._send(code, body) + def do_POST(self): if not self._trusted(write=True): - return self._send(403) + return self._refuse(403) if not self._authed(): - return self._send(401) + return self._refuse(401) parts = urlsplit(self.path).path.strip("/").split("/") if len(parts) != 3 or parts[0] != "api": - return self._send(404) + return self._refuse(404) _, name, action = parts try: mod_ = REGISTRY.get(name) except module.ModuleError as e: - return self._send(404, str(e).encode()) + return self._refuse(404, str(e).encode()) fn = mod_.actions.get(action) if fn is None: - return self._send(404, b"unknown action") + return self._refuse(404, b"unknown action") try: length = int(self.headers.get("Content-Length", 0) or 0) except ValueError: return self._send(400, b"Invalid Content-Length") ctype, limit = mod_.uploads.get(action, ("application/json", 4096)) if self.headers.get("Content-Type") != ctype or not 0 < length <= limit: - return self._send(400, b"Unexpected body") + return self._refuse(400, b"Unexpected body") data = self.rfile.read(length) try: result = fn(data if action in mod_.uploads else json.loads(data)) -- cgit v1.2.3