From b824115e9b774727e1702cb5e78e3809c58f7b5a Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:25:57 +0100 Subject: [PATCH] Let one API key carry every area the holder may still grant. A key belongs to one application and can include global exercises, several clubs, and the holder's own exercises. Lost roles stop that area from being delivered, and the key stays copyable. Co-authored-by: Cursor --- backend/distribution_contract.py | 1 + backend/distribution_service.py | 169 +++++++++++++++--- .../101_distribution_key_grants.sql | 7 + backend/routers/distribution.py | 14 +- backend/tests/test_distribution_contract.py | 1 + backend/version.py | 13 +- frontend/src/pages/AdminDistributionPage.jsx | 166 ++++++++--------- 7 files changed, 260 insertions(+), 111 deletions(-) create mode 100644 backend/migrations/101_distribution_key_grants.sql diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py index 7f6cbb9..b472f99 100644 --- a/backend/distribution_contract.py +++ b/backend/distribution_contract.py @@ -291,6 +291,7 @@ CONTEXT_VISIBILITIES = { "platform": ("official", "private"), "club": ("club", "private"), "personal": ("private",), + "user": ("official", "club", "private"), } diff --git a/backend/distribution_service.py b/backend/distribution_service.py index 3d719e2..b948ed0 100644 --- a/backend/distribution_service.py +++ b/backend/distribution_service.py @@ -868,6 +868,7 @@ def resolve_bearer(cur, token: str) -> dict: cur.execute( """ SELECT k.secret_hash, k.expires_at, k.revoked_at, k.objects, k.visibilities, + k.context_kind, k.context_profile_id, k.context_club_id, k.club_ids, b.id AS binding_id, b.status AS binding_status, b.recipient_id, r.status AS recipient_status FROM distribution_keys k @@ -900,6 +901,10 @@ def resolve_bearer(cur, token: str) -> dict: "hits": allowed, "objects": list(row.get("objects") or ["exercise"]), "visibilities": list(row.get("visibilities") or ["official", "club", "private"]), + "context_kind": row.get("context_kind"), + "context_profile_id": row.get("context_profile_id"), + "context_club_id": row.get("context_club_id"), + "club_ids": [int(item) for item in (row.get("club_ids") or [])], } @@ -960,7 +965,58 @@ def assert_visibility_scope(visibilities, visibility: Optional[str]) -> None: raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."}) -def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict: +def grant_allows(cur, binding: dict, exercise: dict) -> bool: + """Auslieferung folgt den Schlüsselrechten und den Rollen, die der Inhaber jetzt noch hat.""" + vis = (exercise.get("visibility") or "private").strip().lower() + visibilities = list(binding.get("visibilities") or ["official", "club", "private"]) + if vis not in visibilities: + return False + kind = binding.get("context_kind") + owner = binding.get("context_profile_id") + if kind != "user" or not owner: + legacy_club = binding.get("context_club_id") + if vis == "club" and legacy_club is not None and int(legacy_club) != int(exercise.get("club_id") or 0): + return False + return True + cur.execute("SELECT role FROM profiles WHERE id = %s", (int(owner),)) + role = ((_one(cur) or {}).get("role") or "") + if vis == "official": + return is_superadmin(role) + if vis == "private": + created = exercise.get("created_by") + return created is not None and int(created) == int(owner) + if vis == "club": + club_id = exercise.get("club_id") + clubs = {int(item) for item in (binding.get("club_ids") or [])} + if binding.get("context_club_id") is not None: + clubs.add(int(binding["context_club_id"])) + if club_id is None or int(club_id) not in clubs: + return False + if not has_club_role(cur, int(owner), int(club_id), "club_admin"): + return False + return _api_enabled(cur, int(club_id)) + return False + + +def assert_current_grant(cur, binding: Optional[dict], source_id: str) -> None: + if not binding or binding.get("context_kind") != "user": + assert_visibility_scope( + None if not binding else binding.get("visibilities"), + _source_visibility(cur, source_id), + ) + return + cur.execute( + "SELECT visibility, club_id, created_by FROM exercises WHERE public_id = %s", + (str(source_id),), + ) + exercise = _one(cur) + if exercise is None: + return + if not grant_allows(cur, binding, exercise): + raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."}) + + +def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int, binding: Optional[dict] = None) -> dict: cur.execute( """ SELECT seq, body FROM distribution_events @@ -983,6 +1039,8 @@ def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict: body = json.loads(body) events.append(order_event(body)) last_seq = int(item["seq"]) + if binding and binding.get("context_kind") == "user": + events = _events_still_granted(cur, binding, events) from distribution_contract import cursor_secret, encode_cursor return { @@ -992,7 +1050,29 @@ def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict: } -def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) -> dict: +def _events_still_granted(cur, binding: dict, events: list[dict]) -> list[dict]: + ids = [str(event.get("release_id")) for event in events if event.get("release_id")] + if not ids: + return events + placeholders = ", ".join(["%s"] * len(ids)) + cur.execute( + f""" + SELECT dr.release_id, e.visibility, e.club_id, e.created_by + FROM distribution_releases dr + LEFT JOIN exercises e ON e.public_id = dr.source_id + WHERE dr.release_id IN ({placeholders}) + """, + tuple(ids), + ) + allowed = set() + for row in _rows(cur): + item = r2d(row) + if item.get("visibility") is None or grant_allows(cur, binding, item): + allowed.add(str(item["release_id"])) + return [event for event in events if str(event.get("release_id")) in allowed] + + +def load_availability(cur, recipient_id: str, source_id: str, visibilities=None, binding: Optional[dict] = None) -> dict: import json import uuid @@ -1015,7 +1095,10 @@ def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) status_code=404, detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."}, ) - cur.execute("SELECT status, visibility FROM exercises WHERE public_id = %s", (str(source_id),)) + cur.execute( + "SELECT status, visibility, club_id, created_by FROM exercises WHERE public_id = %s", + (str(source_id),), + ) source = _one(cur) releases = [] for row in rows: @@ -1057,8 +1140,12 @@ def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) [item["package"] for item in releases], ) visibility = (source.get("visibility") if source else None) - in_scope = visibility is None or key_covers( - ["exercise"], visibilities, resource="exercise", visibility=(visibility or "private").strip().lower() + in_scope = visibility is None or ( + grant_allows(cur, binding, source) + if binding and binding.get("context_kind") == "user" + else key_covers( + ["exercise"], visibilities, resource="exercise", visibility=(visibility or "private").strip().lower() + ) ) return { "source_id": str(source_id), @@ -1069,7 +1156,7 @@ def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) } -def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None) -> bytes: +def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None, binding: Optional[dict] = None) -> bytes: cur.execute( """ SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text @@ -1080,14 +1167,14 @@ def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None) -> row = _one(cur) if not row or str(row["recipient_id"]) != str(recipient_id): raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."}) - assert_visibility_scope(visibilities, _source_visibility(cur, str(row["source_id"]))) + assert_current_grant(cur, binding, str(row["source_id"])) enforce_expiry(cur, row) if row.get("fetch_blocked"): raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Paket zurückgezogen."}) return row["manifest_text"].encode("utf-8") -def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilities=None) -> tuple[Path, str]: +def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilities=None, binding: Optional[dict] = None) -> tuple[Path, str]: cur.execute( """ SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, r.source_id, @@ -1101,7 +1188,7 @@ def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilit row = _one(cur) if not row or str(row["recipient_id"]) != str(recipient_id): raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Medium nicht gefunden."}) - assert_visibility_scope(visibilities, _source_visibility(cur, str(row["source_id"]))) + assert_current_grant(cur, binding, str(row["source_id"])) enforce_expiry(cur, row) if row.get("fetch_blocked"): raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."}) @@ -1188,6 +1275,8 @@ def _ensure_relationship(cur, publisher_id: str, recipient_id: str) -> None: def _key_visible(item: dict, profile_id: int, role: str, admin_ids: set[int]) -> bool: kind = item.get("context_kind") + if kind == "user": + return int(item.get("context_profile_id") or 0) == int(profile_id) if kind == "platform": return is_superadmin(role) if kind == "personal": @@ -1237,7 +1326,8 @@ def access_home(cur, profile_id: int, role: str) -> dict: cur.execute( """ SELECT k.id, k.label, k.key_prefix, k.objects, k.visibilities, k.context_kind, - k.context_club_id, k.context_profile_id, k.created_at, c.name AS club_name + k.context_club_id, k.context_profile_id, k.created_at, k.token_value, k.club_ids, + c.name AS club_name FROM distribution_keys k LEFT JOIN clubs c ON c.id = k.context_club_id WHERE k.revoked_at IS NULL @@ -1259,7 +1349,9 @@ def access_home(cur, profile_id: int, role: str) -> dict: "visibilities": list(item.get("visibilities") or []), "context_kind": item.get("context_kind"), "club_id": item.get("context_club_id"), + "club_ids": [int(value) for value in (item.get("club_ids") or [])], "club_name": item.get("club_name"), + "token": item.get("token_value") or "", "created_at": format_utc(created) if created and not isinstance(created, str) else created, } ) @@ -1288,19 +1380,35 @@ def create_named_key( club_id: Optional[int], profile_id: int, role: str, + club_ids: Optional[list[int]] = None, ) -> dict: denial = scope_denial(context_kind, objects, visibilities) if denial: raise HTTPException(status_code=400, detail=denial) owner_profile = None stored_club = None - if context_kind == "platform": + stored_clubs: list[int] = [] + if context_kind == "user": + owner_profile = int(profile_id) + if "official" in visibilities and not is_superadmin(role): + raise HTTPException(status_code=403, detail="Globale Übungen darf nur ein Superadmin auf einen Schlüssel legen.") + if "club" in visibilities: + stored_clubs = sorted({int(item) for item in (club_ids or [])}) + if not stored_clubs: + raise HTTPException(status_code=400, detail="Wähle mindestens einen Verein.") + for chosen in stored_clubs: + if not has_club_role(cur, profile_id, chosen, "club_admin"): + raise HTTPException(status_code=403, detail="Du bist nicht Vereinsadmin dieses Vereins.") + if not _api_enabled(cur, chosen): + raise HTTPException(status_code=403, detail="Die API-Schnittstelle ist für diesen Verein nicht freigegeben.") + elif context_kind == "platform": if not is_superadmin(role): raise HTTPException(status_code=403, detail="Plattform-Schlüssel legt ein Superadmin an.") elif context_kind == "club": if club_id is None: raise HTTPException(status_code=400, detail="Verein fehlt.") stored_club = int(club_id) + stored_clubs = [stored_club] if not has_club_role(cur, profile_id, stored_club, "club_admin"): raise HTTPException(status_code=403, detail="Nur ein Vereinsadmin legt Schlüssel für den Verein an.") if not _api_enabled(cur, stored_club): @@ -1320,12 +1428,13 @@ def create_named_key( binding_id = str(_one(cur)["id"]) if "official" in visibilities: _ensure_relationship(cur, _ensure_publisher(cur, "platform", None, "Plattform"), recipient_id) - if "club" in visibilities and stored_club is not None: - cur.execute("SELECT name FROM clubs WHERE id = %s", (stored_club,)) - club = _one(cur) or {} - _ensure_relationship( - cur, _ensure_publisher(cur, "club", stored_club, club.get("name") or "Verein"), recipient_id - ) + if "club" in visibilities: + for chosen in stored_clubs: + cur.execute("SELECT name FROM clubs WHERE id = %s", (chosen,)) + club = _one(cur) or {} + _ensure_relationship( + cur, _ensure_publisher(cur, "club", chosen, club.get("name") or "Verein"), recipient_id + ) if "private" in visibilities: _ensure_relationship(cur, _ensure_publisher(cur, "own", None, "Eigener Bestand"), recipient_id) @@ -1337,8 +1446,8 @@ def create_named_key( """ INSERT INTO distribution_keys ( id, binding_id, key_prefix, secret_hash, label, objects, visibilities, - context_kind, context_club_id, context_profile_id - ) VALUES (%s, %s, %s, %s, %s, %s::text[], %s::text[], %s, %s, %s) + context_kind, context_club_id, context_profile_id, token_value, club_ids + ) VALUES (%s, %s, %s, %s, %s, %s::text[], %s::text[], %s, %s, %s, %s, %s::int[]) """, ( new_id(), @@ -1351,6 +1460,8 @@ def create_named_key( context_kind, stored_club, owner_profile, + token, + _pg_text_array([str(item) for item in stored_clubs]) if stored_clubs else "{}", ), ) return {"token": token, "prefix": prefix, "label": label} @@ -1374,10 +1485,28 @@ def revoke_named_key(cur, key_id: str, profile_id: int, role: str) -> dict: return {"ok": True} +def _granted_club_ids(item: dict) -> set[int]: + clubs = {int(value) for value in (item.get("club_ids") or [])} + if item.get("context_club_id") is not None: + clubs.add(int(item["context_club_id"])) + return clubs + + def _key_matches_exercise(item: dict, exercise: dict, profile_id: int, role: str, admin_ids: set[int], member_ids: set[int]) -> bool: vis = (exercise.get("visibility") or "private").strip().lower() kind = item.get("context_kind") club_id = item.get("context_club_id") + if kind == "user": + if int(item.get("context_profile_id") or 0) != int(profile_id): + return False + if vis == "official": + return is_superadmin(role) + if vis == "club": + exercise_club = int(exercise.get("club_id") or 0) + return exercise_club in _granted_club_ids(item) and exercise_club in admin_ids + if vis == "private": + return True + return False if vis == "official": return kind == "platform" and is_superadmin(role) if vis == "club": @@ -1411,7 +1540,7 @@ def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) - return [], "Die API-Schnittstelle ist für diesen Verein nicht freigegeben." cur.execute( """ - SELECT k.id, k.label, k.context_kind, k.context_club_id, k.context_profile_id, + SELECT k.id, k.label, k.context_kind, k.context_club_id, k.context_profile_id, k.club_ids, b.recipient_id, c.distribution_api_enabled AS api_enabled FROM distribution_keys k JOIN distribution_bindings b ON b.id = k.binding_id diff --git a/backend/migrations/101_distribution_key_grants.sql b/backend/migrations/101_distribution_key_grants.sql new file mode 100644 index 0000000..2c222f4 --- /dev/null +++ b/backend/migrations/101_distribution_key_grants.sql @@ -0,0 +1,7 @@ +-- Ein Schlüssel kann mehrere Vereine und Sichtbarkeiten tragen. Der Wert bleibt für den Inhaber kopierbar. + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS token_value TEXT; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS club_ids INT[] NOT NULL DEFAULT ARRAY[]::int[]; diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py index 2ab4103..884ae83 100644 --- a/backend/routers/distribution.py +++ b/backend/routers/distribution.py @@ -126,8 +126,9 @@ class AccessKeyBody(BaseModel): name: str = Field(min_length=1, max_length=200) objects: list[str] visibilities: list[str] - context_kind: str + context_kind: str = "user" club_id: Optional[int] = None + club_ids: list[int] = [] class ClubApiBody(BaseModel): @@ -168,7 +169,7 @@ def get_changes( raise exc with get_db() as conn: cur = get_cursor(conn) - payload = list_changes(cur, binding["recipient_id"], seq, limit) + payload = list_changes(cur, binding["recipient_id"], seq, limit, binding) return Response( content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")), media_type="application/json", @@ -185,7 +186,9 @@ def get_availability(source_id: str, authorization: Optional[str] = Header(defau cur = get_cursor(conn) try: assert_exercise_object(binding.get("objects")) - payload = load_availability(cur, binding["recipient_id"], source_id, binding.get("visibilities")) + payload = load_availability( + cur, binding["recipient_id"], source_id, binding.get("visibilities"), binding + ) except HTTPException as exc: held = exc if held is not None: @@ -207,7 +210,7 @@ def get_release(release_id: str, authorization: Optional[str] = Header(default=N cur = get_cursor(conn) try: assert_exercise_object(binding.get("objects")) - body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities")) + body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities"), binding) except HTTPException as exc: held = exc if held is not None: @@ -227,7 +230,7 @@ def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Hea try: assert_exercise_object(binding.get("objects")) path, media_type = load_asset( - cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities") + cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities"), binding ) except HTTPException as exc: held = exc @@ -524,6 +527,7 @@ def post_access_key(body: AccessKeyBody, tenant: TenantContext = Depends(get_ten visibilities=body.visibilities, context_kind=body.context_kind, club_id=body.club_id, + club_ids=body.club_ids, profile_id=tenant.profile_id, role=tenant.global_role or "", ) diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py index 446adce..7262d10 100644 --- a/backend/tests/test_distribution_contract.py +++ b/backend/tests/test_distribution_contract.py @@ -102,6 +102,7 @@ def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> Non def test_key_scope_follows_the_role_context() -> None: + assert scope_denial("user", ["exercise"], ["official", "club", "private"]) is None assert scope_denial("personal", ["exercise"], ["private"]) is None assert scope_denial("personal", ["exercise"], ["official"]) assert scope_denial("club", ["exercise", "framework"], ["club", "private"]) is None diff --git a/backend/version.py b/backend/version.py index 473f306..e85fcef 100644 --- a/backend/version.py +++ b/backend/version.py @@ -1,8 +1,8 @@ # Shinkan Jinkendo Version Information -APP_VERSION = "0.8.253" +APP_VERSION = "0.8.254" BUILD_DATE = "2026-11-23" -DB_SCHEMA_VERSION = "20261123100" +DB_SCHEMA_VERSION = "20261123101" MODULE_VERSIONS = { "legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste) @@ -39,7 +39,7 @@ MODULE_VERSIONS = { "skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions "methods": "0.1.0", "exercises": "2.38.0", # Globale Übungen schreibt und gibt nur superadmin frei - "distribution": "1.2.0", # API-Schlüssel je Mandant: Name, Objekte, Sichtbarkeit; Verein schaltet der Superadmin frei + "distribution": "1.3.0", # Ein Schlüssel je Anwendung, Rechte folgen der aktuellen Rolle, Schlüssel bleibt kopierbar "planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil "training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint "training_programs": "0.1.0", @@ -55,6 +55,13 @@ MODULE_VERSIONS = { } CHANGELOG = [ + { + "version": "0.8.254", + "date": "2026-11-23", + "changes": [ + "Ein API-Schlüssel gehört zu einer Anwendung und kann globale Übungen, mehrere Vereine und eigene Übungen zugleich erlauben. Fällt die Rolle weg, wird dieser Bereich nicht mehr ausgeliefert. Der Schlüssel bleibt kopierbar.", + ], + }, { "version": "0.8.253", "date": "2026-11-23", diff --git a/frontend/src/pages/AdminDistributionPage.jsx b/frontend/src/pages/AdminDistributionPage.jsx index db5b31e..3645207 100644 --- a/frontend/src/pages/AdminDistributionPage.jsx +++ b/frontend/src/pages/AdminDistributionPage.jsx @@ -16,27 +16,27 @@ const OBJECTS = [ ['training_module', 'Trainingsmodul'], ] -const VISIBILITY = { - official: 'Global', - club: 'Verein', - private: 'Eigene', +function toggleValue(list, value, setter) { + setter(list.includes(value) ? list.filter((item) => item !== value) : [...list, value]) } -function KeyForm({ contextKind, clubId, allowedVisibilities, onCreated }) { +function KeyForm({ superadmin, clubs, onCreated }) { const [name, setName] = useState('') const [objects, setObjects] = useState(['exercise']) - const [visibilities, setVisibilities] = useState( - allowedVisibilities.length === 1 ? allowedVisibilities : [allowedVisibilities[0]] - ) + const [globalOn, setGlobalOn] = useState(false) + const [privateOn, setPrivateOn] = useState(true) + const [clubIds, setClubIds] = useState([]) const [busy, setBusy] = useState(false) const [error, setError] = useState('') - - function toggle(list, value, setter) { - setter(list.includes(value) ? list.filter((item) => item !== value) : [...list, value]) - } + const adminClubs = clubs.filter((club) => club.is_club_admin) async function submit(event) { event.preventDefault() + const visibilities = [ + ...(globalOn ? ['official'] : []), + ...(clubIds.length ? ['club'] : []), + ...(privateOn ? ['private'] : []), + ] setBusy(true) setError('') try { @@ -44,8 +44,8 @@ function KeyForm({ contextKind, clubId, allowedVisibilities, onCreated }) { name: name.trim(), objects, visibilities, - context_kind: contextKind, - club_id: clubId || null, + context_kind: 'user', + club_ids: clubIds, }) setName('') onCreated(result) @@ -56,59 +56,96 @@ function KeyForm({ contextKind, clubId, allowedVisibilities, onCreated }) { } } + const visibilitiesChosen = globalOn || privateOn || clubIds.length > 0 + return (
Inhalte {OBJECTS.map(([value, label]) => ( ))}
- Sichtbarkeit - {allowedVisibilities.map((value) => ( -
{error ?

{error}

: null} -
) } -function KeyList({ keys, onRevoke }) { +function KeyList({ keys, clubs, onRevoke }) { + const [copied, setCopied] = useState('') if (!keys.length) return

Noch kein Schlüssel.

+ + function rights(item) { + const names = [] + if (item.visibilities.includes('official')) names.push('Global') + for (const clubId of item.club_ids || []) { + names.push(clubs.find((club) => club.id === clubId)?.name || `Verein ${clubId}`) + } + if (!item.club_ids?.length && item.club_name && item.visibilities.includes('club')) names.push(item.club_name) + if (item.visibilities.includes('private')) names.push('Eigene') + return names.join(', ') + } + + async function copy(token, id) { + await navigator.clipboard.writeText(token) + setCopied(id) + } + return ( -