mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 20:34:17 +01:00
Found by the verifier of v1.42.1 (2026-11-03), each with a test that fails on the commit before it: - the vLLM lanes read a body in UTF-16 or UTF-32 as well as UTF-8 (the SGLang lanes refuse it, orjson), and the guards, which look at a body's bytes first, saw none of its fields: any client could send those lanes what the guards refuse. And the rid strip as first written for this release read such a body and wrote it again in UTF-8 after the guards had passed it, on every lane. A body in another encoding than UTF-8 gets a 415, as RFC 8259 wants JSON between systems; - vLLM takes its request id from a body's "request_id" and the X-Request-Id header: both are dropped for a listed key and the other box too; - a body that may hold an id and cannot be read whole (too deep) was sent as it came: it gets a 400. The id is dropped once, as soon as the body is read, before the pair and every guard, so the body a box sends the other box of a pair is stripped as well. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
640 lines
33 KiB
Python
640 lines
33 KiB
Python
#!/usr/bin/env python3
|
|
"""v6.16's per-client identity wall: QWEN38_CLIENT_KEYS_FILE turns the proxy
|
|
into the component that knows WHO sent the request, or refuses to pretend.
|
|
|
|
The bug class here is the wall that is silently absent: a keys file that is
|
|
missing, empty or malformed must not degrade into "no wall, carry on", and a
|
|
request without a listed bearer must not reach the engine riding somebody
|
|
else's journal line. The 401 speaks the dialect of the caller it is refusing
|
|
(a Claude client parses authentication_error, an OpenAI client parses
|
|
error.type), and /health stays open: a monitoring endpoint behind an
|
|
identity wall stops being monitoring.
|
|
|
|
The proxy is imported fresh per scenario (environment first, then exec_module),
|
|
and every request crosses a real socket into the real handler: the module
|
|
executes where coverage can see it, which matters, because the wall is
|
|
exactly the kind of code a floor was set to keep covered.
|
|
|
|
v6.17's lesson is the engine below: unlike the other proxy test engines, this
|
|
one enforces a key, because the real one does. v6.16's wall identified every
|
|
labeled client and admitted none (their tokens met the engine's own key check
|
|
verbatim), and no test could see it against an engine that lets everything
|
|
through. The admission scenarios at the bottom exist so that hole cannot
|
|
reopen unnoticed.
|
|
"""
|
|
import http.client
|
|
import http.server
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
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()
|
|
|
|
|
|
class Engine(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
# Unlike the other proxy test engines, this one enforces a key, because
|
|
# the real one does: v6.16's tests passed against an engine that lets
|
|
# everything through, which is exactly why the verbatim-forwarding hole
|
|
# survived them. require_key names the engine's key; last_auth records
|
|
# what the proxy actually sent upstream on the last request.
|
|
require_key = None
|
|
last_auth = None
|
|
last_path = None # the path the proxy sent upstream, decoded or not
|
|
last_rid = None # (the body's rid, the x-override-rid header) of the last POST
|
|
last_body = None # the body of the last POST, parsed
|
|
last_request_id = None # the X-Request-Id header of the last POST (vLLM's request id)
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _admit(self):
|
|
Engine.last_auth = self.headers.get("Authorization")
|
|
Engine.last_path = self.path
|
|
if Engine.require_key and Engine.last_auth != "Bearer " + Engine.require_key:
|
|
body = json.dumps({"error": {"message": "engine: bad key",
|
|
"type": "invalid_request_error"}}).encode()
|
|
self.send_response(401)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return False
|
|
return True
|
|
|
|
def do_POST(self):
|
|
if not self._admit():
|
|
return
|
|
n = int(self.headers.get("Content-Length") or "0")
|
|
sent = self.rfile.read(n)
|
|
try:
|
|
Engine.last_body = json.loads(sent or b"{}")
|
|
rid = Engine.last_body.get("rid")
|
|
except (ValueError, AttributeError):
|
|
rid = None
|
|
Engine.last_rid = (rid, self.headers.get("x-override-rid"))
|
|
Engine.last_request_id = self.headers.get("x-request-id")
|
|
body = json.dumps({"id": "chatcmpl-test", "choices": []}).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
do_PUT = do_POST
|
|
|
|
def do_GET(self):
|
|
if not self._admit():
|
|
return
|
|
if self.path == "/server_info/":
|
|
# What the engine's router does with a trailing slash (Starlette's redirect_slashes):
|
|
# a 307 to the route it serves, named with the engine's own address.
|
|
self.send_response(307)
|
|
self.send_header("Location", "http://%s:%d/server_info" % self.server.server_address[:2])
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
return
|
|
# an engine that serves the spelling with a slash itself, without a redirect
|
|
if self.path.split("?")[0] in ("/server_info", "/get_server_info", "/get_server_info/"):
|
|
# What the real engine answers (checked on the reference box, 2026-09-24):
|
|
# its own serving key in clear, at the top and in every internal state; and
|
|
# its whole command line, key included, in launch_command (2026-10-03).
|
|
body = json.dumps({"api_key": "engine-K", "admin_api_key": "admin-K",
|
|
"ssl_keyfile_password": "pw-K",
|
|
"launch_command": "--api-key engine-K --model-path m "
|
|
"--admin-api-key admin-K "
|
|
"--ssl-keyfile-password pw-K",
|
|
"max_total_num_tokens": 1000, "served_model_name": "m",
|
|
"internal_states": [{"api_key": "engine-K",
|
|
"admin_api_key": "admin-K"}]}).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/plain")
|
|
self.send_header("Content-Length", "2")
|
|
self.end_headers()
|
|
self.wfile.write(b"OK")
|
|
|
|
|
|
_fresh = [0]
|
|
|
|
|
|
def fresh_proxy_module(upstream_port, keys_path=None, upstream_key=None):
|
|
"""Import the proxy with the environment the scenario calls for.
|
|
|
|
Module import is when the keys wall is built, so the scenario has to
|
|
exist before the exec, and the SystemExit of a refused start surfaces
|
|
right here: fail closed is observable at import, not only in a journal.
|
|
"""
|
|
_fresh[0] += 1
|
|
spec = importlib.util.spec_from_file_location(
|
|
"kproxy_keys_%d" % _fresh[0], REPO / "keepalive-proxy.py")
|
|
mod = importlib.util.module_from_spec(spec)
|
|
names = ("UPSTREAM", "QWEN38_CLIENT_KEYS_FILE", "QWEN38_UPSTREAM_API_KEY")
|
|
saved = [os.environ.get(k) for k in names]
|
|
os.environ["UPSTREAM"] = "http://127.0.0.1:%d" % upstream_port
|
|
if keys_path is None:
|
|
os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None)
|
|
else:
|
|
os.environ["QWEN38_CLIENT_KEYS_FILE"] = keys_path
|
|
if upstream_key is None:
|
|
os.environ.pop("QWEN38_UPSTREAM_API_KEY", None)
|
|
else:
|
|
os.environ["QWEN38_UPSTREAM_API_KEY"] = upstream_key
|
|
try:
|
|
spec.loader.exec_module(mod)
|
|
finally:
|
|
for key, value in zip(names, saved):
|
|
if value is 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
|
|
|
|
|
|
def post(port, path, token=None, body=None, extra=None):
|
|
headers = {"Content-Type": "application/json", **(extra or {})}
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
req = urllib.request.Request("http://127.0.0.1:%d%s" % (port, path), data=body or BODY, headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
def get(port, path):
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:%d%s" % (port, path), timeout=10) as r:
|
|
return r.status
|
|
except urllib.error.HTTPError as e:
|
|
return e.code
|
|
|
|
|
|
def call(port, method, path, token=None):
|
|
"""(status, body) of any method, with or without a bearer."""
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
data = BODY if method != "GET" else None
|
|
req = urllib.request.Request("http://127.0.0.1:%d%s" % (port, path), data=data,
|
|
headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
class ClientKeys(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
|
|
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
|
|
cls.eport = cls.engine.server_address[1]
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.engine.shutdown()
|
|
cls.engine.server_close()
|
|
|
|
def setUp(self):
|
|
Engine.require_key = None
|
|
Engine.last_auth = None
|
|
|
|
def keys_file(self, text):
|
|
fd, path = tempfile.mkstemp(suffix=".json", text=True)
|
|
with open(fd, "w") as f:
|
|
f.write(text)
|
|
self.addCleanup(os.unlink, path)
|
|
return path
|
|
|
|
def live(self, keys_path=None, upstream_key=None):
|
|
mod = fresh_proxy_module(self.eport, keys_path, upstream_key)
|
|
srv = mod.Server(("127.0.0.1", 0), mod.H)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
self.addCleanup(srv.shutdown)
|
|
self.addCleanup(srv.server_close)
|
|
deadline = time.time() + 10
|
|
while time.time() < deadline:
|
|
try:
|
|
socket.create_connection(("127.0.0.1", srv.server_address[1]), 0.5).close()
|
|
break
|
|
except OSError:
|
|
time.sleep(0.1)
|
|
return srv.server_address[1]
|
|
|
|
def test_the_wall_is_off_by_default_anonymous_still_relayed(self):
|
|
port = self.live()
|
|
status, _ = post(port, "/v1/chat/completions")
|
|
self.assertEqual(status, 200)
|
|
|
|
def test_unlisted_key_is_401_in_the_openai_dialect(self):
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
for tok in (None, "wrong"):
|
|
status, body = post(port, "/v1/chat/completions", tok)
|
|
self.assertEqual(status, 401)
|
|
self.assertIn("client key", json.loads(body)["error"]["message"])
|
|
|
|
def test_unlisted_key_is_401_in_the_anthropic_dialect(self):
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
status, body = post(port, "/v1/messages")
|
|
self.assertEqual(status, 401)
|
|
doc = json.loads(body)
|
|
self.assertEqual(doc["type"], "error")
|
|
self.assertEqual(doc["error"]["type"], "authentication_error")
|
|
|
|
def test_listed_key_is_200_and_the_label_rides_the_journal(self):
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
capture = io.StringIO()
|
|
real = sys.stderr
|
|
sys.stderr = capture
|
|
try:
|
|
for path in ("/v1/chat/completions", "/v1/messages"):
|
|
status, _ = post(port, path, "tok-alice")
|
|
self.assertEqual(status, 200)
|
|
finally:
|
|
sys.stderr = real
|
|
self.assertIn("key=alice", capture.getvalue())
|
|
|
|
def test_a_listed_key_never_names_the_engines_requests(self):
|
|
# SGLang aborts every request whose rid starts with one it aborts: a listed client naming rids "0" to "f",
|
|
# in a body or in the header, and leaving, ended every generation of the box, which no operator route of
|
|
# a listed key may do either (review, 2026-11-03)
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
body = json.dumps(dict(json.loads(BODY), rid="0")).encode()
|
|
for path in ("/v1/completions", "/v1/chat/completions"):
|
|
with self.subTest(path=path):
|
|
status, _ = post(port, path, "tok-alice", body=body, extra={"X-Override-Rid": "0"})
|
|
self.assertEqual(status, 200)
|
|
rid, header = Engine.last_rid
|
|
self.assertIsNone(rid, "no rid of the client's in the body")
|
|
self.assertNotEqual(header, "0", "nor in the header")
|
|
# every other form SGLang takes one in (security review, 2026-11-03): a key written with escapes,
|
|
# which the bytes do not show, a batch's list, /v1/responses' request_id, the Vertex route's parameters
|
|
forms = [("/v1/completions", b'{"model": "m", "prompt": "hi", "r\\u0069d": "0"}', lambda j: j.get("rid")),
|
|
("/invocations", b'{"model": "m", "messages": [], "\\u0072id": "0"}', lambda j: j.get("rid")),
|
|
("/generate", b'{"text": ["a", "b"], "rid": ["0", "1"]}', lambda j: j.get("rid")),
|
|
("/v1/responses", b'{"model": "m", "input": "hi", "request_id": "0"}', lambda j: j.get("request_id")),
|
|
("/v1/responses", b'{"model": "m", "input": "hi", "r\\u0065quest_id": "0"}',
|
|
lambda j: j.get("request_id")),
|
|
("/vertex_generate", b'{"instances": [{"text": "hi"}], "parameters": {"rid": "0"}}',
|
|
lambda j: (j.get("parameters") or {}).get("rid")),
|
|
# vLLM's: a body's request_id on chat and completions
|
|
("/v1/chat/completions", b'{"model": "m", "messages": [], "request_id": "0"}',
|
|
lambda j: j.get("request_id"))]
|
|
for path, raw, rid_of in forms:
|
|
with self.subTest(path=path, body=raw):
|
|
Engine.last_body = None
|
|
status, _ = post(port, path, "tok-alice", body=raw)
|
|
self.assertEqual(status, 200)
|
|
self.assertIsNotNone(Engine.last_body, "the request reached the engine")
|
|
self.assertIsNone(rid_of(Engine.last_body), f"the client's id reached the engine: {Engine.last_body}")
|
|
# vLLM's header
|
|
status, _ = post(port, "/v1/chat/completions", "tok-alice", extra={"X-Request-Id": "0"})
|
|
self.assertEqual(status, 200)
|
|
self.assertIsNone(Engine.last_request_id, "the client's X-Request-Id reached the engine")
|
|
# a body that may name it and cannot be read whole is refused, never sent as it came
|
|
deep = b'{"model": "m", "rid": "0", "x": ' + b"[" * 50000 + b"]" * 50000 + b"}"
|
|
Engine.last_body = None
|
|
status, out = post(port, "/v1/chat/completions", "tok-alice", body=deep)
|
|
self.assertEqual(status, 400, out[:200])
|
|
self.assertIsNone(Engine.last_body, "a body whose id could not be dropped reached the engine")
|
|
|
|
def test_the_scheme_is_read_in_any_case_as_the_engine_reads_it(self):
|
|
"""The wall read the scheme as "Bearer " only, where SGLang, vLLM's middleware and the
|
|
door without the wall take it in any case (RFC 9110, 11.1): a listed key sent as
|
|
"bearer <key>" got the wall's 401 (found in a cloud review, 2026-10-18)."""
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
|
|
def send(value):
|
|
req = urllib.request.Request("http://127.0.0.1:%d/v1/chat/completions" % port, data=BODY,
|
|
headers={"Content-Type": "application/json",
|
|
"Authorization": value})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return r.status
|
|
except urllib.error.HTTPError as e:
|
|
return e.code
|
|
|
|
for scheme in ("Bearer", "bearer", "BEARER", "bEaReR"):
|
|
self.assertEqual(send(scheme + " tok-alice"), 200, scheme)
|
|
# still a bearer of a listed key, or nothing: another scheme, or no key after it
|
|
for value in ("Token tok-alice", "Basic tok-alice", "bearer", "Bearer "):
|
|
self.assertEqual(send(value), 401, value)
|
|
|
|
def journal_of(self, port, token, path="/v1/chat/completions"):
|
|
capture, real = io.StringIO(), sys.stderr
|
|
sys.stderr = capture
|
|
try:
|
|
status, _ = post(port, path, token)
|
|
time.sleep(0.1)
|
|
finally:
|
|
sys.stderr = real
|
|
self.assertEqual(status, 200)
|
|
return [ln for ln in capture.getvalue().splitlines() if "[proxy] 127.0.0.1:" in ln]
|
|
|
|
def test_every_line_of_a_labelled_request_names_the_client(self):
|
|
"""The label was added by the wall, after the line that opens the request, so that
|
|
line named a peer no later line did (found in review, 2026-09-24)."""
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
lines = self.journal_of(port, "tok-alice")
|
|
self.assertGreaterEqual(len(lines), 2, lines)
|
|
self.assertTrue(any(" -> POST " in ln for ln in lines), lines)
|
|
peers = {ln.split("[proxy] ", 1)[1].split(" key=")[0] for ln in lines}
|
|
self.assertEqual(len(peers), 1, lines)
|
|
for ln in lines:
|
|
self.assertIn(" key=alice ", ln)
|
|
|
|
def test_the_cockpit_reads_a_labelled_request_to_its_end(self):
|
|
"""Every such request stayed "in flight" in the cockpit, then "no end logged":
|
|
its end line did not match the peer its first line did."""
|
|
sys.path.insert(0, str(REPO / "dashboard"))
|
|
import lifecycle
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
lines = self.journal_of(port, "tok-alice")
|
|
rows = lifecycle.parse_feed("\n".join("2026-09-24T12:00:00+02:00 gx10 python3[1]: " + ln
|
|
for ln in lines))
|
|
self.assertEqual(len(rows), 1, rows)
|
|
self.assertEqual((rows[0]["outcome"], rows[0]["kind"]), ("ok non-sse", "ok"), rows)
|
|
|
|
def test_a_label_is_one_word_on_the_line(self):
|
|
"""A space in a label split the peer the cockpit matches on; a newline wrote a
|
|
line of the label's choosing into the journal."""
|
|
port = self.live(self.keys_file(json.dumps({"tok-b": "my laptop\n[proxy] forged"})))
|
|
lines = self.journal_of(port, "tok-b")
|
|
self.assertTrue(lines)
|
|
for ln in lines:
|
|
self.assertIn(" key=my_laptop_[proxy]_forged ", ln)
|
|
self.assertFalse(any(ln.startswith("[proxy] forged") for ln in lines))
|
|
|
|
def test_an_escaped_path_does_not_walk_past_the_wall(self):
|
|
"""SGLang decodes percent-escapes before it routes (checked live: GET /%76%31/models
|
|
answers with the model list), so "/%76%31/chat/completions" reached the engine while
|
|
this proxy's checks, which all match the raw string, saw a path that was not /v1/.
|
|
Without a listed key, and with the engine's own key attached by the proxy."""
|
|
Engine.require_key = "engine-K"
|
|
Engine.last_auth = None
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
for path in ("/v1/chat/completions", "/%76%31/chat/completions",
|
|
"/v1/%63%68%61%74/completions", "/%76%31/chat/completions?stream=false"):
|
|
status, body = post(port, path)
|
|
self.assertEqual(status, 401, (path, body))
|
|
self.assertIn("client key", json.loads(body)["error"]["message"])
|
|
self.assertIsNone(Engine.last_auth, "not one of them reached the engine")
|
|
status, _ = post(port, "/%76%31/chat/completions", "tok-alice")
|
|
self.assertEqual(status, 200, "a listed key still gets through the decoded path")
|
|
self.assertEqual(Engine.last_path, "/v1/chat/completions",
|
|
"and the engine is sent the path this proxy checked")
|
|
|
|
def test_a_path_that_hides_a_query_separator_is_refused(self):
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
status, body = post(port, "/v1/chat/completions%3Fstream=true", "tok-alice")
|
|
self.assertEqual(status, 400, body)
|
|
self.assertIn("encoded query", json.loads(body)["error"]["message"])
|
|
|
|
def test_health_stays_open_without_a_key(self):
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
self.assertEqual(get(port, "/health"), 200)
|
|
|
|
# Every route the engine serves, not only POSTs under /v1/. Until v1.18.7 the wall
|
|
# only looked at POST /v1/..., while the proxy attached the engine's own key to
|
|
# everything it relayed: with no key at all, GET /server_info, POST /generate,
|
|
# /flush_cache and /abort_request all reached the engine as the engine (found in
|
|
# review, 2026-09-24).
|
|
ROUTES = (("GET", "/v1/models"), ("GET", "/server_info"), ("GET", "/get_server_info"),
|
|
("GET", "/metrics"), ("POST", "/generate"), ("POST", "/flush_cache"),
|
|
("POST", "/abort_request"), ("POST", "/invocations"), ("PUT", "/v1/chat/completions"))
|
|
|
|
def test_every_route_but_health_needs_a_listed_key(self):
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
for method, path in self.ROUTES:
|
|
for tok in (None, "wrong", "engine-K"):
|
|
with self.subTest(method=method, path=path, token=tok):
|
|
Engine.last_auth = None
|
|
status, body = call(port, method, path, tok)
|
|
self.assertEqual(status, 401, body)
|
|
self.assertIn("client key", body.decode())
|
|
self.assertIsNone(Engine.last_auth, "the engine was never reached")
|
|
|
|
# The engine's operator routes, which the wall signed with the engine's key for any listed
|
|
# client until 2026-10-16: weights reloaded, updated or checked, the profiler, pause,
|
|
# slow_down, internal state, the update groups, the remote weight transfer.
|
|
OPERATOR_ROUTES = (("POST", "/flush_cache"), ("POST", "/abort_request"),
|
|
("POST", "/update_weights_from_disk"), ("POST", "/update_weights_from_tensor"),
|
|
("POST", "/init_weights_update_group"), ("POST", "/begin_weight_update"),
|
|
("POST", "/send_weights_to_remote_instance"), ("POST", "/weights_checker"),
|
|
("POST", "/start_profile"), ("POST", "/slow_down"),
|
|
("POST", "/set_internal_state"), ("POST", "/pause_generation"),
|
|
("POST", "/release_memory_occupation"), ("GET", "/get_weights_by_name"),
|
|
("PUT", "/configure_logging"), ("POST", "/load_lora_adapter"))
|
|
|
|
def test_a_listed_key_still_reaches_every_client_route(self):
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
for method, path in self.ROUTES:
|
|
if (method, path) in self.OPERATOR_ROUTES:
|
|
continue
|
|
with self.subTest(method=method, path=path):
|
|
status, _ = call(port, method, path, "tok-alice")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(Engine.last_auth, "Bearer engine-K")
|
|
|
|
def test_a_listed_key_never_reaches_an_operator_route(self):
|
|
"""A listed key is a client: behind the wall the engine sees the engine's key, so a
|
|
relayed operator route would have been the operator's own call (2026-10-16)."""
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
for method, path in self.OPERATOR_ROUTES:
|
|
with self.subTest(method=method, path=path):
|
|
Engine.last_auth = None
|
|
status, body = call(port, method, path, "tok-alice")
|
|
self.assertEqual(status, 403, body)
|
|
self.assertIn(path, json.loads(body)["error"]["message"])
|
|
self.assertIsNone(Engine.last_auth, "the engine was never reached")
|
|
# and the routes a client uses are untouched: generation in both dialects, counting
|
|
for path in ("/v1/chat/completions", "/v1/messages", "/v1/messages/count_tokens",
|
|
"/generate", "/tokenize"):
|
|
with self.subTest(path=path):
|
|
status, _ = call(port, "POST", path, "tok-alice")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(Engine.last_auth, "Bearer engine-K")
|
|
|
|
def test_a_listed_key_reaches_the_reading_routes_of_the_other_dialects(self):
|
|
"""Ollama's /api/tags and /api/show, SageMaker's /ping and the root only read, in SGLang
|
|
v0.5.21 (a model list, a model card, an empty 200, "is running"), and the wall refused
|
|
them as operator routes (found in review, 2026-10-17)."""
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
for method, path in (("GET", "/ping"), ("GET", "/api/tags"), ("POST", "/api/show"), ("GET", "/")):
|
|
with self.subTest(method=method, path=path):
|
|
Engine.last_auth = None
|
|
status, body = call(port, method, path, "tok-alice")
|
|
self.assertEqual(status, 200, body)
|
|
self.assertEqual(Engine.last_auth, "Bearer engine-K")
|
|
# /encode and /classify run the model outside the size guard; /v1/embeddings and
|
|
# /v1/classify, which it guards, are a client's way there
|
|
for path in ("/encode", "/classify"):
|
|
with self.subTest(path=path):
|
|
Engine.last_auth = None
|
|
status, body = call(port, "POST", path, "tok-alice")
|
|
self.assertEqual(status, 403, body)
|
|
self.assertIsNone(Engine.last_auth)
|
|
|
|
def test_server_info_never_carries_the_engine_key_through_the_proxy(self):
|
|
"""/server_info returns the engine's serving key in clear. Behind the wall that key
|
|
is exactly what a named client must not learn; without the wall the caller already
|
|
holds it. Either way the relayed answer has no reason to carry it."""
|
|
Engine.require_key = "engine-K"
|
|
walled = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
open_ = self.live()
|
|
for port, tok in ((walled, "tok-alice"), (open_, "engine-K")):
|
|
for path in ("/server_info", "/get_server_info"):
|
|
with self.subTest(port=port, path=path):
|
|
status, body = call(port, "GET", path, tok)
|
|
self.assertEqual(status, 200)
|
|
self.assertNotIn(b"engine-K", body)
|
|
self.assertNotIn(b"admin-K", body)
|
|
self.assertNotIn(b"pw-K", body)
|
|
doc = json.loads(body)
|
|
self.assertEqual(doc["max_total_num_tokens"], 1000, "the rest is intact")
|
|
self.assertEqual(doc["launch_command"],
|
|
"--api-key <masked> --model-path m --admin-api-key "
|
|
"<masked> --ssl-keyfile-password <masked>")
|
|
|
|
def test_server_info_is_masked_however_the_route_is_spelled(self):
|
|
"""The masking keyed on the exact spelling and the proxy followed the engine's
|
|
redirects: /server_info/ came back 307 to /server_info, the proxy followed it with the
|
|
engine's key, and relayed the answer unmasked (2026-10-16). A redirect is now relayed,
|
|
pointing back at the proxy, and a slash the engine serves is masked. Behind the wall a
|
|
listed key does not reach these spellings at all (a 403 since the same day); the
|
|
answer of either mode carries no key."""
|
|
Engine.require_key = "engine-K"
|
|
walled = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
open_ = self.live()
|
|
for port, tok in ((walled, "tok-alice"), (open_, "engine-K")):
|
|
for path in ("/server_info/", "/get_server_info/"):
|
|
with self.subTest(port=port, path=path):
|
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
conn.request("GET", path, headers={"Authorization": "Bearer " + tok})
|
|
r = conn.getresponse()
|
|
body = r.read()
|
|
conn.close()
|
|
self.assertNotIn(b"engine-K", body)
|
|
self.assertNotIn(b"admin-K", body)
|
|
if port == walled:
|
|
self.assertEqual(r.status, 403, body)
|
|
elif path == "/server_info/":
|
|
self.assertEqual(r.status, 307, body)
|
|
self.assertEqual(r.getheader("Location"), "/server_info")
|
|
else:
|
|
self.assertEqual(r.status, 200, body)
|
|
self.assertEqual(json.loads(body)["max_total_num_tokens"], 1000)
|
|
|
|
def test_a_key_is_masked_in_every_form_a_command_line_gives_it(self):
|
|
"""launch_command (v6.32) is one shape; the masking does not depend on it."""
|
|
mod = fresh_proxy_module(1, upstream_key="engine-key-long")
|
|
doc = {"a": "--api-key=k1 --api-key 'k 2' --api-key \"k 3\" --admin-api-key\tk4",
|
|
"b": ["x engine-key-long y", {"c": "--ssl-keyfile-password=pw --port 30000"}],
|
|
"n": 42}
|
|
self.assertEqual(mod.mask_secrets(doc),
|
|
{"a": "--api-key=<masked> --api-key <masked> --api-key <masked> "
|
|
"--admin-api-key\t<masked>",
|
|
"b": ["x <masked> y", {"c": "--ssl-keyfile-password=<masked> --port 30000"}],
|
|
"n": 42})
|
|
|
|
def test_a_key_too_short_to_be_real_is_not_looked_for_by_value(self):
|
|
mod = fresh_proxy_module(1, upstream_key="mod")
|
|
self.assertEqual(mod.mask_secrets({"model_path": "org/model", "cmd": "--api-key mod"}),
|
|
{"model_path": "org/model", "cmd": "--api-key <masked>"})
|
|
|
|
def test_a_doubly_encoded_path_is_refused_in_both_modes(self):
|
|
"""canonical_path decodes once and SGLang decodes again, so /%2576%2531/... became
|
|
/%76%31/... here (not /v1/, so no wall and no guard) and /v1/... in the engine."""
|
|
Engine.require_key = "engine-K"
|
|
walled = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
open_ = self.live(upstream_key="engine-K")
|
|
for port, tok in ((walled, None), (walled, "tok-alice"), (open_, "engine-K")):
|
|
for path in ("/%2576%2531/chat/completions", "/v1/%2563hat/completions",
|
|
"/%252576%252531/models"):
|
|
with self.subTest(port=port, token=tok, path=path):
|
|
Engine.last_auth = None
|
|
status, body = call(port, "POST", path, tok)
|
|
self.assertEqual(status, 400, body)
|
|
self.assertIsNone(Engine.last_auth, "the engine was never reached")
|
|
|
|
def test_upstream_key_admits_named_client_as_engine_key(self):
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'), upstream_key="engine-K")
|
|
status, _ = post(port, "/v1/chat/completions", "tok-alice")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(Engine.last_auth, "Bearer engine-K")
|
|
|
|
def test_verbatim_without_upstream_key_named_client_meets_engine_check(self):
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(self.keys_file('{"tok-alice":"alice"}'))
|
|
status, body = post(port, "/v1/chat/completions", "tok-alice")
|
|
self.assertEqual(status, 401)
|
|
self.assertNotIn("client key", json.loads(body)["error"]["message"])
|
|
self.assertEqual(Engine.last_auth, "Bearer tok-alice")
|
|
|
|
def test_upstream_key_stays_dormant_when_wall_off(self):
|
|
Engine.require_key = "engine-K"
|
|
port = self.live(upstream_key="engine-K")
|
|
status, _ = post(port, "/v1/chat/completions", "engine-K")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(Engine.last_auth, "Bearer engine-K")
|
|
|
|
def test_an_unreadable_keys_file_says_so(self):
|
|
"""docs/clients.md installed the file owned by root until v1.18.7; the proxy runs as
|
|
the user and reads it itself, so it refused to start saying "missing, malformed or
|
|
empty" about a file that was there and well formed."""
|
|
path = self.keys_file('{"tok-alice":"alice"}')
|
|
os.chmod(path, 0)
|
|
self.addCleanup(os.chmod, path, 0o600)
|
|
err = io.StringIO()
|
|
real, sys.stderr = sys.stderr, err
|
|
try:
|
|
with self.assertRaises(SystemExit):
|
|
fresh_proxy_module(self.eport, path)
|
|
finally:
|
|
sys.stderr = real
|
|
self.assertIn("not readable by this user", err.getvalue())
|
|
|
|
def test_missing_empty_broken_keys_files_refuse_to_be_imported(self):
|
|
for path, text in ((None, "/nonexistent/keys.json"), ("{}", "{}"), ("{not json", "{not json")):
|
|
real = "/nonexistent/keys.json" if path is None else self.keys_file(text)
|
|
with self.assertRaises(SystemExit, msg=repr(text)):
|
|
fresh_proxy_module(self.eport, real)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|