Since 2026-11-25 nanobanana, video-extract, 3d-gen, 3d-render, matomo, movies and meta are live plugins with their own proxies and managed grants, but the core still served the old path next to them — and its hub editions won over the plugin skills on workers. This finishes the move (form ai-agent-moves-to-ai-agent-plugins_o2qxmd, move A). Rebased on41665fa2, which had already removed the core's Meta Business. - gone: toolproxy/{matomo,media,webroutes,owned,catalog}.py, the nanobanana / 3d-gen / 3d-render / video-extract / matomo / movies routes and the movies webhook, cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo, movies}, the guests' `tools` groups (users store, Caller.tool_groups, Me/GuestUser.tools, tools.matomoSites), the User page's Paid tools and Tools budget panels - kept: the /proxy/tools door (tokens, whoami — now the caller's plugins and spend — and the shared client), the tool ledger, the tools chip, a guest job's tool token (c6e15991: tool_scope still gives one with plugin skills) - labsync: a plugin skill wins over a lab skill of the same name; plugin skills with a proxy keep their hub.json - guest runs get their plugins' skills on spawn, resume, reply, fork and No project runs alike (deps passed to scope_for / scratch_scope everywhere) - Movies brings Jellyfin when the movies grant comes on (new guest, or the owner's switch) - plugins/carryover_tools.py: tool groups → grants / installs (never over an explicit grant), Meta keys + saved days (only where the plugin has none), Matomo viewers, Seerr users and pending requests, 3d-gen ownership → the plugins' data, once - matomo_sites: users.json tools.matomoSites → the matomo grant's `extraSites` (list grantField, sibling ai-agent-plugins PR), and the grant on for an `analytics` guest — once per guest, so Cel (analytics + site 11 after the groups moved) gets it; an explicit grant only gets extraSites when it has none; waits for a matomo manifest with the field - Me → Budget's Tools card reads the guest's managed plugins Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
491 lines
24 KiB
Python
491 lines
24 KiB
Python
"""Guests through the identity provider (users/oidc.py, users/idp.py): the
|
|
login page's methods, the OIDC round trip against a fake Pocket ID (real RSA
|
|
signatures), the refusals, the mailed login switched off, and the guests
|
|
mirrored into Pocket ID from Settings → Users.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
import urllib.parse
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"GUEST_PUBLIC_URL": "https://claude.example.test",
|
|
"OIDC_ISSUER": "https://login.example.test",
|
|
"OIDC_INTERNAL_URL": "http://pocket-id:1411",
|
|
"OIDC_CLIENT_ID": "cid", "OIDC_CLIENT_SECRET": "csecret",
|
|
"POCKET_ID_API_KEY": "pkey",
|
|
"IDP_APPS": "jellyfin|Jellyfin|https://netflix.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
|
|
import httpx # noqa: E402
|
|
from cryptography.hazmat.primitives import hashes # noqa: E402
|
|
from cryptography.hazmat.primitives.asymmetric import padding, rsa # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
import users.routes as user_routes # noqa: E402
|
|
from users import idp, mailer, oidc # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
ISS, INTERNAL = "https://login.example.test", "http://pocket-id:1411"
|
|
|
|
|
|
def _b64(b: bytes) -> str:
|
|
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
|
|
|
|
|
def _int(n: int) -> str:
|
|
return _b64(n.to_bytes((n.bit_length() + 7) // 8, "big"))
|
|
|
|
|
|
class FakePocketId:
|
|
"""Discovery, JWKS, token endpoint and the admin API, in memory."""
|
|
|
|
def __init__(self):
|
|
self.key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
self.codes: dict[str, dict] = {} # code → claims to sign
|
|
self.users: dict[str, dict] = {}
|
|
self.groups: dict[str, dict] = {"g-other": {"id": "g-other", "name": "family"}}
|
|
self.calls: list[tuple[str, str, dict | None]] = []
|
|
self.down = False
|
|
self.no_interaction = False
|
|
self.authorized: dict | None = None
|
|
self.n = 0
|
|
|
|
def sign(self, claims: dict, key=None) -> str:
|
|
head = _b64(json.dumps({"alg": "RS256", "kid": "k1", "typ": "JWT"}).encode())
|
|
body = _b64(json.dumps(claims).encode())
|
|
sig = (key or self.key).sign(f"{head}.{body}".encode(), padding.PKCS1v15(),
|
|
hashes.SHA256())
|
|
return f"{head}.{body}.{_b64(sig)}"
|
|
|
|
def _id(self, prefix):
|
|
self.n += 1
|
|
return f"{prefix}-{self.n}"
|
|
|
|
def handler(self, req: httpx.Request) -> httpx.Response:
|
|
if self.down:
|
|
raise httpx.ConnectError("down", request=req)
|
|
url, path = str(req.url), req.url.path
|
|
if req.url.host == "login.example.test" and path == "/authorize":
|
|
# Pocket ID answers an authorize request with its consent step.
|
|
self.authorized = dict(req.url.params)
|
|
if self.no_interaction:
|
|
return httpx.Response(400, json={"error": "invalid_request"})
|
|
return httpx.Response(302, headers={"location": "/interaction?interaction=ia_Z9x-42abcdef"})
|
|
body = json.loads(req.content) if req.content and req.headers.get(
|
|
"content-type", "").startswith("application/json") else None
|
|
self.calls.append((req.method, path, body))
|
|
if path == "/.well-known/openid-configuration":
|
|
return httpx.Response(200, json={
|
|
"issuer": ISS, "authorization_endpoint": f"{ISS}/authorize",
|
|
"token_endpoint": f"{INTERNAL}/api/oidc/token",
|
|
"jwks_uri": f"{INTERNAL}/.well-known/jwks.json"})
|
|
if path == "/.well-known/jwks.json":
|
|
pub = self.key.public_key().public_numbers()
|
|
return httpx.Response(200, json={"keys": [
|
|
{"kty": "RSA", "alg": "RS256", "kid": "k1", "n": _int(pub.n), "e": _int(pub.e)}]})
|
|
if path == "/api/oidc/token":
|
|
form = dict(urllib.parse.parse_qsl(req.content.decode()))
|
|
auth = req.headers.get("authorization", "")
|
|
if auth != "Basic " + base64.b64encode(b"cid:csecret").decode():
|
|
return httpx.Response(401, json={"error": "invalid_client"})
|
|
claims = self.codes.pop(form.get("code"), None)
|
|
if claims is None or form.get("redirect_uri") != oidc.REDIRECT_URI \
|
|
or not form.get("code_verifier"):
|
|
return httpx.Response(400, json={"error": "invalid_grant"})
|
|
token = claims.pop("_raw", None) or self.sign(claims)
|
|
return httpx.Response(200, json={"access_token": "at", "id_token": token})
|
|
assert req.headers.get("x-api-key") == "pkey", url
|
|
return self.admin(req.method, path, body, dict(req.url.params))
|
|
|
|
def admin(self, method, path, body, params):
|
|
parts = path.strip("/").split("/") # api, users, <id>, ...
|
|
if parts[:2] == ["api", "users"]:
|
|
if len(parts) == 2 and method == "GET":
|
|
q = params.get("search", "").lower()
|
|
return httpx.Response(200, json={"data": [
|
|
u for u in self.users.values()
|
|
if q in u["username"].lower() or q in (u.get("email") or "").lower()]})
|
|
if len(parts) == 2 and method == "POST":
|
|
u = {**body, "id": self._id("u"), "groups": []}
|
|
self.users[u["id"]] = u
|
|
return httpx.Response(201, json=u)
|
|
u = self.users.get(parts[2])
|
|
if u is None:
|
|
return httpx.Response(404, json={"error": "not found"})
|
|
if len(parts) == 3 and method == "GET":
|
|
return httpx.Response(200, json=u)
|
|
if len(parts) == 3 and method == "PUT":
|
|
u.update({k: v for k, v in body.items() if k != "id"})
|
|
return httpx.Response(200, json=u)
|
|
if len(parts) == 3 and method == "DELETE":
|
|
del self.users[parts[2]]
|
|
return httpx.Response(204)
|
|
if parts[3:] == ["groups"]:
|
|
return httpx.Response(200, json=[self.groups[g] for g in u["groups"]])
|
|
if parts[3:] == ["user-groups"]:
|
|
u["groups"] = list(body["userGroupIds"])
|
|
return httpx.Response(200, json=u)
|
|
if parts[3:] == ["one-time-access-token"]:
|
|
return httpx.Response(201, json={"token": f"LC{parts[2].replace('-', '')}x9"})
|
|
if parts[:2] == ["api", "user-groups"]:
|
|
if method == "GET":
|
|
q = params.get("search", "")
|
|
return httpx.Response(200, json={"data": [
|
|
g for g in self.groups.values() if q in g["name"]]})
|
|
if method == "POST":
|
|
g = {"id": self._id("g"), "name": body["name"]}
|
|
self.groups[g["id"]] = g
|
|
return httpx.Response(201, json=g)
|
|
return httpx.Response(404, json={"error": f"unexpected {method} {path}"})
|
|
|
|
def group_names(self, pid: str) -> list[str]:
|
|
return sorted(self.groups[g]["name"] for g in self.users[pid]["groups"])
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
def setUp(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
self.fake = FakePocketId()
|
|
transport = httpx.MockTransport(self.fake.handler)
|
|
for mod in (oidc, idp):
|
|
self.addCleanup(setattr, mod, "TRANSPORT", mod.TRANSPORT)
|
|
mod.TRANSPORT = transport
|
|
oidc._discovery.update(at=0.0, doc=None)
|
|
oidc._jwks.update(at=0.0, keys={})
|
|
oidc._pending.clear()
|
|
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
|
|
|
|
def browser(self) -> TestClient:
|
|
return TestClient(main.app, base_url="https://claude.example.test",
|
|
follow_redirects=False)
|
|
|
|
def owner(self) -> TestClient:
|
|
return TestClient(main.app)
|
|
|
|
def claims(self, state_nonce: str, **over) -> dict:
|
|
now = int(time.time())
|
|
c = {"iss": ISS, "aud": "cid", "sub": "sub-dom", "exp": now + 300, "iat": now,
|
|
"nonce": state_nonce, "email": "dom@example.com",
|
|
"preferred_username": "dom", "groups": ["ai-agent"]}
|
|
c.update(over)
|
|
return {k: v for k, v in c.items() if v is not None}
|
|
|
|
def start(self, c: TestClient, nxt: str = "/c/42") -> tuple[str, str]:
|
|
"""Start a sign-in; ``(state, nonce)`` the provider was handed."""
|
|
r = c.get("/api/auth/oidc/start", params={"next": nxt})
|
|
self.assertEqual(r.status_code, 302, r.text)
|
|
q = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(r.headers["location"]).query))
|
|
return q["state"], q["nonce"]
|
|
|
|
def finish(self, c: TestClient, state: str, claims: dict, *, code: str = "code1",
|
|
callback_state: str | None = None):
|
|
self.fake.codes[code] = claims
|
|
return c.get("/api/auth/oidc/callback",
|
|
params={"code": code, "state": callback_state or state})
|
|
|
|
|
|
class Login(Base):
|
|
def test_methods_say_oidc(self):
|
|
r = self.browser().get("/api/auth/methods")
|
|
self.assertEqual(r.json(), {"oidc": True, "provider": "gabvdl.xyz",
|
|
"apps": ["Jellyfin"]})
|
|
|
|
def test_start_redirects_to_the_provider_with_pkce(self):
|
|
c = self.browser()
|
|
r = c.get("/api/auth/oidc/start", params={"next": "/c/1"})
|
|
self.assertEqual(r.status_code, 302)
|
|
loc = urllib.parse.urlsplit(r.headers["location"])
|
|
self.assertEqual(f"{loc.scheme}://{loc.netloc}{loc.path}", f"{ISS}/authorize")
|
|
q = dict(urllib.parse.parse_qsl(loc.query))
|
|
self.assertEqual(q["client_id"], "cid")
|
|
self.assertEqual(q["redirect_uri"], "https://claude.example.test/api/auth/oidc/callback")
|
|
self.assertEqual(q["code_challenge_method"], "S256")
|
|
self.assertIn("groups", q["scope"].split())
|
|
self.assertEqual(r.cookies.get(oidc.STATE_COOKIE), q["state"])
|
|
|
|
def test_start_with_a_login_code_goes_through_the_code_page_to_the_interaction(self):
|
|
c = self.browser()
|
|
r = c.get("/api/auth/oidc/start", params={"lc": "Abc123", "next": "/c/7"})
|
|
self.assertEqual(r.status_code, 302)
|
|
self.assertEqual(r.headers["location"],
|
|
f"{ISS}/lc/Abc123?redirect=%2Finteraction%3Finteraction%3Dia_Z9x-42abcdef")
|
|
# the hub opened the authorize request itself, with this browser's state
|
|
self.assertEqual(self.fake.authorized["client_id"], "cid")
|
|
self.assertEqual(self.fake.authorized["state"], r.cookies.get(oidc.STATE_COOKIE))
|
|
# …so the callback that follows the interaction still matches the cookie
|
|
DEPS.users.set_idp(self.dom["id"], "sub-dom")
|
|
state, nonce = self.fake.authorized["state"], self.fake.authorized["nonce"]
|
|
done = self.finish(c, state, self.claims(nonce))
|
|
self.assertEqual(done.headers["location"], "/c/7")
|
|
self.assertIn(SESSION_COOKIE, done.cookies)
|
|
|
|
def test_login_code_falls_back_to_the_code_page_alone(self):
|
|
self.fake.no_interaction = True
|
|
r = self.browser().get("/api/auth/oidc/start", params={"lc": "Abc123"})
|
|
self.assertEqual(r.headers["location"], f"{ISS}/lc/Abc123")
|
|
self.fake.no_interaction, self.fake.down = False, True
|
|
oidc._discovery.update(at=time.time(), doc={
|
|
"authorization_endpoint": f"{ISS}/authorize",
|
|
"token_endpoint": f"{INTERNAL}/api/oidc/token",
|
|
"jwks_uri": f"{INTERNAL}/.well-known/jwks.json"})
|
|
r = self.browser().get("/api/auth/oidc/start", params={"lc": "Abc123"})
|
|
self.assertEqual(r.headers["location"], f"{ISS}/lc/Abc123")
|
|
bad = self.browser().get("/api/auth/oidc/start", params={"lc": "../evil"})
|
|
self.assertIn("error=expired", bad.headers["location"])
|
|
|
|
def test_not_on_the_admin_host(self):
|
|
r = self.owner().get("/api/auth/oidc/start", headers=OWNER_H, follow_redirects=False)
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
def test_round_trip_opens_the_guests_session(self):
|
|
DEPS.users.set_idp(self.dom["id"], "sub-dom")
|
|
c = self.browser()
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, self.claims(nonce))
|
|
self.assertEqual(r.status_code, 302, r.text)
|
|
self.assertEqual(r.headers["location"], "/c/42")
|
|
self.assertIn(SESSION_COOKIE, r.cookies)
|
|
me = c.get("/api/me").json()
|
|
self.assertEqual((me["id"], me["role"]), (self.dom["id"], "guest"))
|
|
self.assertIsNotNone(DEPS.users.get(self.dom["id"])["lastLoginAt"])
|
|
# the state is spent: replaying the callback goes nowhere
|
|
again = self.finish(c, state, self.claims(nonce), code="code2")
|
|
self.assertIn("error=expired", again.headers["location"])
|
|
|
|
def test_email_ties_a_guest_once(self):
|
|
c = self.browser()
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, self.claims(nonce, sub="sub-new"))
|
|
self.assertEqual(r.headers["location"], "/c/42")
|
|
self.assertEqual(DEPS.users.get(self.dom["id"])["idpId"], "sub-new")
|
|
# another provider account with the same address doesn't take it over
|
|
c2 = self.browser()
|
|
state, nonce = self.start(c2)
|
|
r = self.finish(c2, state, self.claims(nonce, sub="sub-other"))
|
|
self.assertIn("error=not_allowed", r.headers["location"])
|
|
self.assertEqual(DEPS.users.get(self.dom["id"])["idpId"], "sub-new")
|
|
|
|
def test_state_must_match_this_browser(self):
|
|
DEPS.users.set_idp(self.dom["id"], "sub-dom")
|
|
victim, attacker = self.browser(), self.browser()
|
|
state, nonce = self.start(victim)
|
|
r = self.finish(attacker, state, self.claims(nonce))
|
|
self.assertIn("error=expired", r.headers["location"])
|
|
self.assertNotIn(SESSION_COOKIE, r.cookies)
|
|
|
|
def test_token_checks(self):
|
|
DEPS.users.set_idp(self.dom["id"], "sub-dom")
|
|
other_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
cases = {
|
|
"nonce": lambda n: self.claims("wrong"),
|
|
"aud": lambda n: self.claims(n, aud="someone-else"),
|
|
"iss": lambda n: self.claims(n, iss="https://evil.example"),
|
|
"exp": lambda n: self.claims(n, exp=int(time.time()) - 3600),
|
|
"signature": lambda n: {"_raw": self.fake.sign(self.claims(n), other_key)},
|
|
}
|
|
for what, make in cases.items():
|
|
with self.subTest(what):
|
|
c = self.browser()
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, make(nonce))
|
|
self.assertIn("error=failed", r.headers["location"], what)
|
|
self.assertNotIn(SESSION_COOKIE, r.cookies)
|
|
|
|
def test_refusals(self):
|
|
c = self.browser()
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, self.claims(nonce, sub="nobody", email="nobody@x.test"))
|
|
self.assertIn("error=not_allowed", r.headers["location"])
|
|
self.assertTrue(DEPS.security_log.events(kinds={"oidc_refused"}, limit=5))
|
|
DEPS.users.set_idp(self.dom["id"], "sub-dom")
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, self.claims(nonce, groups=["jellyfin"]))
|
|
self.assertIn("error=not_allowed", r.headers["location"])
|
|
DEPS.users.update(self.dom["id"], {"disabled": True})
|
|
state, nonce = self.start(c)
|
|
r = self.finish(c, state, self.claims(nonce))
|
|
self.assertIn("error=not_allowed", r.headers["location"])
|
|
|
|
def test_provider_error_comes_back_as_not_allowed(self):
|
|
c = self.browser()
|
|
state, _ = self.start(c)
|
|
r = c.get("/api/auth/oidc/callback", params={"state": state, "error": "access_denied"})
|
|
self.assertIn("error=not_allowed", r.headers["location"])
|
|
|
|
def test_the_mailed_login_is_off(self):
|
|
c = self.browser()
|
|
r = c.post("/api/auth/request-link", json={"email": "dom@example.com"})
|
|
self.assertEqual(r.status_code, 410)
|
|
self.assertEqual(r.json()["detail"]["kind"], "oidc")
|
|
token = DEPS.auth.mint_link(self.dom["id"])
|
|
self.assertEqual(c.post("/api/auth/login", json={"token": token}).status_code, 410)
|
|
|
|
def test_old_sessions_stay_valid(self):
|
|
c = self.browser()
|
|
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
self.assertEqual(c.get("/api/me").json()["id"], self.dom["id"])
|
|
|
|
def test_safe_next(self):
|
|
for raw in ("//evil.example", "https://evil.example/x", "/api/users", "/login",
|
|
"javascript:alert(1)", "", None, "/\\evil"):
|
|
self.assertEqual(oidc.safe_next(raw), "/", raw)
|
|
self.assertEqual(oidc.safe_next("/c/9?x=1"), "/c/9?x=1")
|
|
|
|
|
|
def _movies_plugin(test: unittest.TestCase, default_on: bool = True) -> None:
|
|
"""The managed ``movies`` plugin, installed for the owner for one test."""
|
|
import json
|
|
import tempfile
|
|
from plugins.store import OWNER_UID
|
|
src = pathlib.Path(tempfile.mkdtemp()) / "movies"
|
|
src.mkdir()
|
|
(src / "plugin.json").write_text(json.dumps({
|
|
"schema": 1, "id": "movies", "name": "Movies", "version": "1.0.0",
|
|
"managed": {"defaultForGuests": default_on}}))
|
|
DEPS.plugin_store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
test.addCleanup(DEPS.plugin_store.uninstall, OWNER_UID, "movies")
|
|
|
|
|
|
class Mirror(Base):
|
|
def test_create_mirrors_the_guest_with_the_guest_group(self):
|
|
_movies_plugin(self)
|
|
r = self.owner().post("/api/users", headers=OWNER_H,
|
|
json={"email": "claire@example.com", "name": "Claire"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
u = r.json()
|
|
self.assertTrue(u["idp"]["ok"], u["idp"])
|
|
pid = u["idp"]["id"]
|
|
rec = self.fake.users[pid]
|
|
self.assertEqual((rec["username"], rec["email"], rec["firstName"], rec["isAdmin"]),
|
|
(u["id"], "claire@example.com", "Claire", False))
|
|
# The movies plugin is on for a new guest, and Movies brings the Jellyfin app.
|
|
self.assertEqual(self.fake.group_names(pid), ["ai-agent", "jellyfin"])
|
|
|
|
def test_the_movies_grant_coming_on_brings_jellyfin(self):
|
|
_movies_plugin(self, default_on=False)
|
|
r = self.owner().post("/api/users", headers=OWNER_H,
|
|
json={"email": "claire@example.com", "name": "Claire"})
|
|
u = r.json()
|
|
pid = u["idp"]["id"]
|
|
self.assertEqual(self.fake.group_names(pid), ["ai-agent"])
|
|
r = self.owner().put(f"/api/plugins/managed/grants/{u['id']}/movies", headers=OWNER_H,
|
|
json={"enabled": True})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(DEPS.users.get(u["id"])["apps"], {"jellyfin": True})
|
|
self.assertEqual(self.fake.group_names(pid), ["ai-agent", "jellyfin"])
|
|
# Switched off by hand, it stays off — a later grant change that isn't
|
|
# Movies coming on leaves it.
|
|
self.owner().put(f"/api/users/{u['id']}", headers=OWNER_H, json={"apps": {"jellyfin": False}})
|
|
self.owner().put(f"/api/plugins/managed/grants/{u['id']}/movies", headers=OWNER_H,
|
|
json={"enabled": True})
|
|
self.assertEqual(DEPS.users.get(u["id"])["apps"], {"jellyfin": False})
|
|
|
|
def test_apps_and_disable_follow_the_hub_and_keep_foreign_groups(self):
|
|
idp.sync(DEPS, self.dom)
|
|
pid = DEPS.users.get(self.dom["id"])["idpId"]
|
|
self.fake.users[pid]["groups"].append("g-other") # added by hand in Pocket ID
|
|
r = self.owner().put(f"/api/users/{self.dom['id']}", headers=OWNER_H,
|
|
json={"apps": {"jellyfin": True}})
|
|
self.assertEqual(r.json()["apps"], {"jellyfin": True})
|
|
self.assertEqual(self.fake.group_names(pid), ["ai-agent", "family", "jellyfin"])
|
|
self.owner().put(f"/api/users/{self.dom['id']}", headers=OWNER_H,
|
|
json={"apps": {"jellyfin": False}, "disabled": True})
|
|
self.assertEqual(self.fake.group_names(pid), ["ai-agent", "family"])
|
|
self.assertTrue(self.fake.users[pid]["disabled"])
|
|
|
|
def test_existing_account_is_found_by_username_not_duplicated(self):
|
|
self.fake.users["u-old"] = {"id": "u-old", "username": self.dom["id"],
|
|
"email": "old@example.com", "groups": []}
|
|
idp.sync(DEPS, self.dom)
|
|
self.assertEqual(DEPS.users.get(self.dom["id"])["idpId"], "u-old")
|
|
self.assertEqual(self.fake.users["u-old"]["email"], "dom@example.com")
|
|
self.assertEqual(len(self.fake.users), 1)
|
|
|
|
def test_an_admin_account_is_never_taken_over(self):
|
|
# The owner's Pocket ID account shares the guest's address: the sync
|
|
# must not rename it nor drop its admin flag.
|
|
self.fake.users["u-owner"] = {"id": "u-owner", "username": "gabrielvidal",
|
|
"email": self.dom["email"], "isAdmin": True,
|
|
"groups": []}
|
|
state = idp.sync(DEPS, self.dom)
|
|
self.assertFalse(state["ok"])
|
|
self.assertIn("admin", state["error"])
|
|
self.assertEqual(self.fake.users["u-owner"]["username"], "gabrielvidal")
|
|
self.assertTrue(self.fake.users["u-owner"]["isAdmin"])
|
|
self.assertFalse(DEPS.users.get(self.dom["id"]).get("idpId"))
|
|
|
|
def test_provider_down_never_breaks_a_save(self):
|
|
self.fake.down = True
|
|
r = self.owner().put(f"/api/users/{self.dom['id']}", headers=OWNER_H,
|
|
json={"name": "Dominique"})
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(r.json()["name"], "Dominique")
|
|
self.assertFalse(r.json()["idp"]["ok"])
|
|
self.assertIn("unreachable", r.json()["idp"]["error"])
|
|
|
|
def test_delete_removes_the_account(self):
|
|
idp.sync(DEPS, self.dom)
|
|
pid = DEPS.users.get(self.dom["id"])["idpId"]
|
|
self.owner().delete(f"/api/users/{self.dom['id']}", headers=OWNER_H)
|
|
self.assertNotIn(pid, self.fake.users)
|
|
|
|
def test_sync_all_and_the_list_meta(self):
|
|
DEPS.users.create("claire@example.com", "Claire")
|
|
r = self.owner().post("/api/users/idp-sync", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(sorted(r.json()["results"]), sorted(u["id"] for u in DEPS.users.all()))
|
|
meta = self.owner().get("/api/users", headers=OWNER_H).json()["idp"]
|
|
self.assertEqual(meta["apps"], [{"group": "jellyfin", "label": "Jellyfin",
|
|
"url": "https://netflix.example.test"}])
|
|
self.assertTrue(meta["enabled"] and meta["login"])
|
|
|
|
def test_invite_link_is_a_provider_login_code(self):
|
|
sent = []
|
|
orig_enabled, orig_sso = mailer.enabled, mailer.sso_mail
|
|
mailer.enabled = lambda: True
|
|
mailer.sso_mail = lambda to, name, url, **kw: sent.append((to, url, kw))
|
|
self.addCleanup(setattr, mailer, "enabled", orig_enabled)
|
|
self.addCleanup(setattr, mailer, "sso_mail", orig_sso)
|
|
DEPS.users.update(self.dom["id"], {"apps": {"jellyfin": True}})
|
|
r = self.owner().post(f"/api/users/{self.dom['id']}/login-link", headers=OWNER_H,
|
|
json={"send": True, "mail": "sso"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
url = r.json()["url"]
|
|
self.assertTrue(url.startswith(
|
|
"https://claude.example.test/api/auth/oidc/start?lc=LC"), url)
|
|
self.assertEqual(sent[0][0], "dom@example.com")
|
|
self.assertEqual([a["label"] for a in sent[0][2]["apps"]], ["Jellyfin"])
|
|
|
|
def test_store_cleans_apps(self):
|
|
u = DEPS.users.update(self.dom["id"], {"apps": {"jellyfin": 1, "Bad Name": True, 3: 1}})
|
|
self.assertEqual(u["apps"], {"jellyfin": True})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|