"""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)