diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 18421a2f..f09e3f6d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -166,6 +166,7 @@ jobs: tests/test_proxy_keepalive.py tests/test_proxy_client_keys.py \ tests/test_proxy_systemone.py tests/test_proxy_hold.py \ tests/test_proxy_short_body.py tests/test_proxy_engine_withholds_headers.py \ + tests/test_proxy_door.py \ tests/test_tools.py tests/test_oc_fit_limits.py tests/test_oc_merge_limits.py; do "$PY" -m coverage run --branch --parallel-mode --source=. \ --omit="dashboard/*,tests/*,.venv-test/*" "$f" >/dev/null 2>&1 || true diff --git a/SECURITY.md b/SECURITY.md index 8dff8c37..3b2ca7c2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -89,6 +89,14 @@ installed choice is kept across updates in both directions, so neither a hardened box nor one that deliberately exposed its engine is changed by an update nobody read about. +**The key is checked before a body is read** (since v1.22.13, proxy v6.34). +Without the identity wall, the engine's key is the proxy port's one gate, and the +proxy applies it itself, with the engine's own rule and the engine's own 401, +before it reads a byte of the body. Until then a caller with no key, or a wrong +one, had its body read whole (up to `MAX_BODY_BYTES`) and, when it was large, +counted by the engine on the proxy's own key before the engine refused it. Paths +under `/health` and `/metrics` stay open, as the engine keeps them. + **The cockpit (`dashboard/`, :30090)** runs as the user who installed the box, and that user is already root-equivalent: `install.sh` requires it to be in the `docker` group, and a member of that group can start a container with the host's diff --git a/dashboard/tests/test_lifecycle.py b/dashboard/tests/test_lifecycle.py index 4caa0add..0acf9b73 100644 --- a/dashboard/tests/test_lifecycle.py +++ b/dashboard/tests/test_lifecycle.py @@ -453,6 +453,7 @@ class FeedOutcomes(unittest.TestCase): "400 bad Content-Length": "fail", "413 body over cap": "fail", "401 unknown client key": "fail", # the identity wall's refusal (v6.16) + "401 without the serving key": "fail", # the door's refusal, before the body (v6.34) "503 monster held during warmup": "fail", "503 engine unreachable": "fail", "503 engine unreachable (upstream 502)": "fail", diff --git a/docs/clients.md b/docs/clients.md index 08063b4d..1fbc764d 100644 --- a/docs/clients.md +++ b/docs/clients.md @@ -14,6 +14,9 @@ act on, and aborts decodes that emit the corruption marker. The engine port (`:30000`) speaks the same APIs without that protection, and **since v1.17 it binds `127.0.0.1`, so it answers on the box only**. That is the whole arrangement in one line: one door, and it is the one with the lock. +Since v1.22.13 the proxy checks that lock itself, with the engine's own rule, before it +reads a request's body: a request without the key gets the engine's own 401 at once, and +`/health` and `/metrics` stay open, as the engine keeps them. `ENGINE_BIND=0.0.0.0 ./install.sh` puts the engine back on the network for a box that wants it, and a box that already had it there keeps it across updates. diff --git a/keepalive-proxy.py b/keepalive-proxy.py index 364e170a..e7a4262a 100755 --- a/keepalive-proxy.py +++ b/keepalive-proxy.py @@ -266,7 +266,7 @@ before relaying them at once: measured 2026-08-23, median inter-event gap 0 ms / max 1307 ms through the proxy vs a steady 118 ms direct. read1() returns as soon as bytes are available, so the stream stays token by token. """ -import base64, collections, concurrent.futures, hashlib, http.client, json, math, os, queue, re, select, socket, ssl, string, subprocess, sys, threading, time, urllib.parse, urllib.request, urllib.error, uuid +import base64, collections, concurrent.futures, hashlib, hmac, http.client, json, math, os, queue, re, select, socket, ssl, string, subprocess, sys, threading, time, urllib.parse, urllib.request, urllib.error, uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -573,6 +573,40 @@ def _upstream_auth(handler): # /v1/... only, while _upstream_auth attaches the engine's key to everything relayed. OPEN_ROUTES = frozenset({"/health"}) SERVER_INFO_ROUTES = frozenset({"/server_info", "/get_server_info"}) +# Without the identity wall, the engine's key is this port's one gate (README), and since +# v6.34 the proxy applies it before reading a body. The rule is the engine's own, from +# SGLang's srt/utils/auth.py (decide_request_auth, _check_bearer_token; the same in both +# pinned images) and measured on the live engine on 2026-10-08: a path under /health or +# /metrics needs no key (/health, /health_generate and /metrics answered 200 with no +# header); any other needs an Authorization header that, without the whitespace around it, +# is a scheme spelled "bearer" in any case, one space, and the key exactly. "bearer KEY" +# and "Bearer KEY " were admitted; "Bearer KEY", "BearerKEY", "Token KEY", the key +# alone and no header were 401. +ENGINE_OPEN_PREFIXES = ("/health", "/metrics") +# The engine's own refusal, byte for byte, so a client gets the answer it always got. +ENGINE_401_BODY = b'{"error":"Unauthorized"}' + + +def engine_admits(authorization, key): + """True when SGLang's own key check would admit this Authorization header value.""" + if not authorization: + return False + parts = authorization.strip(" \t").split(" ", 1) + if len(parts) != 2 or parts[0].lower() != "bearer": + return False + return hmac.compare_digest(parts[1].encode("utf-8", "replace"), key.encode("utf-8", "replace")) + + +def _door_key(): + """The key the engine checks, or None when there is none to compare with: the engine's + own check then decides, as it always did. It is the file the proxy signs its own engine + calls with, so the door and those calls cannot disagree about which key is current.""" + if UPSTREAM_API_KEY: + return UPSTREAM_API_KEY + try: + return _api_key() or None + except Exception: + return None KEY_FIELDS = ("api_key", "admin_api_key", "ssl_keyfile_password") # A secret flag's value, wherever a string of the answer repeats a command line (SGLang's # launch_command, v6.32): `--api-key K`, `--api-key=K`, quoted or not. @@ -2718,8 +2752,9 @@ class H(BaseHTTPRequestHandler): pass def handle_expect_100(self): - # A client that asks before it sends (Expect: 100-continue) is told of the cap - # before it sends anything, rather than invited to send it all first. + # A client that asks before it sends (Expect: 100-continue) is told of the cap, and + # of a key the engine would refuse (v6.34), before it sends anything, rather than + # invited to send it all first. n = parse_body_length(self.headers.get("Content-Length")) if n is not None and body_over_cap(n): log(f"{self.client_address[0]}:{self.client_address[1]} REFUSED body {n}b over the " @@ -2728,6 +2763,13 @@ class H(BaseHTTPRequestHandler): json.dumps({"error": {"type": "body_too_large", "message": f"keepalive-proxy: request body {n}b exceeds the {MAX_BODY_BYTES}b cap"}}).encode()) return False + path, suspect = canonical_path(self.path) + route = path.split("?")[0] + if not suspect and self._door_shut(route): + log(f"{self.client_address[0]}:{self.client_address[1]} REFUSED without the serving key " + f"on {route}, before its body was sent") + self._door_answer(route) + return False return super().handle_expect_100() def _unavailable(self, exc): @@ -3363,7 +3405,7 @@ class H(BaseHTTPRequestHandler): self._done("400 suspect path"); return self._label_peer() log(f"{self._peer} -> {self.command} {self.path.split('?')[0]} body={n0}b") - if self._wall_refused(): + if self._wall_refused() or self._door_refused(): return n = parse_body_length(self.headers.get("Content-Length")) if n is None: @@ -3765,7 +3807,7 @@ class H(BaseHTTPRequestHandler): "fragment, an escape left after one decode, or a byte " "outside printable ASCII, and is refused"}}).encode()) self._done("400 suspect path"); return - if self._wall_refused(): + if self._wall_refused() or self._door_refused(): return resp, herr, cerr = self._open(None) if cerr is not None: @@ -3819,6 +3861,44 @@ class H(BaseHTTPRequestHandler): self._done("401 unknown client key") return True + def _door_shut(self, route): + """True when this request does not carry the key the engine admits (v6.34). The + wall, when on, decides instead; a route the engine leaves open, or a box whose key + the proxy cannot read, stays the engine's own business.""" + if CLIENT_KEYS or route.startswith(ENGINE_OPEN_PREFIXES): + return False + key = _door_key() + return bool(key) and not engine_admits(self.headers.get("Authorization"), key) + + def _door_refused(self): + """True when this request was answered 401 because it does not carry the key the + engine admits (v6.34): answered before a byte of its body is read, so it costs + neither the proxy's memory nor any engine work, where the engine's own 401 came only + after the body was read whole and, for a large prompt, counted by the engine on the + proxy's key.""" + route = self.path.split("?")[0] + if not self._door_shut(route): + return False + log(f"{self._peer} REFUSED without the serving key on {route}, before its body") + self._door_answer(route) + self._done("401 without the serving key") + return True + + def _door_answer(self, route): + """The engine's own 401, or, on the route that answers in its own envelope, the same + status and error_type a refused key came back with before the door.""" + if self.command == "POST" and route == SYSTEMONE_PATH: + # This route answers in its own envelope, and a key the engine refuses came back + # in it before the door: same status, same error_type, an honest message. + body = json.dumps({"detail": {"error_type": "engine_error", "message": + "keepalive-proxy: the engine's key check refuses this " + "request (HTTP 401: " + ENGINE_401_BODY.decode() + "): it " + "carries no Authorization: Bearer key the engine admits, " + "so nothing was sent to it"}}).encode() + else: + body = ENGINE_401_BODY + self._plain(401, {"Content-Type": "application/json"}, body) + if __name__ == "__main__": port = int(sys.argv[1]) if len(sys.argv) > 1 else 30001 holds = (f"holds requests up to {HOLD_MAX_S:.0f}s while {' or '.join(HOLD_UNITS)} comes back" diff --git a/tests/test_proxy_abort.py b/tests/test_proxy_abort.py index 47b44703..755c2198 100644 --- a/tests/test_proxy_abort.py +++ b/tests/test_proxy_abort.py @@ -32,6 +32,14 @@ import uuid from pathlib import Path +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + def _keep_env(cls): """Put os.environ back as this class found it, once it is done: the variables set for the proxy under test (UPSTREAM and the rest) stayed set for every module after this @@ -163,6 +171,7 @@ class Abort(unittest.TestCase): cls.mod = importlib.util.module_from_spec(SPEC) sys.argv = ["keepalive-proxy.py"] SPEC.loader.exec_module(cls.mod) + cls.mod._api_key = _no_key cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.port = cls.proxy.server_address[1] diff --git a/tests/test_proxy_answer_headers.py b/tests/test_proxy_answer_headers.py index b204806d..71ecf1c9 100644 --- a/tests/test_proxy_answer_headers.py +++ b/tests/test_proxy_answer_headers.py @@ -19,6 +19,15 @@ import time import unittest from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + PROXY = Path(__file__).resolve().parents[1] / "keepalive-proxy.py" @@ -77,6 +86,7 @@ class EveryRelayedAnswerHasOneServerAndOneDate(unittest.TestCase): cls.addClassCleanup(setattr, sys, "argv", argv) sys.argv = ["keepalive-proxy.py"] spec.loader.exec_module(cls.mod) + cls.mod._api_key = _no_key cls.mod.log = lambda *a: None cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() diff --git a/tests/test_proxy_client_keys.py b/tests/test_proxy_client_keys.py index 4e90cd01..778da942 100644 --- a/tests/test_proxy_client_keys.py +++ b/tests/test_proxy_client_keys.py @@ -37,6 +37,15 @@ import urllib.error import urllib.request from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + REPO = Path(__file__).resolve().parents[1] BODY = json.dumps({"model": "x", "messages": []}).encode() @@ -144,6 +153,7 @@ def fresh_proxy_module(upstream_port, keys_path=None, upstream_key=None): os.environ.pop(key, None) else: os.environ[key] = value + mod._api_key = _no_key # a scenario's key, when it has one, is QWEN38_UPSTREAM_API_KEY return mod diff --git a/tests/test_proxy_door.py b/tests/test_proxy_door.py new file mode 100644 index 00000000..48ed7629 --- /dev/null +++ b/tests/test_proxy_door.py @@ -0,0 +1,398 @@ +#!/usr/bin/env python3 +"""The serving key is checked before a body is read (keepalive-proxy v6.34). + +Without the identity wall, the engine's own key check is this port's one gate, and the +proxy applies it itself: a request that does not carry the key the engine admits gets the +engine's own 401 before a byte of its body is read, with no engine work behind it, and the +routes the engine leaves open (/health*, /metrics*) stay open. The rule is the engine's, +and the matrix below is what the live engine answered on 2026-10-08 (SGLang's +srt/utils/auth.py, the same in both pinned images).""" +import http.client +import http.server +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve() +KEY = "door-test-key-0123456789" + +# (Authorization value, does the engine admit it), as measured on the live engine. +ENGINE_RULE = [ + (f"Bearer {KEY}", True), + (f"bearer {KEY}", True), + (f"BEARER {KEY}", True), + (f" Bearer {KEY}", True), + (f"Bearer {KEY} ", True), + (f"Bearer {KEY}", False), + (f"Bearer\t{KEY}", False), + (f"Token {KEY}", False), + (KEY, False), + ("Bearer wrong", False), + (f"Bearer {KEY}x", False), + ("Bearer", False), + (None, False), +] + + +class TheRuleItself(unittest.TestCase): + """engine_admits and the key it compares with, in process (the coverage floor reads these).""" + + @classmethod + def setUpClass(cls): + import importlib.util + spec = importlib.util.spec_from_file_location("kproxy_door", HERE.parents[1] / "keepalive-proxy.py") + cls.m = importlib.util.module_from_spec(spec) + sys.argv = ["keepalive-proxy.py"] + spec.loader.exec_module(cls.m) + + def test_the_measured_matrix(self): + for auth, admitted in ENGINE_RULE: + with self.subTest(auth=auth): + self.assertEqual(self.m.engine_admits(auth, KEY), admitted) + + def test_a_non_ascii_bearer_is_refused_not_raised(self): + self.assertFalse(self.m.engine_admits("Bearer cl\xe9", KEY)) + + def test_the_key_comes_from_the_upstream_setting_then_the_file(self): + old_up, old_read = self.m.UPSTREAM_API_KEY, self.m._api_key + try: + self.m.UPSTREAM_API_KEY = "from-env" + self.m._api_key = lambda: "from-file" + self.assertEqual(self.m._door_key(), "from-env") + self.m.UPSTREAM_API_KEY = "" + self.assertEqual(self.m._door_key(), "from-file") + self.m._api_key = lambda: "" + self.assertIsNone(self.m._door_key(), "an empty key file compares with nothing") + + def missing(): + raise FileNotFoundError("no key here") + self.m._api_key = missing + self.assertIsNone(self.m._door_key()) + finally: + self.m.UPSTREAM_API_KEY, self.m._api_key = old_up, old_read + + +class Engine(http.server.BaseHTTPRequestHandler): + """Answers everything and writes down every request it was asked, so a test can prove + the engine was never reached. It checks no key: whatever reaches it is relayed.""" + seen = [] + lock = threading.Lock() + + def log_message(self, *a): + pass + + def _send(self, obj): + out = json.dumps(obj).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + def do_GET(self): + with Engine.lock: + Engine.seen.append(("GET", self.path, self.headers.get("Authorization"))) + if self.path.startswith("/v1/models"): + self._send({"object": "list", "data": [{"id": "qwen3.8-test", "object": "model"}]}) + elif self.path in ("/server_info", "/get_server_info"): + self._send({"max_total_num_tokens": 1_000_000}) + else: + self._send({"ok": True}) + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + self.rfile.read(n) + with Engine.lock: + Engine.seen.append(("POST", self.path, self.headers.get("Authorization"))) + if self.path == "/tokenize": + self._send({"count": 10}) + return + self._send({"id": "x", "object": "chat.completion", "model": "qwen3.8-test", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, + "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}) + + +def _free_port(): + with socket.socket() as sk: + sk.bind(("127.0.0.1", 0)) + return sk.getsockname()[1] + + +def _start_proxy(home, upstream_port, extra_env=None): + port = _free_port() + err = tempfile.NamedTemporaryFile(prefix="door-proxy-stderr-", delete=False) + env = {"PATH": os.environ["PATH"], "HOME": str(home), "PROXY_BIND": "127.0.0.1", + "UPSTREAM": f"http://127.0.0.1:{upstream_port}", **(extra_env or {})} + proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], + env=env, stdout=err, stderr=err) + end = time.time() + 20 + while time.time() < end: + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + time.sleep(0.05) + return proc, port, err.name + + +def _home(with_key=True): + home = Path(tempfile.mkdtemp(prefix="door-home-")) + (home / ".config/qwen38").mkdir(parents=True) + if with_key: + (home / ".config/qwen38/api-key").write_text(KEY + "\n") + return home + + +class TheDoor(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine) + threading.Thread(target=cls.eng.serve_forever, daemon=True).start() + cls.home = _home() + cls.proc, cls.port, cls.err = _start_proxy(cls.home, cls.eng.server_address[1]) + + @classmethod + def tearDownClass(cls): + cls.proc.terminate() + cls.proc.wait(timeout=10) + cls.eng.shutdown() + cls.eng.server_close() + shutil.rmtree(cls.home, ignore_errors=True) + try: + text = Path(cls.err).read_text(errors="replace") + finally: + os.unlink(cls.err) + # A traceback is an error even when the status the client got was right: the + # door-full path of an earlier draft wrote its 503 and then raised. + assert "Traceback" not in text, text[-2000:] + + def setUp(self): + with Engine.lock: + Engine.seen = [] + + def request(self, method, path, body=None, auth=None, headers=None): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + try: + c.putrequest(method, path, skip_accept_encoding=True) + if auth is not None: + c.putheader("Authorization", auth) + for k, v in (headers or {}).items(): + c.putheader(k, v) + if body is not None: + c.putheader("Content-Type", "application/json") + c.putheader("Content-Length", str(len(body))) + c.endheaders() + if body is not None: + c.send(body) + r = c.getresponse() + return r.status, r.read() + finally: + c.close() + + def chat(self, auth, content="hi"): + body = json.dumps({"model": "qwen3.8-test", "messages": [{"role": "user", "content": content}], + "max_tokens": 4}).encode() + return self.request("POST", "/v1/chat/completions", body, auth) + + def test_the_engine_rule_decides_and_a_refusal_costs_the_engine_nothing(self): + for auth, admitted in ENGINE_RULE: + with self.subTest(auth=auth): + with Engine.lock: + Engine.seen = [] + status, raw = self.chat(auth) + if admitted: + self.assertEqual(status, 200, raw[:200]) + self.assertIn(("POST", "/v1/chat/completions"), [s[:2] for s in Engine.seen]) + else: + self.assertEqual(status, 401, raw[:200]) + self.assertEqual(raw, b'{"error":"Unauthorized"}', "the engine's own answer") + self.assertEqual(Engine.seen, [], "a refused request reached the engine") + + def test_a_large_body_without_the_key_is_refused_with_no_count_and_no_relay(self): + body = json.dumps({"model": "qwen3.8-test", + "messages": [{"role": "user", "content": "1 " * 1_200_000}]}).encode() + status, raw = self.request("POST", "/v1/chat/completions", body, None) + self.assertEqual(status, 401, raw[:200]) + self.assertEqual(Engine.seen, [], "no /server_info, no /tokenize, no relay") + + def test_the_body_is_not_read_before_the_refusal(self): + """Headers announcing 50 MB, and not one byte of it sent: the 401 still comes, at + once. Before v6.34 the proxy waited for the body, and only then relayed it.""" + s = socket.create_connection(("127.0.0.1", self.port), timeout=10) + try: + s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\n" + b"Content-Type: application/json\r\nContent-Length: 50000000\r\n\r\n") + s.settimeout(5) + head = b"" + t0 = time.time() + while b"\r\n\r\n" not in head: + piece = s.recv(4096) + if not piece: + break + head += piece + finally: + s.close() + self.assertTrue(head.startswith(b"HTTP/1.1 401"), head[:80]) + self.assertLess(time.time() - t0, 3) + self.assertEqual(Engine.seen, []) + + def test_the_routes_the_engine_leaves_open_need_no_key(self): + for path in ("/health", "/health_generate", "/metrics"): + with self.subTest(path=path): + with Engine.lock: + Engine.seen = [] + status, _ = self.request("GET", path) + self.assertEqual(status, 200) + self.assertIn(("GET", path), [s[:2] for s in Engine.seen]) + + def test_a_read_without_the_key_is_refused_too(self): + for path in ("/v1/models", "/server_info", "/get_model_info"): + with self.subTest(path=path): + with Engine.lock: + Engine.seen = [] + status, raw = self.request("GET", path) + self.assertEqual(status, 401, raw[:200]) + self.assertEqual(Engine.seen, []) + status, raw = self.request("GET", "/v1/models", auth=f"Bearer {KEY}") + self.assertEqual(status, 200, raw[:200]) + + def test_an_escaped_open_route_is_still_open_and_an_escaped_closed_one_still_closed(self): + """The door judges the path the engine routes on (decoded once), never the raw one.""" + status, _ = self.request("GET", "/%68ealth") + self.assertEqual(status, 200) + status, _ = self.request("GET", "/%76%31/models") + self.assertEqual(status, 401) + + def test_systemone_keeps_its_envelope(self): + body = json.dumps({"state": "s", "model": "jev-latest", + "questions": {"q": {"type": "noul", "instructions": "i"}}}).encode() + status, raw = self.request("POST", "/v1/systemone", body, "Bearer wrong") + self.assertEqual(status, 401, raw[:200]) + detail = json.loads(raw)["detail"] + self.assertEqual(detail["error_type"], "engine_error") + self.assertIn("key", detail["message"]) + self.assertEqual(Engine.seen, [], "no model lookup, no pool read, no branch") + + def test_a_client_that_asks_first_is_refused_before_it_sends(self): + s = socket.create_connection(("127.0.0.1", self.port), timeout=10) + try: + s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" + b"Expect: 100-continue\r\nContent-Length: 1000000\r\n\r\n") + head = b"" + while b"\r\n\r\n" not in head: + piece = s.recv(4096) + if not piece: + break + head += piece + finally: + s.close() + self.assertTrue(head.startswith(b"HTTP/1.1 401"), head[:80]) + self.assertEqual(Engine.seen, []) + + def test_a_client_with_the_key_that_asks_first_is_invited(self): + s = socket.create_connection(("127.0.0.1", self.port), timeout=10) + try: + s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" + b"Authorization: Bearer " + KEY.encode() + b"\r\n" + b"Expect: 100-continue\r\nContent-Length: 2\r\n\r\n") + s.settimeout(5) + head = s.recv(4096) + finally: + s.close() + self.assertTrue(head.startswith(b"HTTP/1.1 100"), head[:80]) + + +class WithoutAKeyToCompare(unittest.TestCase): + """A box whose key the proxy cannot read: the engine's own check decides, as before.""" + + @classmethod + def setUpClass(cls): + cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine) + threading.Thread(target=cls.eng.serve_forever, daemon=True).start() + cls.home = _home(with_key=False) + cls.proc, cls.port, cls.err = _start_proxy(cls.home, cls.eng.server_address[1]) + + @classmethod + def tearDownClass(cls): + cls.proc.terminate() + cls.proc.wait(timeout=10) + cls.eng.shutdown() + cls.eng.server_close() + shutil.rmtree(cls.home, ignore_errors=True) + os.unlink(cls.err) + + def test_a_request_without_a_key_is_relayed(self): + with Engine.lock: + Engine.seen = [] + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + try: + c.request("POST", "/v1/chat/completions", + json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}), + {"Content-Type": "application/json"}) + r = c.getresponse() + self.assertEqual(r.status, 200) + r.read() + finally: + c.close() + self.assertIn(("POST", "/v1/chat/completions"), [s[:2] for s in Engine.seen]) + + +class TheIdentityWallIsUnchanged(unittest.TestCase): + """With the wall on, clients hold bearers of their own, which the engine's rule would + refuse: the wall decides, and the door stands aside.""" + + @classmethod + def setUpClass(cls): + cls.eng = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine) + threading.Thread(target=cls.eng.serve_forever, daemon=True).start() + cls.home = _home() + keys = cls.home / "client-keys.json" + keys.write_text(json.dumps({"alice-token": "alice"})) + cls.proc, cls.port, cls.err = _start_proxy( + cls.home, cls.eng.server_address[1], + {"QWEN38_CLIENT_KEYS_FILE": str(keys), "QWEN38_UPSTREAM_API_KEY": KEY}) + + @classmethod + def tearDownClass(cls): + cls.proc.terminate() + cls.proc.wait(timeout=10) + cls.eng.shutdown() + cls.eng.server_close() + shutil.rmtree(cls.home, ignore_errors=True) + os.unlink(cls.err) + + def post(self, auth): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + try: + c.request("POST", "/v1/chat/completions", + json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}), + {"Content-Type": "application/json", "Authorization": auth}) + r = c.getresponse() + return r.status, r.read() + finally: + c.close() + + def test_a_named_client_is_admitted_with_the_engine_key_upstream(self): + with Engine.lock: + Engine.seen = [] + status, raw = self.post("Bearer alice-token") + self.assertEqual(status, 200, raw[:200]) + self.assertIn(("POST", "/v1/chat/completions", f"Bearer {KEY}"), Engine.seen) + + def test_an_unlisted_bearer_meets_the_wall(self): + status, raw = self.post(f"Bearer {KEY}") + self.assertEqual(status, 401) + self.assertIn(b"missing or unknown client key", raw) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_proxy_engine_withholds_headers.py b/tests/test_proxy_engine_withholds_headers.py index 5d44ae46..d782cfce 100644 --- a/tests/test_proxy_engine_withholds_headers.py +++ b/tests/test_proxy_engine_withholds_headers.py @@ -31,6 +31,15 @@ import unittest from contextlib import redirect_stderr from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + HERE = Path(__file__).resolve() REPO = HERE.parents[1] @@ -132,6 +141,7 @@ class Base(unittest.TestCase): cls.mod = importlib.util.module_from_spec(spec) sys.argv = ["keepalive-proxy.py"] spec.loader.exec_module(cls.mod) + cls.mod._api_key = _no_key cls.log = io.StringIO() cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) cls.err = redirect_stderr(cls.log) diff --git a/tests/test_proxy_guard.py b/tests/test_proxy_guard.py index 3e517579..b8fd124f 100644 --- a/tests/test_proxy_guard.py +++ b/tests/test_proxy_guard.py @@ -42,6 +42,23 @@ def key_home(): return home +# Since v6.34 the proxy applies the engine's key check before it reads a body, so a client of +# these harnesses presents the key the harness gave the proxy, as every real client does. +KEY_HEADER = {"Authorization": "Bearer test-key"} + + +def no_key_home(): + """A throwaway HOME with no engine key, for a proxy run as a process whose clients send + none: the ambient HOME may hold one (the CI's offline step gives it one).""" + return Path(tempfile.mkdtemp(prefix="proxy-nokey-home-")) + + +def _no_key(): + """The serving key of an in-process proxy whose clients send none: none, whatever HOME + holds. The door that compares a bearer with that key has its own tests.""" + raise FileNotFoundError("no serving key in this harness") + + class FakeTokenize(http.server.BaseHTTPRequestHandler): seen = [] @@ -409,7 +426,7 @@ class ProxyInFrontOfLoadingEngine(unittest.TestCase): def _post(self, body): req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body, - headers={"Content-Type": "application/json"}, method="POST") + headers={"Content-Type": "application/json", **KEY_HEADER}, method="POST") try: with urllib.request.urlopen(req, timeout=10) as r: return r.status, dict(r.headers), r.read() @@ -450,7 +467,10 @@ class ProxyOnABoxSwitchedToImages(unittest.TestCase): sk.bind(("127.0.0.1", 0)); dead = sk.getsockname()[1] with socket.socket() as sk: sk.bind(("127.0.0.1", 0)); port = sk.getsockname()[1] - env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{dead}", PATH=f"{fake}:{os.environ.get('PATH', '')}") + home = no_key_home() + self.addCleanup(shutil.rmtree, home, True) + env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{dead}", PATH=f"{fake}:{os.environ.get('PATH', '')}", + HOME=str(home)) proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(port)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.addCleanup(lambda: (proc.terminate(), proc.wait(timeout=5))) @@ -587,7 +607,7 @@ class RefusalIsRecognisableAsOverflow(unittest.TestCase): body = json.dumps({"model": "m", "messages": [ {"role": "user", "content": "word " * 120000}]}).encode() req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body, - headers={"Content-Type": "application/json"}, method="POST") + headers={"Content-Type": "application/json", **KEY_HEADER}, method="POST") try: with urllib.request.urlopen(req, timeout=10) as r: self.fail(f"an oversize body was relayed: {r.status}") @@ -840,8 +860,9 @@ class CorruptionTripwireEndToEnd(unittest.TestCase): threading.Thread(target=cls.eng.serve_forever, daemon=True).start() with socket.socket() as sk: sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] + cls.home = no_key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", - CORRUPTION_RUN="48", PROMPT_CEILING_TOKENS="0") + CORRUPTION_RUN="48", PROMPT_CEILING_TOKENS="0", HOME=str(cls.home)) cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(100): @@ -854,6 +875,7 @@ class CorruptionTripwireEndToEnd(unittest.TestCase): def tearDownClass(cls): cls.proc.terminate(); cls.proc.wait(timeout=10) cls.eng.shutdown(); cls.eng.server_close() + shutil.rmtree(cls.home, ignore_errors=True) def test_the_stream_is_cut_and_the_client_is_told_why(self): import time @@ -923,9 +945,10 @@ class HardeningV615(unittest.TestCase): threading.Thread(target=cls.eng.serve_forever, daemon=True).start() with socket.socket() as sk: sk.bind(("127.0.0.1", 0)); cls.port = sk.getsockname()[1] + cls.home = no_key_home() env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{cls.eng.server_address[1]}", PROMPT_CEILING_TOKENS="200000", UPSTREAM_GET_TIMEOUT_S="1", - MAX_BODY_BYTES="1000000") + MAX_BODY_BYTES="1000000", HOME=str(cls.home)) cls.proc = subprocess.Popen([sys.executable, str(HERE.parents[1] / "keepalive-proxy.py"), str(cls.port)], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(100): @@ -940,6 +963,7 @@ class HardeningV615(unittest.TestCase): def tearDownClass(cls): cls.proc.terminate(); cls.proc.wait(timeout=10) cls.eng.shutdown(); cls.eng.server_close() + shutil.rmtree(cls.home, ignore_errors=True) def _raw(self, head, body=b""): import socket @@ -1610,6 +1634,7 @@ class ClientStringsAreNotKept(unittest.TestCase): cls.m = importlib.util.module_from_spec(spec) sys.argv = ["keepalive-proxy.py"] spec.loader.exec_module(cls.m) + cls.m._api_key = _no_key cls.proxy = cls.m.Server(("127.0.0.1", 0), cls.m.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.base = f"http://127.0.0.1:{cls.proxy.server_port}" @@ -1696,7 +1721,7 @@ class TopLogprobsCeilingEndToEnd(unittest.TestCase): def post(self, obj, path="/v1/chat/completions"): req = urllib.request.Request( self.base + path, data=json.dumps(obj).encode(), method="POST", - headers={"Content-Type": "application/json", "Authorization": "Bearer t"}) + headers={"Content-Type": "application/json", "Authorization": "Bearer test-key"}) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.read() @@ -1763,7 +1788,7 @@ class TopLogprobsCeilingEndToEnd(unittest.TestCase): def raw_post(self, path, raw): req = urllib.request.Request( self.base + path, data=raw, method="POST", - headers={"Content-Type": "application/json", "Authorization": "Bearer t"}) + headers={"Content-Type": "application/json", "Authorization": "Bearer test-key"}) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.read() @@ -1828,7 +1853,7 @@ class TheOversizeGuardReachesTheNonV1Routes(unittest.TestCase): def _post(self, path, obj): req = urllib.request.Request(f"http://127.0.0.1:{self.port}{path}", data=json.dumps(obj).encode(), method="POST", - headers={"Content-Type": "application/json"}) + headers={"Content-Type": "application/json", **KEY_HEADER}) try: with urllib.request.urlopen(req, timeout=15) as r: return r.status, r.read() @@ -1886,7 +1911,7 @@ class TheGuardNominatesByItsBound(unittest.TestCase): body = json.dumps({"model": model, "messages": [{"role": "user", "content": content}]}).encode() SmallPoolEngine.seen_post_paths = [] req = urllib.request.Request(f"http://127.0.0.1:{self.port}/v1/chat/completions", data=body, - method="POST", headers={"Content-Type": "application/json"}) + method="POST", headers={"Content-Type": "application/json", **KEY_HEADER}) try: with urllib.request.urlopen(req, timeout=15) as r: status, raw = r.status, r.read() diff --git a/tests/test_proxy_keepalive.py b/tests/test_proxy_keepalive.py index 39f90626..3ceb06ef 100644 --- a/tests/test_proxy_keepalive.py +++ b/tests/test_proxy_keepalive.py @@ -27,6 +27,14 @@ import unittest from pathlib import Path +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + def _keep_env(cls): """Put os.environ back as this class found it, once it is done: the variables set for the proxy under test (UPSTREAM and the rest) stayed set for every module after this @@ -140,6 +148,7 @@ class Base(unittest.TestCase): cls.mod = importlib.util.module_from_spec(spec) sys.argv = ["keepalive-proxy.py"] spec.loader.exec_module(cls.mod) + cls.mod._api_key = _no_key cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.port = cls.proxy.server_address[1] diff --git a/tests/test_proxy_refusal_reaches_client.py b/tests/test_proxy_refusal_reaches_client.py index 44e9f150..080be10b 100644 --- a/tests/test_proxy_refusal_reaches_client.py +++ b/tests/test_proxy_refusal_reaches_client.py @@ -5,7 +5,11 @@ The 413 for a body past MAX_BODY_BYTES went out without the body being read, and socket closed at once: the kernel answered the rest of the upload with a reset, and the reset destroyed the 413 on its way, so a client sending 20 MB past a 1 MB cap saw a broken pipe five times in five (found in review, 2026-09-24). And a client that asks first -(Expect: 100-continue) was invited to send it all before being refused.""" +(Expect: 100-continue) was invited to send it all before being refused. + +The same holds for the 401 the proxy answers since v6.34 when a request does not carry the +key the engine admits: it is sent before the body is read, so it must arrive whole too, and +a client that asks first must be refused before it sends.""" import http.client import os import pathlib @@ -19,6 +23,7 @@ import unittest REPO = pathlib.Path(__file__).resolve().parents[1] CAP = 1024 * 1024 +KEY = "k-test" # the key this harness gives the proxy class TheRefusalArrives(unittest.TestCase): @@ -26,7 +31,7 @@ class TheRefusalArrives(unittest.TestCase): def setUpClass(cls): cls.home = pathlib.Path(tempfile.mkdtemp(prefix="kp-413-")) (cls.home / ".config" / "qwen38").mkdir(parents=True) - (cls.home / ".config" / "qwen38" / "api-key").write_text("k-test\n") + (cls.home / ".config" / "qwen38" / "api-key").write_text(KEY + "\n") with socket.socket() as s: s.bind(("127.0.0.1", 0)) cls.port = s.getsockname()[1] @@ -53,7 +58,8 @@ class TheRefusalArrives(unittest.TestCase): for _ in range(5): c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) try: - c.request("POST", "/v1/chat/completions", body, {"Content-Type": "application/json"}) + c.request("POST", "/v1/chat/completions", body, {"Content-Type": "application/json", + "Authorization": f"Bearer {KEY}"}) r = c.getresponse() self.assertEqual(r.status, 413) self.assertIn(b"body_too_large", r.read()) @@ -64,6 +70,7 @@ class TheRefusalArrives(unittest.TestCase): s = socket.create_connection(("127.0.0.1", self.port), timeout=10) try: s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" + b"Authorization: Bearer " + KEY.encode() + b"\r\n" b"Expect: 100-continue\r\nContent-Length: %d\r\n\r\n" % (20 * CAP)) head = b"" while b"\r\n\r\n" not in head: @@ -75,6 +82,36 @@ class TheRefusalArrives(unittest.TestCase): s.close() self.assertTrue(head.startswith(b"HTTP/1.1 413"), head[:80]) + def test_a_client_without_the_key_that_just_sends_reads_the_401(self): + """Under the cap, so only the key decides: the refusal goes out before the body is + read, and the client, still sending, reads it whole, five times in five.""" + body = b"x" * (CAP - 1) + for _ in range(5): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + try: + c.request("POST", "/v1/chat/completions", body, {"Content-Type": "application/json"}) + r = c.getresponse() + self.assertEqual(r.status, 401) + self.assertEqual(r.read(), b'{"error":"Unauthorized"}') + finally: + c.close() + + def test_a_client_without_the_key_that_asks_first_is_refused_before_sending(self): + s = socket.create_connection(("127.0.0.1", self.port), timeout=10) + try: + s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" + b"Authorization: Bearer wrong\r\n" + b"Expect: 100-continue\r\nContent-Length: %d\r\n\r\n" % (CAP - 1)) + head = b"" + while b"\r\n\r\n" not in head: + piece = s.recv(4096) + if not piece: + break + head += piece + finally: + s.close() + self.assertTrue(head.startswith(b"HTTP/1.1 401"), head[:80]) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/test_proxy_relay_integrity.py b/tests/test_proxy_relay_integrity.py index d441b984..8222a85a 100644 --- a/tests/test_proxy_relay_integrity.py +++ b/tests/test_proxy_relay_integrity.py @@ -26,6 +26,15 @@ import time import unittest from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + REPO = Path(__file__).resolve().parents[1] FULL = b'{"id":"x","choices":[{"message":{"content":"' + b"a" * 4000 + b'"}}]}' @@ -71,6 +80,7 @@ class TheClientSeesTheCut(unittest.TestCase): err, sys.stderr = sys.stderr, io.StringIO() try: spec.loader.exec_module(cls.mod) + cls.mod._api_key = _no_key finally: sys.stderr = err if saved is None: @@ -186,6 +196,7 @@ class ACallerThatLeavesStopsTheGeneration(unittest.TestCase): self.addCleanup(setattr, sys, "stderr", err) try: spec.loader.exec_module(mod) + mod._api_key = _no_key finally: if saved is None: os.environ.pop("UPSTREAM", None) diff --git a/tests/test_proxy_short_body.py b/tests/test_proxy_short_body.py index 35698a1c..41199ff0 100644 --- a/tests/test_proxy_short_body.py +++ b/tests/test_proxy_short_body.py @@ -18,6 +18,15 @@ import time import unittest from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + PROXY = Path(__file__).resolve().parents[1] / "keepalive-proxy.py" @@ -53,6 +62,7 @@ class ABodyThatNeverArrivedWhole(unittest.TestCase): self.addCleanup(setattr, sys, "argv", argv) sys.argv = ["keepalive-proxy.py"] spec.loader.exec_module(self.mod) + self.mod._api_key = _no_key self.lines = [] self.mod.log = self.lines.append self.proxy = self.mod.Server(("127.0.0.1", 0), self.mod.H) diff --git a/tests/test_proxy_systemone.py b/tests/test_proxy_systemone.py index a8d7ee11..486fa3e5 100644 --- a/tests/test_proxy_systemone.py +++ b/tests/test_proxy_systemone.py @@ -211,8 +211,9 @@ class SystemOne(unittest.TestCase): spec.loader.exec_module(cls.mod) # Handed its key rather than given ~/.config/qwen38/api-key: the file this wrote # when it was missing outlived an interrupted run, and install.sh keeps the key it - # finds (found in review, 2026-09-24). - cls.mod._api_key = lambda: "test-key" + # finds (found in review, 2026-09-24). It is the key the client below presents: + # since v6.34 the proxy applies the engine's key check before it reads a body. + cls.mod._api_key = lambda: "client-token" cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.base = f"http://127.0.0.1:{cls.proxy.server_port}" diff --git a/tests/test_systemone_check_stream.py b/tests/test_systemone_check_stream.py index 6f1a4b00..898d1ede 100644 --- a/tests/test_systemone_check_stream.py +++ b/tests/test_systemone_check_stream.py @@ -19,6 +19,15 @@ import time import unittest from pathlib import Path + +def _no_key(): + """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send + no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them + at the door (the CI's offline step gives HOME one). The door has its own tests, in + tests/test_proxy_door.py.""" + raise FileNotFoundError("no serving key in this harness") + + REPO = Path(__file__).resolve().parents[1] KEEPALIVE_S = 0.3 MAX_SILENCE_S = 1.5 @@ -102,6 +111,7 @@ class TheMixedLoadGrade(unittest.TestCase): argv, sys.argv = sys.argv, ["keepalive-proxy.py"] try: spec.loader.exec_module(cls.proxy_mod) + cls.proxy_mod._api_key = _no_key finally: sys.argv = argv cls.proxy = cls.proxy_mod.Server(("127.0.0.1", 0), cls.proxy_mod.H)