The API key button is Connect again. Besides the key, it walks through adding this server to opencode: type the API's address (remembered in the browser; prefilled on a LAN visit) and it fills in a command that saves the key to a 0600 file without it touching shell history, and the provider block from the same builder as `llmhost opencode-config`. GET /api/connect replaces /api/key, behind the same sign-in. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
13 KiB
Python
240 lines
13 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))
|
|
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 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'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)
|