proxy v6.63: a 401 says what is wrong with the key and where the right one is

Every refused key was {"error":"Unauthorized"}: none sent, another box's,
one with quotes or two spaces, one under another scheme. Claude Code showed
"Failed to authenticate. API Error: 401 {"error":"Unauthorized"}", opencode
"Error: Unauthorized" (2026-11-30). The answer names the cause and the next
step, in each route's dialect, with WWW-Authenticate: Bearer, and never a byte
of the key nor of what was sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Hasan BasbunarandClaude Opus 5.5 committed 2026-11-30 09:33:19 +01:00
1 parent a5a4deb310
commit 61ec37463e
5 files changed
+98 -22

No files matched your search

+41 -18
View File
@@ -1355,8 +1355,38 @@ CLIENT_ROUTES = SERVER_INFO_ROUTES | frozenset({
# generation on an idle engine and was relayed from the network with no key (D02 of the
# 2026-10-24 security review).
ENGINE_OPEN_ROUTES = frozenset({"/health", "/ready", "/metrics"})
# The engine's own refusal, byte for byte, so a client gets the answer it always got.
ENGINE_401_BODY = b'{"error":"Unauthorized"}'
# Where the person reading a refusal finds the key. The refusal was the engine's own until v6.62,
# {"error":"Unauthorized"}, whatever was wrong: Claude Code showed "Failed to authenticate. API Error:
# 401 {"error":"Unauthorized"}" and opencode "Error: Unauthorized" for a key of another box, one sent
# with quotes and one sent in x-api-key alike (2026-11-30).
KEY_WHERE = "The key is on the box, in ~/.config/qwen38/api-key, and in its cockpit (Now, Connect a client)."
def key_refusal(headers, key):
"""Why the key a request carries is refused, and what to send instead. Never a byte of the key, nor
of what was sent: that a header holds the right key spelled wrong is said to whoever sent it only,
who has it."""
value = (headers.get("Authorization") or "").strip(" \t") or (headers.get("x-api-key") or "").strip(" \t")
if not value:
return ("this port needs the box's API key, and the request carries none. Send it as Authorization: "
f"Bearer <key>, or as x-api-key: <key>. {KEY_WHERE}")
bare = value[6:] if value[:6].lower() == "bearer" else value
bare = re.sub(r"(?:\\[nrt])+$", "", bare.strip(" \t\"'`<>")).strip(" \t\"'`<>")
if hmac.compare_digest(bare.encode("utf-8", "replace"), key.encode("utf-8", "replace")):
return ("the key is this box's, but the header around it is not. Send exactly Authorization: Bearer <key>: "
"one space, no quotes, nothing after it")
if headers.get("Authorization") and not re.match(r"(?i)bearer [^ ]+$", value):
return (f"the Authorization header is not of the form Bearer <key>. {KEY_WHERE}")
return f"the key sent is not this box's (another box's, or one from before a new installation?). {KEY_WHERE}"
def key_error(route, msg):
"""A 401's body in its route's dialect."""
msg = "keepalive-proxy: " + msg
if route.startswith("/v1/messages"):
return json.dumps({"type": "error", "error": {"type": "authentication_error", "message": msg}}).encode()
return json.dumps({"error": {"message": msg, "type": "invalid_request_error", "param": None,
"code": "invalid_api_key"}}).encode()
def engine_admits(authorization, key):
@@ -9595,12 +9625,9 @@ class H(BaseHTTPRequestHandler):
self._done("403 operator route")
return True
log(f"{self._peer} REFUSED unknown client key on {route}")
err = ({"type": "error", "error": {"type": "authentication_error",
"message": "keepalive-proxy: missing or unknown client key"}}
if route.startswith("/v1/messages") else
{"error": {"type": "invalid_request",
"message": "keepalive-proxy: missing or unknown client key"}})
self._plain(401, {"Content-Type": "application/json"}, json.dumps(err).encode())
self._plain(401, {"Content-Type": "application/json", "WWW-Authenticate": "Bearer"},
key_error(route, "missing or unknown client key. This box knows its clients by their keys: send the "
"one its operator gave you, as Authorization: Bearer <key> or x-api-key: <key>"))
self._done("401 unknown client key")
return True
@@ -9628,19 +9655,15 @@ class H(BaseHTTPRequestHandler):
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."""
"""A 401 in the route's dialect, or in its own envelope for System One, with the error_type a
key the engine refused came back with there before the door."""
why = key_refusal(self.headers, _door_key() or "")
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()
f"keepalive-proxy: {why}. Nothing was sent to the engine (HTTP 401)"}}).encode()
else:
body = ENGINE_401_BODY
self._plain(401, {"Content-Type": "application/json"}, body)
body = key_error(route, why)
self._plain(401, {"Content-Type": "application/json", "WWW-Authenticate": "Bearer"}, body)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 30001
+2 -1
View File
@@ -203,7 +203,8 @@ class TheDoor(unittest.TestCase):
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(json.loads(raw)["error"]["code"], "invalid_api_key", raw[:200])
self.assertNotIn(KEY.encode(), raw)
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):
+50
View File
@@ -155,5 +155,55 @@ class AListedKeyInXApiKey(Base):
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_no_key(self):
msg = self.refusal()["error"]["message"]
for words in ("carries none", "Authorization: Bearer <key>", "x-api-key", "~/.config/qwen38/api-key", "cockpit"):
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()
+3 -2
View File
@@ -240,11 +240,12 @@ class LlamaCppGuard(unittest.TestCase):
self.assertEqual(st, 200, out[:120])
self.assertEqual(Engine.auths[-1], "Bearer test-key")
# a wrong key under any spelling stays refused at the door, before the relay: the door's own body,
# SGLang's, and not the engine's "Invalid API Key"
# and not the engine's "Invalid API Key"
st, out = self.post("/v1/chat/completions",
{"model": SERVED, "messages": [{"role": "user", "content": "hi"}]},
auth="bearer wrong")
self.assertEqual((st, out), (401, self.mod.ENGINE_401_BODY))
self.assertEqual(st, 401)
self.assertIn("not this box's", json.loads(out)["error"]["message"])
self.assertEqual(Engine.generated, ["/v1/chat/completions"], "only the admitted one reached the engine")
def test_a_conversation_id_never_reaches_the_engine(self):
+2 -1
View File
@@ -11,6 +11,7 @@ The same holds for the 401 the proxy answers since v6.34 when a request does not
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 json
import os
import pathlib
import shutil
@@ -85,7 +86,7 @@ class TheRefusalArrives(unittest.TestCase):
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"}')
self.assertIn("carries none", json.loads(r.read())["error"]["message"])
finally:
c.close()