install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard
A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt` is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt` shows the tunnel (and `logs -f` now follows the service it was asked for). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d07a92e5b5
commit
e814a2359d
11 changed files with 1155 additions and 26 deletions
|
|
@ -76,13 +76,14 @@ button.small { font-size: 12px; padding: 4px 10px; }
|
|||
}
|
||||
.effort select:disabled { color: var(--muted); }
|
||||
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
|
||||
button {
|
||||
button, a.btn {
|
||||
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
|
||||
}
|
||||
button:hover:not(:disabled) { border-color: var(--faint); }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
a.btn { display: inline-block; text-decoration: none; }
|
||||
button.primary, a.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||
button.danger { color: var(--bad); }
|
||||
|
||||
.profiles { display: flex; flex-direction: column; gap: 8px; }
|
||||
|
|
@ -169,6 +170,7 @@ pre {
|
|||
<span id="phase" class="pill">…</span>
|
||||
<span class="spacer"></span>
|
||||
<span class="meta" id="uptime"></span>
|
||||
<span class="meta" id="whoami" hidden></span>
|
||||
<button id="logout" title="Forget API key">Sign out</button>
|
||||
</header>
|
||||
|
||||
|
|
@ -268,6 +270,11 @@ pre {
|
|||
<div class="err" id="auth-err"></div>
|
||||
<button class="primary" type="submit">Continue</button>
|
||||
</form>
|
||||
<div class="dialog" id="auth-oidc" hidden>
|
||||
<h3>Sign in</h3>
|
||||
<p id="auth-oidc-text">This dashboard signs in through your identity provider.</p>
|
||||
<a class="btn primary" href="/auth/login" id="auth-oidc-go">Sign in</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
|
|
@ -275,6 +282,9 @@ pre {
|
|||
const $ = (id) => document.getElementById(id);
|
||||
let KEY = null;
|
||||
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
|
||||
// "key": the API key, typed in and kept in this browser. "oidc": a session cookie set by
|
||||
// signing in at the provider (/auth/login); the key isn't accepted then.
|
||||
let AUTH = { mode: "key" };
|
||||
let state = null;
|
||||
let logTimer = null;
|
||||
|
||||
|
|
@ -287,14 +297,23 @@ function toast(msg) {
|
|||
}
|
||||
|
||||
async function api(path, opts = {}) {
|
||||
const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } });
|
||||
if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); }
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY;
|
||||
const r = await fetch(path, { ...opts, headers, credentials: "same-origin" });
|
||||
if (r.status === 401) { showAuth(AUTH.mode === "key" ? "That key was rejected." : ""); throw new Error("unauthorized"); }
|
||||
const body = await r.json();
|
||||
if (!r.ok) throw new Error(body.error || r.statusText);
|
||||
return body;
|
||||
}
|
||||
|
||||
function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); }
|
||||
function showAuth(err = "") {
|
||||
if (AUTH.mode === "oidc") {
|
||||
$("auth-form").hidden = true; $("auth-oidc").hidden = false;
|
||||
$("auth").classList.add("show"); $("auth-oidc-go").focus();
|
||||
return;
|
||||
}
|
||||
$("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus();
|
||||
}
|
||||
$("auth-form").addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
KEY = $("auth-key").value.trim();
|
||||
|
|
@ -302,7 +321,14 @@ $("auth-form").addEventListener("submit", (e) => {
|
|||
$("auth").classList.remove("show");
|
||||
poll();
|
||||
});
|
||||
$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); };
|
||||
$("logout").onclick = async () => {
|
||||
if (AUTH.mode === "oidc") {
|
||||
try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {}
|
||||
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); showAuth();
|
||||
return;
|
||||
}
|
||||
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth();
|
||||
};
|
||||
|
||||
const fmt = {
|
||||
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
|
||||
|
|
@ -692,12 +718,26 @@ $("logs").addEventListener("toggle", () => {
|
|||
let pollTimer = null;
|
||||
async function poll() {
|
||||
clearTimeout(pollTimer);
|
||||
if (!KEY) { showAuth(); return; }
|
||||
if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; }
|
||||
try { render(await api("/api/status")); }
|
||||
catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } }
|
||||
catch (e) {
|
||||
if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in
|
||||
if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; }
|
||||
}
|
||||
pollTimer = setTimeout(poll, 2000);
|
||||
}
|
||||
poll();
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const r = await fetch("/auth/config", { credentials: "same-origin" });
|
||||
if (r.ok) AUTH = await r.json();
|
||||
} catch (e) {}
|
||||
if (AUTH.mode === "oidc") {
|
||||
$("logout").title = "Sign out of this dashboard";
|
||||
if (AUTH.user) { $("whoami").textContent = AUTH.name || AUTH.user; $("whoami").hidden = false; }
|
||||
}
|
||||
poll();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
236
llmhost/web/oidc.py
Normal file
236
llmhost/web/oidc.py
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
"""Dashboard sign-in through an OpenID Connect provider. Stdlib only.
|
||||
|
||||
Off unless config.json has a "dashboard_auth" block with mode "oidc" (`llmhost install-newt` sets it); then it replaces the
|
||||
API key on the dashboard (the API on api_port still takes the key -- that's for clients).
|
||||
|
||||
The flow is the authorization-code flow of a confidential client, with PKCE:
|
||||
|
||||
/auth/login -> 302 to the provider, with state, nonce and an S256 code challenge.
|
||||
The state is also set in a short-lived cookie, so a callback only
|
||||
completes in the browser that started it (no login CSRF).
|
||||
/auth/callback -> code exchanged at the token endpoint with the client secret, the
|
||||
ID token's claims checked, groups read from userinfo, the allow
|
||||
list applied, and a session cookie set.
|
||||
/auth/logout -> POST; drops the session.
|
||||
|
||||
The ID token comes straight from the token endpoint over TLS, which OIDC Core 3.1.3.7 lets
|
||||
a client rely on in place of checking its signature; its iss/aud/azp/exp/nonce are still
|
||||
checked. Sessions live in memory, so a dashboard restart signs everyone out.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
SESSION_COOKIE = "llmhost_session"
|
||||
STATE_COOKIE = "llmhost_oidc_state"
|
||||
SESSION_TTL = 12 * 3600
|
||||
LOGIN_TTL = 600 # how long a started sign-in may take to come back
|
||||
MAX_PENDING = 256 # unfinished sign-ins kept at once
|
||||
CLOCK_SKEW = 120
|
||||
SCOPES = "openid profile email groups"
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
"""A sign-in that can't complete; the message is safe to show the user."""
|
||||
|
||||
|
||||
def b64url(raw: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def jwt_claims(token: str) -> dict:
|
||||
try:
|
||||
payload = token.split(".")[1]
|
||||
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
|
||||
except (IndexError, ValueError):
|
||||
raise AuthError("the provider sent an unreadable ID token")
|
||||
|
||||
|
||||
def parse_cookies(header: str) -> dict:
|
||||
out = {}
|
||||
for part in (header or "").split(";"):
|
||||
k, sep, v = part.strip().partition("=")
|
||||
if sep:
|
||||
out.setdefault(k, v)
|
||||
return out
|
||||
|
||||
|
||||
def origin_of(url: str) -> str:
|
||||
u = urllib.parse.urlsplit(url)
|
||||
return f"{u.scheme}://{u.netloc}".lower()
|
||||
|
||||
|
||||
class OIDC:
|
||||
def __init__(self, conf: dict, client_secret: str, http=None):
|
||||
self.issuer = conf["issuer"].rstrip("/")
|
||||
self.client_id = conf["client_id"]
|
||||
self.secret = client_secret
|
||||
self.public_url = conf["public_url"].rstrip("/")
|
||||
self.redirect_uri = self.public_url + "/auth/callback"
|
||||
self.origin = origin_of(self.public_url)
|
||||
self.secure = self.public_url.startswith("https://")
|
||||
self.allowed_groups = set(conf.get("allowed_groups") or [])
|
||||
self.allowed_users = set(conf.get("allowed_users") or [])
|
||||
if not (self.allowed_groups or self.allowed_users):
|
||||
raise ValueError("dashboard_auth needs allowed_groups or allowed_users")
|
||||
self.http = http or self._http
|
||||
self.lock = threading.Lock()
|
||||
self.pending = {} # state -> {nonce, verifier, t}
|
||||
self.sessions = {} # sha256(session id) -> {user, name, exp}
|
||||
self._disco = None
|
||||
|
||||
# -- provider ---------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _http(method, url, data=None, headers=None):
|
||||
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return r.status, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()
|
||||
|
||||
def discovery(self) -> dict:
|
||||
if self._disco is None:
|
||||
try:
|
||||
st, body = self.http("GET", self.issuer + "/.well-known/openid-configuration")
|
||||
d = json.loads(body) if st == 200 else None
|
||||
except (OSError, ValueError):
|
||||
d = None
|
||||
if not d or d.get("issuer", "").rstrip("/") != self.issuer:
|
||||
raise AuthError(f"couldn't reach the sign-in provider at {self.issuer}")
|
||||
self._disco = d
|
||||
return self._disco
|
||||
|
||||
# -- sign-in ----------------------------------------------------------------------
|
||||
|
||||
def start(self):
|
||||
"""Begin a sign-in: (provider URL to redirect to, state for the state cookie)."""
|
||||
d = self.discovery()
|
||||
state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
|
||||
now = time.time()
|
||||
with self.lock:
|
||||
for s in [s for s, p in self.pending.items() if now - p["t"] > LOGIN_TTL]:
|
||||
del self.pending[s]
|
||||
if len(self.pending) >= MAX_PENDING:
|
||||
del self.pending[min(self.pending, key=lambda s: self.pending[s]["t"])]
|
||||
self.pending[state] = {"nonce": nonce, "verifier": verifier, "t": now}
|
||||
q = urllib.parse.urlencode({
|
||||
"response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri,
|
||||
"scope": SCOPES, "state": state, "nonce": nonce,
|
||||
"code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
|
||||
"code_challenge_method": "S256"})
|
||||
return f"{d['authorization_endpoint']}?{q}", state
|
||||
|
||||
def finish(self, params: dict, cookie_state: str) -> dict:
|
||||
"""Complete a sign-in from the callback's query. Returns the new session
|
||||
{"id", "user", "name"}; raises AuthError for anything that doesn't check out."""
|
||||
if params.get("error"):
|
||||
raise AuthError(f"the provider said: {params.get('error_description') or params['error']}")
|
||||
state = params.get("state", "")
|
||||
if not state or not cookie_state or not hmac.compare_digest(state, cookie_state):
|
||||
raise AuthError("this sign-in was started in a different browser or tab; try again")
|
||||
with self.lock:
|
||||
p = self.pending.pop(state, None)
|
||||
if not p or time.time() - p["t"] > LOGIN_TTL:
|
||||
raise AuthError("this sign-in expired; try again")
|
||||
d = self.discovery()
|
||||
if "iss" in params and params["iss"].rstrip("/") != self.issuer:
|
||||
raise AuthError("the response came from a different provider")
|
||||
code = params.get("code")
|
||||
if not code:
|
||||
raise AuthError("the provider sent no authorization code")
|
||||
|
||||
basic = base64.b64encode(f"{urllib.parse.quote(self.client_id, safe='')}:"
|
||||
f"{urllib.parse.quote(self.secret, safe='')}".encode()).decode()
|
||||
st, body = self.http("POST", d["token_endpoint"], urllib.parse.urlencode({
|
||||
"grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri,
|
||||
"code_verifier": p["verifier"]}).encode(), {
|
||||
"Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json"})
|
||||
try:
|
||||
tok = json.loads(body)
|
||||
except ValueError:
|
||||
tok = {}
|
||||
if st != 200 or "id_token" not in tok:
|
||||
raise AuthError(f"the provider refused the code ({tok.get('error') or st})")
|
||||
|
||||
c = jwt_claims(tok["id_token"])
|
||||
now = time.time()
|
||||
aud = c.get("aud")
|
||||
auds = aud if isinstance(aud, list) else [aud]
|
||||
if c.get("iss", "").rstrip("/") != self.issuer:
|
||||
raise AuthError("the ID token is from a different provider")
|
||||
if self.client_id not in auds or (len(auds) > 1 and c.get("azp") != self.client_id):
|
||||
raise AuthError("the ID token was issued to a different client")
|
||||
if not isinstance(c.get("exp"), (int, float)) or c["exp"] < now - CLOCK_SKEW:
|
||||
raise AuthError("the ID token has expired")
|
||||
if not hmac.compare_digest(str(c.get("nonce", "")), p["nonce"]):
|
||||
raise AuthError("the ID token doesn't belong to this sign-in")
|
||||
|
||||
info = dict(c)
|
||||
if d.get("userinfo_endpoint") and tok.get("access_token"):
|
||||
st, body = self.http("GET", d["userinfo_endpoint"], None, {
|
||||
"Authorization": f"Bearer {tok['access_token']}", "Accept": "application/json"})
|
||||
try:
|
||||
u = json.loads(body) if st == 200 else {}
|
||||
except ValueError:
|
||||
u = {} # a signed/encrypted userinfo isn't JSON; the ID token's claims stand
|
||||
if u.get("sub") == c.get("sub"):
|
||||
info.update(u)
|
||||
|
||||
user = info.get("preferred_username") or info.get("email") or info.get("sub")
|
||||
groups = set(info.get("groups") or [])
|
||||
if user not in self.allowed_users and not (groups & self.allowed_groups):
|
||||
raise AuthError(f"signed in as {user}, but that account isn't allowed on this dashboard")
|
||||
|
||||
sid = secrets.token_urlsafe(32)
|
||||
with self.lock:
|
||||
for h in [h for h, s in self.sessions.items() if s["exp"] < now]:
|
||||
del self.sessions[h]
|
||||
self.sessions[self._h(sid)] = {"user": user, "name": info.get("name") or user,
|
||||
"exp": now + SESSION_TTL}
|
||||
return {"id": sid, "user": user, "name": info.get("name") or user}
|
||||
|
||||
# -- sessions ---------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _h(sid: str) -> str:
|
||||
return hashlib.sha256(sid.encode()).hexdigest()
|
||||
|
||||
def session(self, cookie_header: str):
|
||||
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
|
||||
if not sid:
|
||||
return None
|
||||
with self.lock:
|
||||
s = self.sessions.get(self._h(sid))
|
||||
if s and s["exp"] < time.time():
|
||||
del self.sessions[self._h(sid)]
|
||||
s = None
|
||||
return s
|
||||
|
||||
def end(self, cookie_header: str):
|
||||
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
|
||||
if sid:
|
||||
with self.lock:
|
||||
self.sessions.pop(self._h(sid), None)
|
||||
|
||||
def same_origin(self, headers) -> bool:
|
||||
"""For state-changing requests: the browser's Origin (or Referer) must be the
|
||||
dashboard's own. SameSite=Lax already keeps the cookie off cross-site POSTs;
|
||||
this is the second lock on that door."""
|
||||
o = headers.get("Origin") or (origin_of(headers["Referer"]) if headers.get("Referer") else "")
|
||||
return o.lower() == self.origin
|
||||
|
||||
def cookie(self, name, value, max_age, path="/"):
|
||||
attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"]
|
||||
if self.secure:
|
||||
attrs.append("Secure")
|
||||
return "; ".join(attrs)
|
||||
|
|
@ -1,19 +1,23 @@
|
|||
"""Dashboard: status, metrics and model switching. Stdlib only.
|
||||
|
||||
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key.
|
||||
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or,
|
||||
when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py).
|
||||
"""
|
||||
import hmac
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from .. import hfcache, hw, opencode, paths, plan, service
|
||||
from . import oidc as oidc_mod
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SAMPLE_SECONDS = 2
|
||||
|
|
@ -408,7 +412,7 @@ class Sampler:
|
|||
threading.Thread(target=fn, args=("model",), daemon=True).start()
|
||||
|
||||
|
||||
def make_handler(sampler, key):
|
||||
def make_handler(sampler, key, oidc=None):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "llm-host"
|
||||
|
||||
|
|
@ -425,6 +429,15 @@ def make_handler(sampler, key):
|
|||
self.wfile.write(body)
|
||||
|
||||
def authed(self):
|
||||
if oidc:
|
||||
# Signed in through the provider; the API key isn't accepted here.
|
||||
if oidc.session(self.headers.get("Cookie", "")) is None:
|
||||
self.send_json(401, {"error": "unauthorized", "login": "/auth/login"})
|
||||
return False
|
||||
if self.command == "POST" and not oidc.same_origin(self.headers):
|
||||
self.send_json(403, {"error": "cross-origin request refused"})
|
||||
return False
|
||||
return True
|
||||
h = self.headers.get("Authorization", "")
|
||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
||||
if hmac.compare_digest(tok.encode(), key.encode()):
|
||||
|
|
@ -432,8 +445,67 @@ def make_handler(sampler, key):
|
|||
self.send_json(401, {"error": "unauthorized"})
|
||||
return False
|
||||
|
||||
def redirect(self, url, cookies=()):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", url)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
for c in cookies:
|
||||
self.send_header("Set-Cookie", c)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def auth_page(self, code, msg):
|
||||
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
|
||||
f"<title>llm-host sign-in</title><body style='font:15px system-ui;margin:3em auto;"
|
||||
f"max-width:32em;padding:0 16px'><h2>Couldn't sign you in</h2><p>{html.escape(msg)}</p>"
|
||||
f"<p><a href='/auth/login'>Try again</a></p>").encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/"))
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def on_public_host(self):
|
||||
"""A session cookie only exists on the public URL's host, so a visit by any
|
||||
other name (mybox.local:11340) is sent there instead of to a login loop."""
|
||||
host = (self.headers.get("Host") or "").lower()
|
||||
return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower()
|
||||
|
||||
def auth_get(self, path, query):
|
||||
if path == "/auth/config":
|
||||
s = oidc.session(self.headers.get("Cookie", "")) if oidc else None
|
||||
return self.send_json(200, {"mode": "oidc" if oidc else "key",
|
||||
"user": s and s["user"], "name": s and s["name"]})
|
||||
if not oidc:
|
||||
return self.send_json(404, {"error": "not found"})
|
||||
if path == "/auth/login":
|
||||
if not self.on_public_host():
|
||||
return self.redirect(oidc.public_url + "/auth/login")
|
||||
try:
|
||||
url, state = oidc.start()
|
||||
except oidc_mod.AuthError as e:
|
||||
return self.auth_page(502, str(e))
|
||||
return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")])
|
||||
if path == "/auth/callback":
|
||||
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
|
||||
cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "")
|
||||
try:
|
||||
s = oidc.finish(params, cookie_state)
|
||||
except oidc_mod.AuthError as e:
|
||||
return self.auth_page(403, str(e))
|
||||
print(f"llm-host dashboard: {s['user']} signed in", flush=True)
|
||||
return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL),
|
||||
oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")])
|
||||
self.send_json(404, {"error": "not found"})
|
||||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
path, _, query = self.path.partition("?")
|
||||
if path.startswith("/auth/"):
|
||||
return self.auth_get(path, query)
|
||||
if oidc and path in ("/", "/index.html") and not self.on_public_host():
|
||||
return self.redirect(oidc.public_url + "/")
|
||||
if path in ("/", "/index.html"):
|
||||
body = (HERE / "index.html").read_bytes()
|
||||
self.send_response(200)
|
||||
|
|
@ -455,6 +527,17 @@ def make_handler(sampler, key):
|
|||
|
||||
def do_POST(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/auth/logout" and oidc:
|
||||
if not oidc.same_origin(self.headers):
|
||||
return self.send_json(403, {"error": "cross-origin request refused"})
|
||||
oidc.end(self.headers.get("Cookie", ""))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0))
|
||||
self.send_header("Content-Length", "11")
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"ok": true}')
|
||||
return
|
||||
if not self.authed():
|
||||
return
|
||||
try:
|
||||
|
|
@ -494,6 +577,11 @@ def serve():
|
|||
key = paths.api_key()
|
||||
sampler = Sampler(cfg, key)
|
||||
threading.Thread(target=sampler.loop, daemon=True).start()
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
|
||||
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
|
||||
auth = None
|
||||
conf = cfg.get("dashboard_auth") or {}
|
||||
if conf.get("mode") == "oidc":
|
||||
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth))
|
||||
how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key"
|
||||
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
|
||||
srv.serve_forever()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue