llm-host/tests/test_dashboard_auth.py
neil 3e9ebeed42 Hand out the right opencode command: the API's public URL, and setup uses the install script
install-newt now asks for the API's public URL first (--api-url) and records it; it names
the Pangolin resource and refuses an endpoint on the same host. expose-dashboard records
only that the dashboard is public. One rule (opencode.client_targets) decides which
opencode-install.sh commands are shown -- local only without a tunnel; internet and local
with one; internet only once the dashboard is public -- and setup's closing message,
`llmhost opencode-config` and the dashboard's Connect dialog all use it.

Setup's offer to install opencode now goes through opencode-install.sh --install-only, a
new mode that only installs opencode; this machine's own provider is still configured by
llm-host, which keeps it in sync on every switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:35:41 -08:00

261 lines
14 KiB
Python

"""Dashboard sign-in: API key mode, and OIDC against a fake provider, through the real handler."""
import base64
import hashlib
import http.client
import json
import sys
import threading
import urllib.parse
from http.server import ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import cli, paths
from llmhost.web import oidc as oidc_mod
from llmhost.web import server as web
harness.guard(paths, ROOT)
check = harness.Checks()
ISSUER = "https://auth.example.test"
PUBLIC = "https://dash.example.test"
KEY = "sk-test"
def b64(obj):
return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
class FakeProvider:
"""Discovery, token and userinfo endpoints. The test sets what the next token
response's claims and userinfo look like."""
def __init__(self):
self.claims = {}
self.userinfo = {}
self.challenges = {} # code -> code_challenge
self.token_calls = 0
def __call__(self, method, url, data=None, headers=None):
if url == ISSUER + "/.well-known/openid-configuration":
return 200, json.dumps({
"issuer": ISSUER, "authorization_endpoint": ISSUER + "/authorize",
"token_endpoint": ISSUER + "/token", "userinfo_endpoint": ISSUER + "/userinfo"}).encode()
if url == ISSUER + "/token":
self.token_calls += 1
form = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode()).items()}
want = "Basic " + base64.b64encode(b"llm-host:s3cret").decode()
if headers.get("Authorization") != want:
return 401, b'{"error": "invalid_client"}'
verifier = form.get("code_verifier", "")
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
if self.challenges.get(form.get("code")) != challenge:
return 400, b'{"error": "invalid_grant"}'
if form.get("redirect_uri") != PUBLIC + "/auth/callback":
return 400, b'{"error": "invalid_grant"}'
return 200, json.dumps({"id_token": f"h.{b64(self.claims)}.sig", "access_token": "at"}).encode()
if url == ISSUER + "/userinfo":
return 200, json.dumps(self.userinfo).encode()
return 404, b"{}"
class StubSampler:
def __init__(self):
self.resets = 0
def snapshot(self):
return {"ok": True}
def reset_stats(self):
self.resets += 1
def serve(oidc):
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, oidc))
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
def req(srv, method, path, headers=None, body=None):
c = http.client.HTTPConnection("127.0.0.1", srv.server_address[1], timeout=5)
c.request(method, path, body=body, headers=headers or {})
r = c.getresponse()
data = r.read()
out = (r.status, dict((k.lower(), v) for k, v in r.getheaders()), data,
[v for k, v in r.getheaders() if k.lower() == "set-cookie"])
c.close()
return out
PUB_HOST = {"Host": "dash.example.test"}
print("\n1. API key mode is unchanged")
srv = serve(None)
st, _, body, _ = req(srv, "GET", "/auth/config")
check("config reports key mode", st == 200 and json.loads(body)["mode"] == "key", body)
check("status without key -> 401", req(srv, "GET", "/api/status")[0] == 401)
check("status with key -> 200", req(srv, "GET", "/api/status", {"Authorization": f"Bearer {KEY}"})[0] == 200)
check("no /auth/login without OIDC", req(srv, "GET", "/auth/login")[0] == 404)
paths.save_config(harness.config())
check("/api/connect needs the key", req(srv, "GET", "/api/connect")[0] == 401)
st, h, body, _ = req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})
cx = json.loads(body)
check("/api/connect returns the key", st == 200 and cx["key"] == KEY, body[:200])
check("/api/connect isn't cached", h.get("cache-control") == "no-store", h)
blk = cx["opencode"]
check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk/openai-compatible", blk)
check("opencode block offers the one alias", list(blk["models"]) == [cx["model"]] == ["default"], blk["models"])
check("opencode block leaves the address to the page", "LABEL" in blk["name"] and "HOST" in blk["options"]["baseURL"], blk)
check("the key isn't inlined in the block", KEY not in json.dumps(blk))
check("one address before any tunnel: the LAN", len(cx["targets"]) == 1
and cx["targets"][0]["url"].endswith(f":{harness.config()['api_port']}"), cx["targets"])
check("with its opencode-install.sh command", "/opencode-install.sh)\" -- --url http://" in cx["targets"][0]["command"],
cx["targets"])
c2 = harness.config(); c2["newt"] = {"endpoint": "https://p.example.test", "id": "x", "api_url": "https://llm-api.example.test"}
paths.save_config(c2)
cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2])
check("tunnel, local dashboard: internet then LAN", [t["where"] for t in cx["targets"]]
== ["from the internet", "on your local network"] and cx["targets"][0]["url"] == "https://llm-api.example.test", cx["targets"])
c2["dashboard_public"] = True
paths.save_config(c2)
cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2])
check("public dashboard: the internet only", [t["url"] for t in cx["targets"]] == ["https://llm-api.example.test"], cx["targets"])
paths.save_config(harness.config())
R = web.raw_file_url
check("raw URL for a Gitea/Forgejo repo", R("https://git.example.com/pub/llm-host.git", "main", "f.sh")
== "https://git.example.com/pub/llm-host/raw/branch/main/f.sh")
check("raw URL for a GitHub repo", R("https://github.com/someone/llm-host", "dev", "f.sh")
== "https://raw.githubusercontent.com/someone/llm-host/dev/f.sh")
check("no raw URL for an ssh remote", R("git@github.com:someone/llm-host.git", "main", "f.sh") is None)
srv.shutdown()
print("\n2. OIDC mode refuses the key and unsigned visitors")
prov = FakeProvider()
conf = {"mode": "oidc", "issuer": ISSUER, "client_id": "llm-host", "public_url": PUBLIC,
"allowed_groups": ["llm-admins"], "allowed_users": ["friend"]}
o = oidc_mod.OIDC(conf, "s3cret", http=prov)
srv = serve(o)
st, _, body, _ = req(srv, "GET", "/auth/config", PUB_HOST)
check("config reports oidc, nobody signed in", json.loads(body) == {"mode": "oidc", "user": None, "name": None}, body)
check("status without session -> 401", req(srv, "GET", "/api/status", PUB_HOST)[0] == 401)
check("the dashboard doesn't serve the opencode installer", req(srv, "GET", "/opencode-install.sh", PUB_HOST)[0] == 404)
check("the API key no longer opens it", req(srv, "GET", "/api/status", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
st, h, _, _ = req(srv, "GET", "/", {"Host": "mybox.local:11340"})
check("a LAN name is sent to the public URL", st == 302 and h["location"] == PUBLIC + "/", h.get("location"))
st, h, _, _ = req(srv, "GET", "/auth/login", {"Host": "mybox.local:11340"})
check("login by a LAN name starts on the public URL", st == 302 and h["location"] == PUBLIC + "/auth/login")
try:
oidc_mod.OIDC({**conf, "allowed_groups": [], "allowed_users": []}, "x")
check("an allow list is required", False)
except ValueError:
check("an allow list is required", True)
def login(claims_over=None, userinfo=None, cookie_state=None, tamper_state=None):
"""Run /auth/login then /auth/callback. Returns (callback status, session cookie or None, body)."""
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
assert st == 302, st
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
code = "code-" + q["state"][:8]
prov.challenges[code] = q["code_challenge"]
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "iat": 1, "sub": "u1",
"nonce": q["nonce"], "preferred_username": "alice", **(claims_over or {})}
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "name": "Alice",
"groups": ["llm-admins"]} if userinfo is None else userinfo
state_cookie = cookies[0].split(";")[0]
if cookie_state is not None:
state_cookie = f"{oidc_mod.STATE_COOKIE}={cookie_state}"
st, h, body, cookies = req(srv, "GET", "/auth/callback?" + urllib.parse.urlencode(
{"code": code, "state": tamper_state or q["state"], "iss": ISSUER}), {**PUB_HOST, "Cookie": state_cookie})
sess = next((c.split(";")[0] for c in cookies if c.startswith(oidc_mod.SESSION_COOKIE + "=")), None)
return st, sess, body, q, h
print("\n3. the authorization request")
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
check("redirects to the provider", h["location"].startswith(ISSUER + "/authorize?"))
check("PKCE S256", q.get("code_challenge_method") == "S256" and len(q.get("code_challenge", "")) == 43)
check("redirect URI is the public callback", q.get("redirect_uri") == PUBLIC + "/auth/callback")
check("asks for groups", "groups" in q.get("scope", "").split())
check("state cookie is HttpOnly, Secure, Lax, scoped to /auth/",
all(a in cookies[0] for a in ("HttpOnly", "Secure", "SameSite=Lax", "Path=/auth/")), cookies)
print("\n4. a good sign-in")
st, sess, body, q, h = login()
check("callback -> 302 home", st == 302 and h["location"] == "/", (st, body))
check("session cookie set", sess is not None)
st, _, body, _ = req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})
check("status with session -> 200", st == 200, st)
st, _, body, _ = req(srv, "GET", "/auth/config", {**PUB_HOST, "Cookie": sess})
check("config names the user", json.loads(body)["user"] == "alice" and json.loads(body)["name"] == "Alice", body)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess})
check("POST without Origin -> 403", st == 403, st)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})
check("POST from another origin -> 403", st == 403, st)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
check("POST from the dashboard's origin -> 200", st == 200, st)
check("/api/connect refused without a session", req(srv, "GET", "/api/connect", PUB_HOST)[0] == 401)
check("/api/connect refused for the key alone", req(srv, "GET", "/api/connect", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
st, _, body, _ = req(srv, "GET", "/api/connect", {**PUB_HOST, "Cookie": sess})
check("signed in: /api/connect returns the key", st == 200 and json.loads(body)["key"] == KEY, body[:200])
check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions)
print("\n5. sign-ins that must fail")
before = len(o.sessions)
st, sess2, body, *_ = login(cookie_state="someone-elses-state")
check("state cookie mismatch -> 403, no session", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"nonce": "wrong"})
check("wrong nonce -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"aud": "other-client"})
check("ID token for another client -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"iss": "https://evil.test"})
check("ID token from another issuer -> 403", st == 403 and sess2 is None, st)
st, sess2, *_ = login(claims_over={"exp": 1})
check("expired ID token -> 403", st == 403 and sess2 is None, st)
st, sess2, body, *_ = login(userinfo={"sub": "u1", "preferred_username": "stranger", "groups": ["users"]},
claims_over={"preferred_username": "stranger"})
check("not in an allowed group -> 403", st == 403 and sess2 is None and b"isn&#x27;t allowed" in body, body[:200])
st, sess2, *_ = login(userinfo={"sub": "u1", "preferred_username": "friend", "groups": []},
claims_over={"preferred_username": "friend"})
check("an allowed username gets in without the group", st == 302 and sess2 is not None, st)
st, sess3, *_ = login(userinfo={"sub": "OTHER", "preferred_username": "x", "groups": ["llm-admins"]},
claims_over={"preferred_username": "stranger"})
check("userinfo for a different sub is ignored", st == 403 and sess3 is None, st)
st, _, _, _ = req(srv, "GET", "/auth/callback?error=access_denied&state=x", {**PUB_HOST, "Cookie": f"{oidc_mod.STATE_COOKIE}=x"})
check("provider error -> 403", st == 403, st)
check("no stray sessions from the failures", len(o.sessions) == before + 1, len(o.sessions))
# A state can be used once.
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
prov.challenges["c1"] = q["code_challenge"]
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "sub": "u1", "nonce": q["nonce"]}
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "groups": ["llm-admins"]}
cb = "/auth/callback?" + urllib.parse.urlencode({"code": "c1", "state": q["state"]})
hdr = {**PUB_HOST, "Cookie": cookies[0].split(";")[0]}
check("first use of a state works", req(srv, "GET", cb, hdr)[0] == 302)
check("replaying it -> 403", req(srv, "GET", cb, hdr)[0] == 403)
print("\n6. sign-out")
st, sess, *_ = login()
check("logout from another origin -> 403", req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
st, _, _, cookies = req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
check("logout -> 200 and clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
check("the old cookie no longer works", req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})[0] == 401)
srv.shutdown()
print("\n7. setup keeps the dashboard's sign-in setting")
carried = cli.carried_settings({"dashboard_auth": conf, "reasoning": {"m": "low"}}, {"m"})
check("dashboard_auth carried", carried.get("dashboard_auth") == conf, carried)
check("reasoning still carried", carried.get("reasoning") == {"m": "low"})
check("nothing invented when unset", "dashboard_auth" not in cli.carried_settings({}, set()))
print("\n8. the client secret is stored privately")
paths.save_secret(paths.OIDC_SECRET_FILE, "s3cret")
check("secret file is 0600", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
check("reads back", paths.oidc_secret() == "s3cret")
check.done(ROOT)