mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
A key header of 64 KB of "\n" was read in 8.7 s under the interpreter's lock, with no key, every stream of the box still: it is refused at once. The red banner of a start that barely moves is no longer drawn again at each reading, its Stop with it. The words of a box with no lane name what starts one, and a start's length by lane. llama-server's own /chat/completions gets a chat keepalive. The relay's sign-in page names where this browser reaches the cockpit, through a tunnel or TLS. A body the cockpit does not read is never its connection's next request. A chunked body shows its size in Traffic. The other box of a pair is told before a silent stream is cut, and binds nothing for it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
222 lines
10 KiB
Python
222 lines
10 KiB
Python
"""The key a request brings, wherever its client puts it, and what a refused one is told (v6.63).
|
|
|
|
Anthropic clients send a key in x-api-key: the engines read Authorization alone, so the right key came
|
|
back 401 (anthropic 1.12.1, the AI SDK's provider, Claude Code with ANTHROPIC_API_KEY, 2026-11-30;
|
|
anthropic 2.14.0 sends Authorization). And every refusal was {"error":"Unauthorized"}, whatever was wrong
|
|
with the key."""
|
|
import http.server
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
KEY = "k3y-of-this-test-0123456789"
|
|
BODY = json.dumps({"model": "m", "max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]}).encode()
|
|
|
|
|
|
class Engine(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
seen = []
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def answer(self):
|
|
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
self.seen.append((self.path, dict(self.headers.items()), raw))
|
|
out = b'{"data": [{"id": "m", "owned_by": "sglang"}]}'
|
|
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)
|
|
|
|
do_GET = do_POST = answer
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
WALL = None
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
saved = dict(os.environ)
|
|
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
|
|
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
|
|
cls.engine.daemon_threads = True
|
|
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.engine.server_close)
|
|
cls.addClassCleanup(cls.engine.shutdown)
|
|
os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None)
|
|
if cls.WALL:
|
|
fd, path = tempfile.mkstemp(suffix=".json", text=True)
|
|
with open(fd, "w") as f:
|
|
json.dump(cls.WALL, f)
|
|
cls.addClassCleanup(os.unlink, path)
|
|
os.environ["QWEN38_CLIENT_KEYS_FILE"] = path
|
|
os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", CLIENT_IO_S="5", PROMPT_CEILING_TOKENS="0",
|
|
PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY=KEY)
|
|
spec = importlib.util.spec_from_file_location(f"kp_keys_{time.time_ns()}", REPO / "keepalive-proxy.py")
|
|
cls.mod = importlib.util.module_from_spec(spec)
|
|
sys.argv = ["keepalive-proxy.py"]
|
|
spec.loader.exec_module(cls.mod)
|
|
cls.journal = []
|
|
cls.mod.log = cls.journal.append
|
|
cls.mod._SERVED.update(names=("m",), engine="sglang", ts=time.time())
|
|
cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
|
|
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.proxy.server_close)
|
|
cls.addClassCleanup(cls.proxy.shutdown)
|
|
|
|
def setUp(self):
|
|
Engine.seen.clear()
|
|
self.journal.clear()
|
|
|
|
def ask(self, *headers, path="/v1/messages", method="POST", body=BODY):
|
|
"""(status, the answer's headers, its body)"""
|
|
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
|
|
try:
|
|
lines = [f"{method} {path} HTTP/1.1", "Host: p", "Content-Type: application/json", *headers]
|
|
if method == "POST":
|
|
lines.append(f"Content-Length: {len(body)}")
|
|
s.sendall("\r\n".join(lines).encode("latin-1") + b"\r\n\r\n" + (body if method == "POST" else b""))
|
|
got = b""
|
|
while True:
|
|
c = s.recv(65536)
|
|
if not c:
|
|
break
|
|
got += c
|
|
finally:
|
|
s.close()
|
|
head, _, rest = got.partition(b"\r\n\r\n")
|
|
lines = head.decode().split("\r\n")
|
|
return (int(lines[0].split(" ")[1]), {k.lower(): v.strip() for k, _, v in (ln.partition(":") for ln in lines[1:])}, rest)
|
|
|
|
def to_the_engine(self):
|
|
_, headers, _ = next(s for s in Engine.seen if s[0] in ("/v1/messages", "/v1/chat/completions"))
|
|
return {k.lower(): v for k, v in headers.items()}
|
|
|
|
|
|
class AKeyInXApiKey(Base):
|
|
def test_it_is_the_bearer_it_stands_for(self):
|
|
for header in (f"x-api-key: {KEY}", f"X-Api-Key: {KEY} ", f"X-API-KEY: {KEY}\r\nAuthorization: "):
|
|
for path in ("/v1/messages", "/v1/chat/completions"):
|
|
with self.subTest(header=header, path=path):
|
|
Engine.seen.clear()
|
|
self.assertEqual(self.ask(header, path=path)[0], 200)
|
|
got = self.to_the_engine()
|
|
self.assertEqual(got["authorization"], f"Bearer {KEY}")
|
|
self.assertNotIn("x-api-key", got)
|
|
|
|
def test_on_a_get(self):
|
|
self.assertEqual(self.ask(f"x-api-key: {KEY}", path="/v1/models", method="GET")[0], 200)
|
|
|
|
def test_another_key_is_refused_and_the_engine_not_asked(self):
|
|
for header in ("x-api-key: wrong", f"x-api-key: {KEY}x", "x-api-key: ", f"x-api-key: Bearer {KEY}"):
|
|
self.assertEqual(self.ask(header)[0], 401, header)
|
|
self.assertEqual(Engine.seen, [])
|
|
|
|
def test_the_authorization_header_decides_when_there_is_one(self):
|
|
self.assertEqual(self.ask("Authorization: Bearer wrong", f"x-api-key: {KEY}")[0], 401)
|
|
self.assertEqual(self.ask(f"Authorization: Bearer {KEY}", "x-api-key: wrong")[0], 200)
|
|
self.assertNotIn("x-api-key", self.to_the_engine())
|
|
|
|
def test_the_operator_s_stop_still_needs_its_authorization(self):
|
|
self.assertEqual(self.ask(f"x-api-key: {KEY}", path="/proxy/stop", body=b"{}")[0], 401)
|
|
self.assertEqual(self.ask(f"Authorization: Bearer {KEY}", path="/proxy/stop", body=b"{}")[0], 200)
|
|
|
|
|
|
class AListedKeyInXApiKey(Base):
|
|
WALL = {"tok-alice": "alice"}
|
|
|
|
def test_it_names_its_client_and_the_engine_gets_its_own_key(self):
|
|
self.assertEqual(self.ask("x-api-key: tok-alice")[0], 200)
|
|
got = self.to_the_engine()
|
|
self.assertEqual(got["authorization"], f"Bearer {KEY}")
|
|
self.assertNotIn("x-api-key", got)
|
|
self.assertTrue([ln for ln in self.journal if "key=alice" in ln and "-> POST" in ln], self.journal)
|
|
|
|
def test_one_not_listed_is_refused_the_engine_s_own_included(self):
|
|
for value in ("tok-mallory", KEY, "tok-alice x"):
|
|
status, _, body = self.ask(f"x-api-key: {value}")
|
|
self.assertEqual(status, 401, value)
|
|
self.assertIn("client key", json.loads(body)["error"]["message"])
|
|
self.assertEqual(Engine.seen, [])
|
|
|
|
def test_it_reaches_no_operator_route_and_names_no_request(self):
|
|
self.assertEqual(self.ask("x-api-key: tok-alice", path="/flush_cache")[0], 403)
|
|
self.ask("x-api-key: tok-alice", "x-override-rid: 0")
|
|
self.assertNotEqual(self.to_the_engine().get("x-override-rid"), "0")
|
|
|
|
|
|
class ARefusalSaysWhatToSend(Base):
|
|
def refusal(self, *headers, path="/v1/chat/completions"):
|
|
self.journal.clear()
|
|
status, head, body = self.ask(*headers, path=path)
|
|
self.assertEqual(status, 401)
|
|
self.assertEqual(head.get("www-authenticate"), "Bearer")
|
|
self.assertNotIn(KEY.encode(), body, "a byte of the key")
|
|
self.assertNotIn(KEY, "\n".join(self.journal))
|
|
self.assertEqual(Engine.seen, [])
|
|
return json.loads(body)
|
|
|
|
def test_a_long_value_is_refused_at_once(self):
|
|
"""Its reading cost the square of its length under the interpreter's lock: 64 KB of "\\n" sent with no key held
|
|
every stream of the box for 8.7 s (found in review, 2026-11-30)."""
|
|
for value in ("Bearer " + "\\n" * 30_000 + "x", "Bearer " + "\\n" * 30_000, "'" * 60_000, "Bearer " + " " * 60_000 + "x"):
|
|
for name in ("Authorization", "x-api-key"):
|
|
t0 = time.monotonic()
|
|
why = self.mod.key_refusal({name: value}, KEY)
|
|
self.assertLess(time.monotonic() - t0, 0.2, value[:20])
|
|
self.assertNotIn(KEY, why)
|
|
# what a person wraps it in is still read
|
|
self.assertIn("the key is this box's", self.mod.key_refusal({"Authorization": f'Bearer "{KEY}"\\n'}, KEY))
|
|
|
|
def test_no_key(self):
|
|
msg = self.refusal()["error"]["message"]
|
|
for words in ("carries none", "Authorization: Bearer <key>", "x-api-key", "~/.config/qwen38/api-key"):
|
|
self.assertIn(words, msg)
|
|
|
|
def test_the_right_key_in_a_wrong_header(self):
|
|
for header in (f'Authorization: Bearer "{KEY}"', f"Authorization: Bearer '{KEY}'", f"Authorization: Bearer {KEY}",
|
|
f"Authorization: {KEY}", f"Authorization: Bearer {KEY}\\n", f"Authorization: Bearer\t{KEY}",
|
|
f"Authorization: Bearer <{KEY}>", f'x-api-key: "{KEY}"', f"x-api-key: Bearer {KEY}"):
|
|
with self.subTest(header=header):
|
|
self.assertIn("the key is this box's, but the header around it is not", self.refusal(header)["error"]["message"])
|
|
|
|
def test_a_header_of_another_form(self):
|
|
for header in ("Authorization: Token abcdef", "Authorization: Basic dXNlcjpwYXNz", "Authorization: Bearer",
|
|
"Authorization: Bearer a b"):
|
|
with self.subTest(header=header):
|
|
msg = self.refusal(header)["error"]["message"]
|
|
self.assertIn("not of the form Bearer <key>", msg)
|
|
self.assertNotIn("abcdef", msg)
|
|
self.assertNotIn("dXNlcjpwYXNz", msg)
|
|
|
|
def test_another_key(self):
|
|
for header in ("Authorization: Bearer sk-some-other", "x-api-key: sk-some-other"):
|
|
msg = self.refusal(header)["error"]["message"]
|
|
self.assertIn("not this box's", msg)
|
|
self.assertNotIn("sk-some-other", msg)
|
|
|
|
def test_each_dialect_reads_it(self):
|
|
openai = self.refusal()["error"]
|
|
self.assertEqual((openai["type"], openai["code"], openai["param"]), ("invalid_request_error", "invalid_api_key", None))
|
|
for path in ("/v1/messages", "/v1/messages/count_tokens"):
|
|
doc = self.refusal(path=path)
|
|
self.assertEqual((doc["type"], doc["error"]["type"]), ("error", "authentication_error"))
|
|
self.assertIn("carries none", doc["error"]["message"])
|
|
detail = self.refusal(path="/v1/systemone")["detail"]
|
|
self.assertEqual(detail["error_type"], "engine_error")
|
|
self.assertIn("carries none", detail["message"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|