OWNER_HOSTS (homelab: hub.gabvdl.xyz) answers as the owner without Authelia, for the one device that can't be on the personal tailnet (the Orus Mac). On it the gate takes only the owner's __Host-aia_owner session (7 days, host-only, Strict) — no Remote-User, host token or guest cookie is anyone; without one only the sign-in answers. - remoteaccess/webauthn.py: WebAuthn checked by the hub on `cryptography` (challenge, exact origin, RP ID, user present + verified, signature, counter); a small CBOR reader for new passkeys; fuzzed (80k inputs). - passkeys added only through a one-time link made on the admin host (15 min, one use, hashed, fragment-borne); no mail fallback — Pocket ID was rejected because a mailed code there can enrol a passkey. - Settings → Security: Internet access off (drops every session, back on from the admin host only); pushes on every sign-in and passkey added. - machine paths (worker proxy tokens, tool proxy) refused there. - tests: test_remote_access.py (31), test_webauthn.py (7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
394 lines
16 KiB
Python
394 lines
16 KiB
Python
"""
|
|
Guests sign in through an OpenID Connect provider — Pocket ID in the homelab
|
|
(docs/multi-user.md, round 9): one account for the ai-agent and the other
|
|
apps it guards (Jellyfin). Authorization code flow with PKCE, on the guest
|
|
surface only; the ID token is checked here (RS256 against the provider's
|
|
JWKS — ``cryptography``, already in the image through pywebpush).
|
|
|
|
* ``OIDC_ISSUER`` — the provider's public URL (the browser's authorize page,
|
|
the ``iss`` the tokens carry).
|
|
* ``OIDC_INTERNAL_URL`` — where the hub reaches it (discovery, token, JWKS);
|
|
defaults to the issuer.
|
|
* ``OIDC_CLIENT_ID`` / ``OIDC_CLIENT_SECRET`` — this app's client there.
|
|
* ``OIDC_REDIRECT_URI`` — default ``{GUEST_PUBLIC_URL}/api/auth/oidc/callback``.
|
|
* ``OIDC_PROVIDER_NAME`` — the login page's button (``Continue with …``).
|
|
|
|
Set (issuer + client), the built-in mailed link / code login is off
|
|
(``/api/auth/request-link`` and ``/api/auth/login`` answer 410): every
|
|
guest signs in here. Sessions opened before stay valid. Unset, nothing
|
|
changes — the standalone container keeps its own login.
|
|
|
|
A provider account maps to a guest by ``idpId`` (the ``sub``, recorded when
|
|
users/idp.py mirrors the guest), else — once, for a guest mirrored before
|
|
that id was known — by email.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
import secrets
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
|
|
import httpx
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import RedirectResponse
|
|
|
|
import schemas
|
|
from core.http import _r
|
|
from core.state import State
|
|
from security import service as security
|
|
from users import session
|
|
from users.caller import on_guest_surface, on_owner_surface
|
|
from users.deliver import GUEST_PUBLIC_URL
|
|
from users.idp import APPS, GUEST_GROUP
|
|
|
|
log = logging.getLogger("ai-agent.oidc")
|
|
|
|
ISSUER = os.environ.get("OIDC_ISSUER", "").strip().rstrip("/")
|
|
INTERNAL_URL = (os.environ.get("OIDC_INTERNAL_URL", "").strip() or ISSUER).rstrip("/")
|
|
CLIENT_ID = os.environ.get("OIDC_CLIENT_ID", "").strip()
|
|
CLIENT_SECRET = os.environ.get("OIDC_CLIENT_SECRET", "").strip()
|
|
REDIRECT_URI = (os.environ.get("OIDC_REDIRECT_URI", "").strip()
|
|
or (f"{GUEST_PUBLIC_URL}/api/auth/oidc/callback" if GUEST_PUBLIC_URL else ""))
|
|
PROVIDER_NAME = os.environ.get("OIDC_PROVIDER_NAME", "").strip() or "gabvdl.xyz"
|
|
SCOPES = "openid profile email groups"
|
|
|
|
STATE_COOKIE = "aia_oidc"
|
|
COOKIE_PATH = "/api/auth/oidc"
|
|
STATE_TTL_S = 600
|
|
CLOCK_SKEW_S = 120
|
|
_DISCOVERY_TTL_S = 3600
|
|
|
|
# Tests swap in an ``httpx.MockTransport``.
|
|
TRANSPORT: httpx.BaseTransport | None = None
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def enabled() -> bool:
|
|
return bool(ISSUER and CLIENT_ID and CLIENT_SECRET and REDIRECT_URI)
|
|
|
|
|
|
class OidcError(RuntimeError):
|
|
pass
|
|
|
|
|
|
# ── the provider's metadata ──────────────────────────────────────────────────
|
|
_lock = threading.Lock()
|
|
_discovery: dict = {"at": 0.0, "doc": None}
|
|
_jwks: dict = {"at": 0.0, "keys": {}}
|
|
# state → {nonce, verifier, next, exp}: a sign-in started here, not finished.
|
|
_pending: dict[str, dict] = {}
|
|
|
|
|
|
def _http() -> httpx.Client:
|
|
return httpx.Client(timeout=10, transport=TRANSPORT,
|
|
headers={"Accept": "application/json"})
|
|
|
|
|
|
def _origin(url: str) -> str:
|
|
p = urllib.parse.urlsplit(url)
|
|
return f"{p.scheme}://{p.netloc}"
|
|
|
|
|
|
def _inside(url: str) -> str:
|
|
"""A back-channel endpoint, moved onto ``OIDC_INTERNAL_URL`` (the docker
|
|
network) whatever origin the provider advertised."""
|
|
if not url or not INTERNAL_URL:
|
|
return url
|
|
p = urllib.parse.urlsplit(url)
|
|
return INTERNAL_URL + p.path + (f"?{p.query}" if p.query else "")
|
|
|
|
|
|
def _outside(url: str) -> str:
|
|
"""The browser's endpoint, on the public issuer's origin."""
|
|
if not url:
|
|
return f"{ISSUER}/authorize"
|
|
p = urllib.parse.urlsplit(url)
|
|
return _origin(ISSUER) + p.path + (f"?{p.query}" if p.query else "")
|
|
|
|
|
|
def discovery() -> dict:
|
|
with _lock:
|
|
if _discovery["doc"] and time.time() - _discovery["at"] < _DISCOVERY_TTL_S:
|
|
return _discovery["doc"]
|
|
try:
|
|
with _http() as c:
|
|
r = c.get(f"{INTERNAL_URL}/.well-known/openid-configuration")
|
|
r.raise_for_status()
|
|
raw = r.json()
|
|
except (httpx.HTTPError, ValueError) as e:
|
|
raise OidcError(f"discovery failed: {e}") from None
|
|
doc = {"authorization_endpoint": _outside(raw.get("authorization_endpoint", "")),
|
|
"token_endpoint": _inside(raw.get("token_endpoint") or f"{INTERNAL_URL}/api/oidc/token"),
|
|
"jwks_uri": _inside(raw.get("jwks_uri") or f"{INTERNAL_URL}/.well-known/jwks.json")}
|
|
with _lock:
|
|
_discovery.update(at=time.time(), doc=doc)
|
|
return doc
|
|
|
|
|
|
def _b64d(s: str) -> bytes:
|
|
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
|
|
|
|
def _b64e(b: bytes) -> str:
|
|
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
|
|
|
|
|
def _key(kid: str | None):
|
|
"""The provider's RSA public key ``kid`` (the JWKS refetched once on a
|
|
kid it hasn't seen — a key rotation)."""
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
for fresh in (False, True):
|
|
with _lock:
|
|
keys = _jwks["keys"]
|
|
stale = time.time() - _jwks["at"] > _DISCOVERY_TTL_S
|
|
if fresh or stale or not keys:
|
|
try:
|
|
with _http() as c:
|
|
r = c.get(discovery()["jwks_uri"])
|
|
r.raise_for_status()
|
|
found = {}
|
|
for k in r.json().get("keys") or []:
|
|
if k.get("kty") == "RSA" and k.get("n") and k.get("e"):
|
|
found[k.get("kid") or ""] = rsa.RSAPublicNumbers(
|
|
int.from_bytes(_b64d(k["e"]), "big"),
|
|
int.from_bytes(_b64d(k["n"]), "big")).public_key()
|
|
except (httpx.HTTPError, ValueError) as e:
|
|
raise OidcError(f"JWKS fetch failed: {e}") from None
|
|
with _lock:
|
|
_jwks.update(at=time.time(), keys=found)
|
|
keys = found
|
|
key = keys.get(kid or "") or (next(iter(keys.values())) if not kid and len(keys) == 1
|
|
else None)
|
|
if key is not None:
|
|
return key
|
|
raise OidcError(f"no signing key {kid!r}")
|
|
|
|
|
|
def verify_id_token(token: str, nonce: str) -> dict:
|
|
"""The ID token's claims, once its signature, issuer, audience, expiry
|
|
and nonce check out; :class:`OidcError` otherwise."""
|
|
from cryptography.exceptions import InvalidSignature
|
|
from cryptography.hazmat.primitives import hashes
|
|
from cryptography.hazmat.primitives.asymmetric import padding
|
|
try:
|
|
head_b, body_b, sig_b = token.split(".")
|
|
head = json.loads(_b64d(head_b))
|
|
claims = json.loads(_b64d(body_b))
|
|
sig = _b64d(sig_b)
|
|
except (ValueError, TypeError) as e:
|
|
raise OidcError(f"malformed ID token: {e}") from None
|
|
if head.get("alg") != "RS256":
|
|
raise OidcError(f"unexpected alg {head.get('alg')!r}")
|
|
try:
|
|
_key(head.get("kid")).verify(sig, f"{head_b}.{body_b}".encode(),
|
|
padding.PKCS1v15(), hashes.SHA256())
|
|
except InvalidSignature:
|
|
raise OidcError("bad ID token signature") from None
|
|
if (claims.get("iss") or "").rstrip("/") != ISSUER:
|
|
raise OidcError(f"wrong issuer {claims.get('iss')!r}")
|
|
aud = claims.get("aud")
|
|
auds = aud if isinstance(aud, list) else [aud]
|
|
if CLIENT_ID not in auds or (len(auds) > 1 and claims.get("azp") not in (None, CLIENT_ID)):
|
|
raise OidcError("ID token is for another client")
|
|
now = time.time()
|
|
try:
|
|
exp = float(claims.get("exp"))
|
|
except (TypeError, ValueError):
|
|
raise OidcError("ID token has no expiry") from None
|
|
if exp < now - CLOCK_SKEW_S:
|
|
raise OidcError("ID token expired")
|
|
if not nonce or not hmac.compare_digest(str(claims.get("nonce") or ""), nonce):
|
|
raise OidcError("nonce mismatch")
|
|
if not claims.get("sub"):
|
|
raise OidcError("ID token has no subject")
|
|
return claims
|
|
|
|
|
|
def _exchange(code: str, verifier: str) -> dict:
|
|
try:
|
|
with _http() as c:
|
|
r = c.post(discovery()["token_endpoint"],
|
|
data={"grant_type": "authorization_code", "code": code,
|
|
"redirect_uri": REDIRECT_URI, "code_verifier": verifier},
|
|
auth=(CLIENT_ID, CLIENT_SECRET))
|
|
except httpx.HTTPError as e:
|
|
raise OidcError(f"token endpoint unreachable: {e}") from None
|
|
if r.status_code != 200:
|
|
raise OidcError(f"token endpoint: {r.status_code} {r.text[:200]}")
|
|
try:
|
|
out = r.json()
|
|
except ValueError:
|
|
raise OidcError("token endpoint answered no JSON") from None
|
|
if not out.get("id_token"):
|
|
raise OidcError("no id_token in the token response")
|
|
return out
|
|
|
|
|
|
# ── the flow ─────────────────────────────────────────────────────────────────
|
|
def safe_next(raw: str | None) -> str:
|
|
"""Where to land after signing in: a same-origin path only (never
|
|
``//evil.example``, never the login page)."""
|
|
raw = (raw or "").strip()
|
|
if not raw.startswith("/") or raw.startswith("//") or raw.startswith("/\\"):
|
|
return "/"
|
|
p = urllib.parse.urlsplit(raw)
|
|
if p.scheme or p.netloc or p.path == "/login" or p.path.startswith("/api/"):
|
|
return "/"
|
|
return raw
|
|
|
|
|
|
def _prune(now: float) -> None:
|
|
for k in [k for k, v in _pending.items() if v["exp"] < now]:
|
|
del _pending[k]
|
|
|
|
|
|
def _fail(kind: str, nxt: str | None = None) -> RedirectResponse:
|
|
q = {"error": kind}
|
|
if nxt and nxt != "/":
|
|
q["next"] = nxt
|
|
resp = RedirectResponse(f"/login?{urllib.parse.urlencode(q)}", status_code=302)
|
|
resp.delete_cookie(STATE_COOKIE, path=COOKIE_PATH)
|
|
return resp
|
|
|
|
|
|
@router.get("/api/auth/methods", responses=_r(schemas.AuthMethods))
|
|
def methods(request: Request):
|
|
"""How the login page signs people in: the provider's button (and the
|
|
other apps the same account opens, for its one-line explainer), or the mail."""
|
|
if on_owner_surface(request):
|
|
return {"oidc": False, "provider": None, "apps": [], "passkey": True,
|
|
"locked": request.app.state.ai.security_state.remote_locked()}
|
|
if not enabled():
|
|
return {"oidc": False, "provider": None, "apps": []}
|
|
return {"oidc": True, "provider": PROVIDER_NAME, "apps": [a["label"] for a in APPS]}
|
|
|
|
|
|
@router.get("/api/auth/oidc/start")
|
|
def start(request: Request, next: str = "/", lc: str = ""):
|
|
"""Off to the provider: ``next`` is where to land afterwards. ``lc`` is a
|
|
one-time Pocket ID login code (an invitation): it signs them in at the
|
|
provider first, which then carries on to this sign-in's consent step
|
|
(:func:`_through_code_page`)."""
|
|
if not enabled() or not on_guest_surface(request):
|
|
raise HTTPException(404, "not found")
|
|
nxt = safe_next(next)
|
|
try:
|
|
authorize = discovery()["authorization_endpoint"]
|
|
except OidcError as e:
|
|
log.warning("oidc start: %s", e)
|
|
return _fail("failed", nxt)
|
|
state, nonce, verifier = (secrets.token_urlsafe(24), secrets.token_urlsafe(24),
|
|
secrets.token_urlsafe(48))
|
|
now = time.time()
|
|
with _lock:
|
|
_prune(now)
|
|
_pending[state] = {"nonce": nonce, "verifier": verifier, "next": nxt,
|
|
"exp": now + STATE_TTL_S}
|
|
query = urllib.parse.urlencode({
|
|
"response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI,
|
|
"scope": SCOPES, "state": state, "nonce": nonce,
|
|
"code_challenge": _b64e(hashlib.sha256(verifier.encode()).digest()),
|
|
"code_challenge_method": "S256"})
|
|
url = f"{authorize}?{query}"
|
|
if lc:
|
|
if not re.fullmatch(r"[A-Za-z0-9]{6,128}", lc):
|
|
return _fail("expired", nxt)
|
|
url = _through_code_page(lc, url)
|
|
resp = RedirectResponse(url, status_code=302)
|
|
resp.set_cookie(STATE_COOKIE, state, max_age=STATE_TTL_S, httponly=True,
|
|
secure=session.secure(request), samesite="lax", path=COOKIE_PATH)
|
|
return resp
|
|
|
|
|
|
def _through_code_page(lc: str, authorize_url: str) -> str:
|
|
"""Where an invitation's browser goes: Pocket ID's login-code page, which
|
|
then continues to this sign-in's consent step. That page only redirects to
|
|
Pocket ID's own pages, not to ``/authorize`` — so the hub opens the
|
|
authorize request itself (no cookies: the interaction it creates isn't
|
|
tied to a browser) and hands the code page the ``/interaction?interaction=``
|
|
it answered with. Failing that, the code page alone: it signs them in at
|
|
Pocket ID, and the *Continue* button here does the rest."""
|
|
origin = _origin(ISSUER)
|
|
fallback = f"{origin}/lc/{lc}"
|
|
try:
|
|
with httpx.Client(timeout=10, transport=TRANSPORT, follow_redirects=False) as c:
|
|
r = c.get(authorize_url)
|
|
except httpx.HTTPError as e:
|
|
log.warning("oidc invite: authorize request failed: %s", e)
|
|
return fallback
|
|
loc = urllib.parse.urlsplit(r.headers.get("location") or "")
|
|
interaction = dict(urllib.parse.parse_qsl(loc.query)).get("interaction", "")
|
|
if r.status_code not in (301, 302, 303, 307, 308) or loc.path != "/interaction" \
|
|
or (loc.netloc and f"{loc.scheme}://{loc.netloc}" != origin) \
|
|
or not re.fullmatch(r"[A-Za-z0-9_.~-]{8,200}", interaction):
|
|
log.warning("oidc invite: no interaction from the authorize request (%s %s)",
|
|
r.status_code, r.headers.get("location", "")[:120])
|
|
return fallback
|
|
target = f"/interaction?interaction={interaction}"
|
|
return f"{fallback}?redirect={urllib.parse.quote(target, safe='')}"
|
|
|
|
|
|
def _guest_for(deps, claims: dict) -> tuple[dict | None, str]:
|
|
"""The guest a provider account is, and why not when it's nobody."""
|
|
groups = claims.get("groups")
|
|
if isinstance(groups, list) and GUEST_GROUP and GUEST_GROUP not in groups:
|
|
return None, f"not in the {GUEST_GROUP!r} group"
|
|
u = deps.users.by_idp(claims["sub"])
|
|
if u is None:
|
|
email = claims.get("email") or ""
|
|
hit = deps.users.by_email(email) if email else None
|
|
# Only a guest the provider hasn't been tied to yet — never moves a link.
|
|
if hit and not hit.get("idpId"):
|
|
deps.users.set_idp(hit["id"], claims["sub"])
|
|
u = deps.users.get(hit["id"])
|
|
if u is None:
|
|
return None, "no guest with this account"
|
|
if u.get("disabled"):
|
|
return None, "guest disabled"
|
|
return u, ""
|
|
|
|
|
|
@router.get("/api/auth/oidc/callback")
|
|
def callback(deps: State, request: Request, code: str = "", state: str = "",
|
|
error: str = ""):
|
|
"""Back from the provider: check the state this browser started with,
|
|
trade the code for tokens, check the ID token, open the guest's session."""
|
|
if not enabled() or not on_guest_surface(request):
|
|
raise HTTPException(404, "not found")
|
|
mine = request.cookies.get(STATE_COOKIE, "")
|
|
with _lock:
|
|
_prune(time.time())
|
|
pending = _pending.pop(state, None) if state else None
|
|
nxt = pending["next"] if pending else "/"
|
|
if error:
|
|
return _fail("not_allowed" if error in ("access_denied", "unauthorized_client")
|
|
else "failed", nxt)
|
|
if not pending or not mine or not hmac.compare_digest(mine, state):
|
|
return _fail("expired", nxt)
|
|
try:
|
|
claims = verify_id_token(_exchange(code, pending["verifier"])["id_token"],
|
|
pending["nonce"])
|
|
except OidcError as e:
|
|
log.warning("oidc callback: %s", e)
|
|
security.record(deps, "oidc_refused", request=request, detail=f"token: {e}")
|
|
return _fail("failed", nxt)
|
|
u, why = _guest_for(deps, claims)
|
|
if u is None:
|
|
security.record(deps, "oidc_refused", request=request,
|
|
detail=f"{claims.get('preferred_username') or claims['sub']}: {why}")
|
|
return _fail("not_allowed", nxt)
|
|
resp = RedirectResponse(nxt, status_code=302)
|
|
session.open_session(deps, request, resp, u["id"])
|
|
resp.delete_cookie(STATE_COOKIE, path=COOKIE_PATH)
|
|
return resp
|