Found by username or email, an admin's account (the owner's) would have been renamed to the guest and lost isAdmin. The sync now refuses and says why. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
255 lines
9.8 KiB
Python
255 lines
9.8 KiB
Python
"""
|
|
The guests' identity provider — Pocket ID (docs/multi-user.md, round 9).
|
|
|
|
Settings → Users stays where the owner manages guests; this module mirrors
|
|
each guest into Pocket ID through its admin API so one account signs them in
|
|
to the ai-agent *and* the other apps Pocket ID guards (Jellyfin). The hub is
|
|
the source of truth for who exists and which apps they get; Pocket ID only
|
|
holds the login (passkeys, mailed codes).
|
|
|
|
* ``POCKET_ID_API_KEY`` — Pocket ID's ``STATIC_API_KEY`` (``X-API-KEY``);
|
|
unset ⇒ nothing is mirrored.
|
|
* ``OIDC_INTERNAL_URL`` — where the hub reaches Pocket ID (the docker network,
|
|
``http://pocket-id:1411``); defaults to ``OIDC_ISSUER``.
|
|
* ``IDP_GUEST_GROUP`` (``ai-agent``) — every guest is in it; the ai-agent's
|
|
OIDC client is restricted to it at Pocket ID.
|
|
* ``IDP_APPS`` — the other apps, ``group|label|url`` comma-separated
|
|
(``jellyfin|Jellyfin|https://netflix.gabvdl.xyz``): a per-guest switch on
|
|
their page (``apps`` in users.json, off by default) puts them in ``group``.
|
|
|
|
A Pocket ID user's id is the OIDC ``sub`` the login hands back; it is kept as
|
|
``idpId`` on the guest's record. Groups the hub doesn't know about (one the
|
|
owner added by hand in Pocket ID) are left alone. Nothing here raises into a
|
|
request: :func:`sync` answers ``{ok, error}``, stored as ``idpSync``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import logging
|
|
import os
|
|
import re
|
|
|
|
import httpx
|
|
|
|
log = logging.getLogger("ai-agent.idp")
|
|
|
|
ISSUER = os.environ.get("OIDC_ISSUER", "").strip().rstrip("/")
|
|
INTERNAL_URL = (os.environ.get("OIDC_INTERNAL_URL", "").strip() or ISSUER).rstrip("/")
|
|
API_KEY = os.environ.get("POCKET_ID_API_KEY", "").strip()
|
|
GUEST_GROUP = os.environ.get("IDP_GUEST_GROUP", "ai-agent").strip()
|
|
TIMEOUT_S = float(os.environ.get("IDP_TIMEOUT_S", "8"))
|
|
# Pocket ID refuses a login code that lives longer than this (its maxTTL).
|
|
MAX_CODE_TTL_S = 31 * 24 * 3600
|
|
|
|
_GROUP_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,40}$")
|
|
# Tests swap in an ``httpx.MockTransport``.
|
|
TRANSPORT: httpx.BaseTransport | None = None
|
|
|
|
|
|
def _parse_apps(raw: str) -> list[dict]:
|
|
out = []
|
|
for part in raw.split(","):
|
|
bits = [b.strip() for b in part.split("|")]
|
|
if not bits or not _GROUP_RE.match(bits[0]) or bits[0] == GUEST_GROUP:
|
|
continue
|
|
out.append({"group": bits[0], "label": (bits[1] if len(bits) > 1 and bits[1] else bits[0]),
|
|
"url": bits[2] if len(bits) > 2 else ""})
|
|
return out
|
|
|
|
|
|
APPS: list[dict] = _parse_apps(os.environ.get("IDP_APPS", ""))
|
|
|
|
|
|
def enabled() -> bool:
|
|
return bool(INTERNAL_URL and API_KEY)
|
|
|
|
|
|
def app_groups() -> list[str]:
|
|
return [a["group"] for a in APPS]
|
|
|
|
|
|
def managed_groups() -> list[str]:
|
|
"""The groups the hub decides membership of — every other one is left alone."""
|
|
return [GUEST_GROUP, *app_groups()]
|
|
|
|
|
|
def wanted_groups(u: dict) -> list[str]:
|
|
"""The groups a guest belongs in: the guest group, and each app switched on."""
|
|
on = u.get("apps") or {}
|
|
return [GUEST_GROUP, *(g for g in app_groups() if on.get(g))]
|
|
|
|
|
|
def clean_apps(raw) -> dict[str, bool]:
|
|
"""``{group: bool}`` as stored — any well-formed group name (an app taken
|
|
out of ``IDP_APPS`` later keeps its switch, harmlessly)."""
|
|
if not isinstance(raw, dict):
|
|
return {}
|
|
return {k: bool(v) for k, v in raw.items()
|
|
if isinstance(k, str) and _GROUP_RE.match(k)}
|
|
|
|
|
|
def status() -> dict:
|
|
"""What Settings → Users shows about the provider."""
|
|
return {"enabled": enabled(), "issuer": ISSUER or None, "apps": [dict(a) for a in APPS]}
|
|
|
|
|
|
class IdpError(RuntimeError):
|
|
pass
|
|
|
|
|
|
# ── the admin API ────────────────────────────────────────────────────────────
|
|
def _http() -> httpx.Client:
|
|
return httpx.Client(base_url=INTERNAL_URL, timeout=TIMEOUT_S, transport=TRANSPORT,
|
|
headers={"X-API-KEY": API_KEY, "Accept": "application/json"})
|
|
|
|
|
|
def _call(c: httpx.Client, method: str, path: str, *, json=None, params=None,
|
|
ok404: bool = False):
|
|
try:
|
|
r = c.request(method, path, json=json, params=params)
|
|
except httpx.HTTPError as e:
|
|
raise IdpError(f"Pocket ID unreachable: {e}") from None
|
|
if ok404 and r.status_code == 404:
|
|
return None
|
|
if r.status_code >= 400:
|
|
try:
|
|
why = r.json().get("error") or r.text
|
|
except ValueError:
|
|
why = r.text
|
|
raise IdpError(f"Pocket ID {method} {path}: {r.status_code} {str(why)[:200]}")
|
|
if not r.content:
|
|
return None
|
|
try:
|
|
return r.json()
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def _rows(page) -> list[dict]:
|
|
if isinstance(page, dict):
|
|
return [x for x in page.get("data") or [] if isinstance(x, dict)]
|
|
return [x for x in page or [] if isinstance(x, dict)]
|
|
|
|
|
|
def _find_user(c: httpx.Client, username: str, email: str) -> dict | None:
|
|
for q, key in ((username, "username"), (email, "email")):
|
|
if not q:
|
|
continue
|
|
for row in _rows(_call(c, "GET", "/api/users", params={"search": q})):
|
|
if (row.get(key) or "").lower() == q.lower():
|
|
return row
|
|
return None
|
|
|
|
|
|
def _group_ids(c: httpx.Client, names: list[str]) -> dict[str, str]:
|
|
"""``{name: id}`` for ``names``, creating any that doesn't exist yet."""
|
|
out: dict[str, str] = {}
|
|
for name in names:
|
|
hit = next((g for g in _rows(_call(c, "GET", "/api/user-groups",
|
|
params={"search": name}))
|
|
if g.get("name") == name), None)
|
|
if hit is None:
|
|
label = next((a["label"] for a in APPS if a["group"] == name),
|
|
"ai-agent" if name == GUEST_GROUP else name)
|
|
hit = _call(c, "POST", "/api/user-groups",
|
|
json={"name": name, "friendlyName": label}) or {}
|
|
if hit.get("id"):
|
|
out[name] = hit["id"]
|
|
return out
|
|
|
|
|
|
def _user_body(u: dict, rec: dict | None) -> dict:
|
|
name = (u.get("name") or u["id"]).strip()
|
|
return {"username": u["id"], "email": u.get("email") or None,
|
|
# The owner typed the address; the old login proved it by mail.
|
|
"emailVerified": True,
|
|
"firstName": name[:50], "lastName": "", "displayName": name[:100],
|
|
"isAdmin": False, "disabled": bool(u.get("disabled")),
|
|
"locale": (rec or {}).get("locale")}
|
|
|
|
|
|
def _push(c: httpx.Client, u: dict) -> str:
|
|
"""Create or update ``u``'s Pocket ID user and set the hub's groups on it;
|
|
their Pocket ID id."""
|
|
rec = _call(c, "GET", f"/api/users/{u['idpId']}", ok404=True) if u.get("idpId") else None
|
|
if rec is None:
|
|
rec = _find_user(c, u["id"], u.get("email") or "")
|
|
if rec is not None and rec.get("isAdmin"):
|
|
# Found by username or email, it is an admin's account (the owner's):
|
|
# a guest's sync would rename it and drop isAdmin. Never touch it.
|
|
raise IdpError(f"Pocket ID user {rec.get('username')!r} is an admin — "
|
|
"give the guest another id or email")
|
|
if rec is None:
|
|
rec = _call(c, "POST", "/api/users", json=_user_body(u, None)) or {}
|
|
else:
|
|
rec = _call(c, "PUT", f"/api/users/{rec['id']}", json=_user_body(u, rec)) or rec
|
|
pid = rec.get("id")
|
|
if not pid:
|
|
raise IdpError("Pocket ID returned no user id")
|
|
ids = _group_ids(c, managed_groups())
|
|
managed = set(ids.values())
|
|
current = _call(c, "GET", f"/api/users/{pid}/groups") or rec.get("userGroups") or []
|
|
keep = [g["id"] for g in _rows(current) if g.get("id") and g["id"] not in managed]
|
|
want = [ids[g] for g in wanted_groups(u) if g in ids]
|
|
_call(c, "PUT", f"/api/users/{pid}/user-groups", json={"userGroupIds": keep + want})
|
|
return pid
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def sync(deps, u: dict) -> dict:
|
|
"""Mirror one guest into Pocket ID; ``{ok, error, at}``, also stored on
|
|
their record (with their Pocket ID id) for Settings → Users."""
|
|
if not enabled():
|
|
return {"ok": False, "error": "Pocket ID is not configured", "at": _now_iso()}
|
|
try:
|
|
with _http() as c:
|
|
pid = _push(c, u)
|
|
state = {"ok": True, "error": None, "at": _now_iso()}
|
|
except IdpError as e:
|
|
log.warning("idp sync of %s failed: %s", u.get("id"), e)
|
|
pid, state = None, {"ok": False, "error": str(e), "at": _now_iso()}
|
|
deps.users.set_idp(u["id"], pid, state)
|
|
return state
|
|
|
|
|
|
def sync_all(deps) -> dict[str, dict]:
|
|
return {u["id"]: sync(deps, u) for u in deps.users.all()}
|
|
|
|
|
|
def remove(u: dict) -> str | None:
|
|
"""Delete a deleted guest's Pocket ID user; the error, if any."""
|
|
if not enabled():
|
|
return None
|
|
try:
|
|
with _http() as c:
|
|
pid = u.get("idpId")
|
|
if not pid:
|
|
rec = _find_user(c, u["id"], u.get("email") or "")
|
|
pid = rec.get("id") if rec else None
|
|
if pid:
|
|
_call(c, "DELETE", f"/api/users/{pid}", ok404=True)
|
|
return None
|
|
except IdpError as e:
|
|
log.warning("idp delete of %s failed: %s", u.get("id"), e)
|
|
return str(e)
|
|
|
|
|
|
def login_code(deps, u: dict, ttl_s: int) -> str:
|
|
"""A one-time Pocket ID login code for ``u`` (synced first); raises
|
|
:class:`IdpError` when Pocket ID can't make one."""
|
|
state = sync(deps, u)
|
|
if not state["ok"]:
|
|
raise IdpError(state["error"])
|
|
pid = (deps.users.get(u["id"]) or {}).get("idpId")
|
|
with _http() as c:
|
|
out = _call(c, "POST", f"/api/users/{pid}/one-time-access-token",
|
|
json={"ttl": max(60, min(int(ttl_s), MAX_CODE_TTL_S))}) or {}
|
|
token = out.get("token") or ""
|
|
if not re.fullmatch(r"[A-Za-z0-9]{6,128}", token):
|
|
raise IdpError("Pocket ID returned no login code")
|
|
return token
|