llm-host/tests/test_proxy.py
neil c8b70afdbf Split the internet upgrades: API-only tunnel, OIDC, authenticator codes, expose-dashboard
install-newt now sets up the tunnel for the API only; the dashboard stays on the LAN.
Dashboard sign-in is its own step: install-oidc (the OIDC flow, split out) or install-otp,
which pairs authenticator apps with a QR code in the terminal (stdlib QR encoder, TOTP per
RFC 6238) so a code also opens the dashboard, with replay and lockout rules.
expose-dashboard walks through publishing the dashboard, only after install-newt, and
warns while it's protected by the API key alone; with codes it offers to switch the key off
for the dashboard. Each install-* has a remove-*.

Also opencode-install.sh: a standalone script, fetched from the repo, that installs opencode
if needed, saves the API key to a 0600 file and adds the provider to opencode.json for new
and existing configs. /v1/models reports whether the model reasons, for that script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:56:54 -08:00

219 lines
10 KiB
Python

"""Proxy tests: the model name a client asks for must be honoured or refused, never ignored."""
import json, threading, urllib.error, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
from llmhost.backends import proxy
harness.guard(paths, ROOT)
SERVED = "ornith-1.5-9b"
REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit"
KEY = "sk-test-key"
seen = [] # bodies the inner (fake mlx_lm / vLLM) server received
auths = [] # the Authorization header each of them came with
check = harness.Checks()
class Inner(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a): pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
try: seen.append(json.loads(raw or b"{}"))
except ValueError: seen.append(None)
auths.append(self.headers.get("Authorization"))
if seen[-1] and seen[-1].get("stream"):
# vLLM with speculative decoding: one chunk can carry several tokens, so only
# the closing usage chunk has the true count.
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for text in ("Hello", " there, how", " are you"):
self.wfile.write(b"data: " + json.dumps({"choices": [{"index": 0, "delta": {"content": text}}]}).encode() + b"\n\n")
self.wfile.write(b"data: " + json.dumps({"choices": [], "usage": {
"prompt_tokens": 30, "completion_tokens": 7, "total_tokens": 37,
"prompt_tokens_details": {"cached_tokens": 20}}}).encode() + b"\n\n")
self.wfile.write(b"data: [DONE]\n\n")
self.close_connection = True
return
body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model",
"created": 0, "choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "pong"}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).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)
def serve(handler, port):
srv = ThreadingHTTPServer(("127.0.0.1", port), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
INNER, OUTER = 18231, 18232
serve(Inner, INNER)
stats = proxy.Stats()
serve(proxy.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
def post(model, key=KEY, path="/v1/chat/completions", port=None, raw_reply=False, **extra):
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4, **extra}
if model is not None:
body["model"] = model
req = urllib.request.Request(f"http://127.0.0.1:{port or OUTER}{path}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {key}"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=20) as r:
data = r.read()
return r.status, (data if raw_reply else json.loads(data or b"{}"))
except urllib.error.HTTPError as e:
try: return e.code, json.loads(e.read() or b"{}")
except ValueError: return e.code, {}
print("\n1. the loaded model is accepted")
seen.clear()
code, body = post(SERVED)
check("200", code == 200, code)
check("answered", body.get("choices", [{}])[0].get("message", {}).get("content") == "pong", body)
check("forwarded as default_model (mlx_lm must not try to load by name)",
seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
print("\n2. the repo id is accepted as an alias")
check("200", post(REPO)[0] == 200)
print("\n3. case differences are accepted")
check("200", post(SERVED.upper())[0] == 200)
print("\n4. no model named -> the loaded one")
check("200 when absent", post(None)[0] == 200)
check("200 when empty", post("")[0] == 200)
check("200 when blank", post(" ")[0] == 200)
check.section("4b. the stable alias always means whatever is loaded")
from llmhost import plan
check("alias accepted", post(plan.SERVED_ALIAS)[0] == 200, post(plan.SERVED_ALIAS)[0])
check("alias is 'default'", plan.SERVED_ALIAS == "default")
seen.clear()
post(plan.SERVED_ALIAS)
check("still forwarded as default_model", seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
va = plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8001, 1)
check("vLLM serves one name; the proxy owns the alias",
va[1:3] == ["--served-model-name", "m"] and plan.SERVED_ALIAS not in va, va[:5])
check("vLLM listens on localhost only, behind the proxy",
va[va.index("--host") + 1] == "127.0.0.1" and va[va.index("--port") + 1] == "8001", va)
check("vLLM reports cached prompt tokens", "--enable-prompt-tokens-details" in va, va)
print("\n5. a model that ISN'T loaded is refused, not silently answered")
code, body = post("qwen3.8-27b")
check("404", code == 404, code)
err = body.get("error") or {}
check("code=model_not_found", err.get("code") == "model_not_found", err)
check("param=model", err.get("param") == "model", err)
check("names the model asked for", "qwen3.8-27b" in err.get("message", ""), err)
check("names the loaded model", SERVED in err.get("message", ""), err)
check("says how to load it", "llmhost switch" in err.get("message", ""), err)
seen.clear()
post("qwen3.8-27b")
check("never reached the model server", seen == [], seen)
print("\n6. unknown junk is refused too")
check("404", post("../etc/passwd")[0] == 404)
check("404", post("gpt-4")[0] == 404)
print("\n7. auth still comes first")
code, body = post("qwen3.8-27b", key="sk-wrong")
check("401, not 404 (key checked before the model)", code == 401, code)
print("\n8. /v1/models still advertises the served name")
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
headers={"Authorization": f"Bearer {KEY}"})
with urllib.request.urlopen(req, timeout=10) as r:
d = json.loads(r.read())
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
check("reports context and whether it thinks", d["data"][0]["max_model_len"] == 262144
and d["data"][0]["reasoning"] is False, d)
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
VOUTER = 18233
vstats = proxy.Stats()
vstats.ready = True
serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",),
upstream_model="qwen3.8-27b", upstream_key="sk-inner",
reasoning=lambda: {"reasoning_effort": "low"}), VOUTER)
seen.clear(); auths.clear()
check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200)
check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27b", seen[-1])
check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1])
check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404)
check.section("10. the reasoning setting is the dashboard's; a client can't set it")
seen.clear()
post(None, port=VOUTER)
check("dashboard setting applied when the client asks for nothing",
seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, reasoning_effort="xhigh")
check("a client's top-level reasoning_effort never reaches the model",
"reasoning_effort" not in seen[-1], seen[-1])
check("...and the dashboard's setting is what goes instead",
seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "xhigh"})
check("nor one inside chat_template_kwargs",
seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False})
check("a client can't turn thinking off either",
"enable_thinking" not in seen[-1]["chat_template_kwargs"], seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False, "custom_var": 7})
check("template kwargs llm-host has no opinion about are left alone",
seen[-1]["chat_template_kwargs"] == {"custom_var": 7, "reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs="not a dict")
check("junk in chat_template_kwargs is replaced, not merged into",
seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, path="/v1/completions", reasoning_effort="xhigh")
check("a non-chat request is left as it came (no template, no setting)",
seen[-1].get("reasoning_effort") == "xhigh" and "chat_template_kwargs" not in seen[-1], seen[-1])
check.section("10b. with nothing set on the dashboard, the client's setting is still dropped")
NOUTER = 18234
nstats = proxy.Stats()
nstats.ready = True
serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, nstats,
upstream_model="qwen3.8-27b", reasoning=lambda: {}), NOUTER)
seen.clear()
post(None, port=NOUTER, reasoning_effort="xhigh", chat_template_kwargs={"enable_thinking": False})
check("both forms dropped", "reasoning_effort" not in seen[-1], seen[-1])
check("and no empty kwargs left behind for the template to read",
"chat_template_kwargs" not in seen[-1], seen[-1])
seen.clear()
post(None, port=NOUTER, chat_template_kwargs={"custom_var": 7})
check("an unrelated kwarg still survives on its own",
seen[-1]["chat_template_kwargs"] == {"custom_var": 7}, seen[-1])
check.section("11. a streamed run is counted from its usage chunk, and recorded")
before = vstats.snapshot()
code, data = post(None, port=VOUTER, raw_reply=True, stream=True)
after = vstats.snapshot()
check("200", code == 200, code)
check("usage chunk hidden from a client that didn't ask for it", b'"usage"' not in data, data[-200:])
check("generated tokens from usage (3 chunks, 7 tokens)", after["gen_total"] - before["gen_total"] == 7,
after["gen_total"] - before["gen_total"])
run = after["recent"][-1]
check("run recorded with its uncached prompt tokens", run["gen"] == 7 and run["prompt"] == 10, run)
check("time to first token recorded", run["ttft"] is not None, run)
check.done(ROOT)