From fe3633ba8bbd780f52c2208ce9441aa593f2d810 Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 13:07:47 +0100 Subject: [PATCH 1/8] Publish frozen exercise releases and report whether they stay offerable. Recipients can ask whether a released exercise is still offerable. Archiving or removing the source stops new offers; the frozen copy stays fetchable until withdrawal. Co-authored-by: Cursor --- .../working/ACCESS_LAYER_ENDPOINT_AUDIT.md | 2 + backend/distribution_contract.py | 627 ++++++++++ backend/distribution_service.py | 1093 +++++++++++++++++ backend/main.py | 4 +- backend/media_legal_hold.py | 4 + backend/migrations/099_distribution.sql | 191 +++ backend/routers/distribution.py | 460 +++++++ backend/routers/exercises.py | 36 +- backend/tests/test_distribution_contract.py | 259 ++++ backend/version.py | 22 +- docker-compose.dev-env.yml | 1 + .../Shinkan_Lara_Felix_Referenzfall_v1.json | 493 ++++++++ .../Shinkan_Lara_Felix_Uebergabevertrag_v1.md | 70 ++ .../Shinkan_Uebungsfreigabe_Fachkonzept_v1.md | 58 + frontend/src/App.jsx | 9 + frontend/src/api/distribution.js | 78 ++ frontend/src/components/AdminPageNav.jsx | 3 +- .../exercises/ExerciseDistributionPanel.jsx | 262 ++++ .../exercises/ExerciseFormPageRoot.jsx | 3 + frontend/src/pages/AdminDistributionPage.jsx | 195 +++ frontend/src/utils/api.js | 4 + 21 files changed, 3862 insertions(+), 12 deletions(-) create mode 100644 backend/distribution_contract.py create mode 100644 backend/distribution_service.py create mode 100644 backend/migrations/099_distribution.sql create mode 100644 backend/routers/distribution.py create mode 100644 backend/tests/test_distribution_contract.py create mode 100644 docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json create mode 100644 docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md create mode 100644 docs/architecture/distribution/Shinkan_Uebungsfreigabe_Fachkonzept_v1.md create mode 100644 frontend/src/api/distribution.js create mode 100644 frontend/src/components/exercises/ExerciseDistributionPanel.jsx create mode 100644 frontend/src/pages/AdminDistributionPage.jsx diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md index d13886e..a58435b 100644 --- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md +++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md @@ -29,6 +29,8 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C. | media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe | | media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung | | exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv | +| distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals | +| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/admin/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` dieses Vereins; global: nur `superadmin`; Verwaltung nur `superadmin` | | auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT | | catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen | | skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT | diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py new file mode 100644 index 0000000..cce746f --- /dev/null +++ b/backend/distribution_contract.py @@ -0,0 +1,627 @@ +"""Vertrag v1: kanonisches Manifest, Ereignisse, Freigaberegeln, Cursor. + +Reine Funktionen. Die Datenbankschicht ruft sie auf, die Tests prüfen sie ohne Postgres. +""" +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import os +import re +import uuid +from datetime import datetime, timezone +from html import unescape +from typing import Any, Iterable, Optional + +PART_ROLES = ( + "goal", + "prerequisites", + "preparation", + "instructions", + "trainer_notes", + "equipment", + "duration_note", +) +ASSET_ROLES = ("demonstration", "worksheet", "illustration") +ACTIONS = ( + "store", + "render", + "stream", + "download", + "print", + "course_display", + "commercial_course_use", + "adapt", + "public_preview", + "grant_customer_use", +) +REASON_CODES = ("rights", "safety", "privacy", "expired", "editorial_error") +WITHDRAW_TYPES = ("release.withdrawn", "variant.withdrawn", "asset.withdrawn") +EVENT_TYPES = ("release.published", "release.retired", *WITHDRAW_TYPES) + +_TAG = re.compile(r"<[^>]+>") +_MEDIA_TOKEN = re.compile(r"\{\{exerciseMedia:(\d+)\}\}") +_DATA_MEDIA = re.compile(r'data-exercise-media-id=["\'](\d+)["\']', re.I) + +LEGAL_HOLD_REASON = { + "rights_dispute": "rights", + "copyright_complaint": "rights", + "consent_withdrawn": "privacy", + "privacy_complaint": "privacy", + "youth_protection": "safety", + "illegal_content": "safety", + "other": "safety", +} + +OFFICIAL_WRITE_DENIED = "Globale Übungen dürfen nur von Superadmins bearbeitet werden." +RATE_LIMIT_PER_MINUTE = 60 + + +def distribution_enabled() -> bool: + return os.getenv("DISTRIBUTION_ENABLED", "").strip().lower() in ("1", "true", "yes") + + +def cursor_secret() -> str: + secret = os.getenv("DISTRIBUTION_CURSOR_SECRET", "").strip() + if secret: + return secret + if os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod"): + raise RuntimeError("DISTRIBUTION_CURSOR_SECRET fehlt") + return "shinkan-distribution-dev-cursor" + + +def format_utc(dt: datetime) -> str: + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def parse_utc(value: str) -> datetime: + raw = value.strip() + if raw.endswith("Z"): + raw = raw[:-1] + "+00:00" + parsed = datetime.fromisoformat(raw) + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed.astimezone(timezone.utc) + + +def canonical_json(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _copy_if(source: dict, key: str, required: bool = False, keep_null: bool = False) -> Any: + if key not in source: + if required: + raise ValueError(f"Feld fehlt: {key}") + return None + value = source[key] + if value is None and not keep_null: + return None + return value + + +def order_manifest(source: dict) -> dict: + """Feldreihenfolge des Übergabevertrags. Optionale leere Felder entfallen, null bleibt bei Fristen.""" + exercise = source["exercise"] + ordered_exercise: dict[str, Any] = {"title": exercise["title"]} + if exercise.get("summary") is not None: + ordered_exercise["summary"] = exercise["summary"] + if exercise.get("audience") is not None: + ordered_exercise["audience"] = exercise["audience"] + ordered_exercise["rights_id"] = exercise["rights_id"] + ordered_exercise["parts"] = [ + { + "id": part["id"], + "role": part["role"], + "text": part["text"], + "rights_id": part["rights_id"], + } + for part in exercise["parts"] + ] + assets = [] + for asset in exercise["assets"]: + item = { + "id": asset["id"], + "role": asset["role"], + "media_type": asset["media_type"], + "size_bytes": asset["size_bytes"], + "sha256": asset["sha256"], + "rights_id": asset["rights_id"], + } + if asset.get("label") is not None: + item["label"] = asset["label"] + assets.append(item) + ordered_exercise["assets"] = assets + ordered_exercise["common_part_ids"] = list(exercise["common_part_ids"]) + ordered_exercise["common_asset_ids"] = list(exercise["common_asset_ids"]) + ordered_exercise["variants"] = [ + { + "id": variant["id"], + "label": variant["label"], + "part_ids": list(variant["part_ids"]), + "asset_ids": list(variant["asset_ids"]), + } + for variant in exercise["variants"] + ] + rights = [] + for right in source["rights"]: + item = { + "id": right["id"], + "evidence_ref": right["evidence_ref"], + "actions": list(right["actions"]), + "territories": right["territories"], + "valid_from": right["valid_from"], + "valid_until": right["valid_until"], + } + if right.get("attribution") is not None: + item["attribution"] = right["attribution"] + rights.append(item) + return { + "schema_version": source["schema_version"], + "resource_type": source["resource_type"], + "release_id": source["release_id"], + "source_id": source["source_id"], + "revision": source["revision"], + "publisher_id": source["publisher_id"], + "published_at": source["published_at"], + "exercise": ordered_exercise, + "rights": rights, + } + + +def manifest_bytes(source: dict) -> bytes: + return canonical_json(order_manifest(source)) + + +def order_event(event: dict) -> dict: + ordered = { + "event_id": event["event_id"], + "type": event["type"], + "release_id": event["release_id"], + "occurred_at": event["occurred_at"], + } + if event["type"] == "release.published": + ordered["source_id"] = event["source_id"] + ordered["revision"] = event["revision"] + ordered["manifest_sha256"] = event["manifest_sha256"] + elif event["type"] in WITHDRAW_TYPES: + if event["type"] != "release.withdrawn": + ordered["target_id"] = event["target_id"] + ordered["reason_code"] = event["reason_code"] + return ordered + + +def encode_cursor(secret: str, recipient_id: str, seq: int) -> str: + payload = f"{recipient_id}:{int(seq)}".encode("utf-8") + sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest() + raw = payload + b"." + sig.encode("ascii") + return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") + + +def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int: + if token is None or token == "": + return 0 + pad = "=" * (-len(token) % 4) + try: + raw = base64.urlsafe_b64decode(token + pad) + payload, sig = raw.rsplit(b".", 1) + expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii") + if not hmac.compare_digest(sig, expected): + raise ValueError("sig") + rec, seq_raw = payload.decode("utf-8").split(":", 1) + if rec != recipient_id: + raise ValueError("channel") + seq = int(seq_raw) + if seq < 0: + raise ValueError("seq") + return seq + except Exception as exc: + raise InvalidCursor() from exc + + +class InvalidCursor(Exception): + pass + + +def official_write_allowed(visibility: Optional[str], role: Optional[str]) -> bool: + if (visibility or "").strip().lower() != "official": + return True + return (role or "").strip().lower() == "superadmin" + + +def _same_club(left: Any, right: Any) -> bool: + try: + return left is not None and right is not None and int(left) == int(right) + except (TypeError, ValueError): + return False + + +def release_denial( + *, + visibility: Optional[str], + role: Optional[str], + publisher_kind: str, + is_owner: bool, + is_club_admin: bool, + publisher_club_id: Any = None, + exercise_club_id: Any = None, +) -> Optional[str]: + """Freigabe folgt der Zugehörigkeit der Übung, nicht einer gesonderten Zuordnungsliste.""" + vis = (visibility or "").strip().lower() + role_l = (role or "").strip().lower() + kind = (publisher_kind or "").strip().lower() + if vis == "official": + if role_l != "superadmin": + return "Globale Übungen dürfen nur von Superadmins freigegeben werden." + if kind != "platform": + return "Globale Übungen werden nur über den Plattformbestand freigegeben." + return None + if kind == "platform": + return "Der Plattformbestand gibt nur globale Übungen frei." + if vis == "private": + if not is_owner: + return "Private Übungen gibt nur die Person frei, der sie gehören." + if kind != "own": + return "Private Übungen werden über den eigenen Bestand freigegeben." + return None + if vis == "club": + if not is_club_admin: + return "Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei." + if kind != "club" or not _same_club(publisher_club_id, exercise_club_id): + return "Vereinsübungen werden über den Bestand dieses Vereins freigegeben." + return None + return "Diese Übung kann so nicht freigegeben werden." + + +def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool: + if (role or "").strip().lower() == "superadmin": + return True + return denial is None + + +def package_state(*, fetch_blocked: bool, retired: bool) -> str: + if fetch_blocked: + return "withdrawn" + if retired: + return "retired" + return "available" + + +def exercise_offerable(source_status: Optional[str], package_states: Iterable[str]) -> tuple[str, bool]: + """Die eingefrorene Kopie bleibt abrufbar. Neu anbieten darf der Empfänger sie nur, solange die Quelle approved und ein Paket verfügbar ist.""" + status = "deleted" if not (source_status or "").strip() else str(source_status).strip().lower() + states = list(package_states) + return status, status == "approved" and any(item == "available" for item in states) + + +def decide_confirm(stored_release_id: Optional[str], new_release_id: str) -> tuple[str, bool]: + """Technische Wiederholung liefert die gespeicherte Paket-ID. Eine neue Bestätigung legt ein Paket an.""" + if stored_release_id: + return stored_release_id, False + return new_release_id, True + + +def rate_decision(hits: int, window_age_seconds: float, limit: int = RATE_LIMIT_PER_MINUTE) -> tuple[int, bool]: + if window_age_seconds >= 60: + return 1, False + if hits >= limit: + return hits, True + return hits + 1, False + + +def plaintext(value: Optional[str]) -> str: + text = value or "" + text = _MEDIA_TOKEN.sub("", text) + text = _DATA_MEDIA.sub("", text) + text = _TAG.sub("", text) + return unescape(text).strip() + + +def inline_media_ids(value: Optional[str]) -> set[int]: + if not value: + return set() + ids = {int(item) for item in _MEDIA_TOKEN.findall(value)} + ids.update(int(item) for item in _DATA_MEDIA.findall(value)) + return ids + + +def snapshot_hash(exercise: dict, variants: list[dict], media: list[dict]) -> str: + body = { + "title": exercise.get("title") or "", + "summary": exercise.get("summary") or "", + "goal": exercise.get("goal") or "", + "execution": exercise.get("execution") or "", + "preparation": exercise.get("preparation") or "", + "trainer_notes": exercise.get("trainer_notes") or "", + "equipment": exercise.get("equipment"), + "duration_min": exercise.get("duration_min"), + "duration_max": exercise.get("duration_max"), + "status": exercise.get("status"), + "exercise_kind": exercise.get("exercise_kind") or "simple", + "variants": [ + { + "id": str(item.get("public_id")), + "name": item.get("variant_name") or "", + "description": item.get("description") or "", + "execution_changes": item.get("execution_changes") or "", + "duration_min": item.get("duration_min"), + "duration_max": item.get("duration_max"), + } + for item in variants + ], + "media": [ + { + "id": str(item.get("public_id")), + "sha256": item.get("sha256") or "", + "media_type": item.get("media_type") or "", + } + for item in media + ], + } + return sha256_bytes(canonical_json(body)) + + +def _duration_note(exercise: dict) -> Optional[str]: + low = exercise.get("duration_min") + high = exercise.get("duration_max") + if low and high: + return f"{low}–{high} Minuten" + if low or high: + return f"{low or high} Minuten" + return None + + +def _equipment_text(exercise: dict) -> Optional[str]: + raw = exercise.get("equipment") + if isinstance(raw, str): + try: + raw = json.loads(raw) + except json.JSONDecodeError: + raw = [raw] if raw.strip() else [] + if isinstance(raw, list): + parts = [str(item).strip() for item in raw if str(item).strip()] + return ", ".join(parts) or None + return None + + +def default_cut(exercise: dict, variants: list[dict], media: list[dict]) -> dict: + parts: list[dict] = [] + + def add(key: str, role: str, text: Optional[str]) -> None: + cleaned = plaintext(text) + if cleaned: + parts.append({"key": key, "role": role, "text": cleaned}) + + add("field:goal", "goal", exercise.get("goal")) + add("field:preparation", "preparation", exercise.get("preparation")) + add("field:trainer_notes", "trainer_notes", exercise.get("trainer_notes")) + add("field:equipment", "equipment", _equipment_text(exercise)) + add("field:duration", "duration_note", _duration_note(exercise)) + common_keys = [part["key"] for part in parts] + variant_rows = [] + if variants: + for variant in variants: + key = f"variant:{variant['public_id']}:instructions" + text = plaintext(exercise.get("execution")) + extra = plaintext(variant.get("execution_changes")) + combined = "\n".join(piece for piece in (text, extra) if piece) + if combined: + parts.append({"key": key, "role": "instructions", "text": combined}) + variant_rows.append( + { + "key": str(variant["public_id"]), + "label": variant.get("variant_name") or "Variante", + "part_keys": [key] if combined else [], + "media_ids": [], + } + ) + else: + key = "variant:default:instructions" + text = plaintext(exercise.get("execution")) + if text: + parts.append({"key": key, "role": "instructions", "text": text}) + variant_rows.append( + { + "key": "default", + "label": "Standard", + "part_keys": [key] if text else [], + "media_ids": [], + } + ) + assets = [] + for item in media: + kind = (item.get("media_type") or "").lower() + if kind == "video": + role = "demonstration" + elif kind in ("document", "pdf"): + role = "worksheet" + else: + role = "illustration" + assets.append( + { + "media_id": str(item["public_id"]), + "role": role, + "label": item.get("title") or None, + } + ) + return { + "title": exercise.get("title") or "", + "summary": plaintext(exercise.get("summary")) or None, + "audience": None, + "rights": [], + "parts": parts, + "assets": assets, + "common_part_keys": common_keys, + "common_media_ids": [], + "variants": variant_rows, + } + + +def cut_hash(cut: dict) -> str: + return sha256_bytes(canonical_json(cut)) + + +def collect_blockers(exercise: dict, variants: list[dict], media: list[dict], cut: dict, now: datetime) -> list[str]: + blockers: list[str] = [] + if (exercise.get("exercise_kind") or "simple") != "simple": + blockers.append("Kombinationsübungen können in dieser Fassung nicht herausgegeben werden.") + if (exercise.get("status") or "") != "approved": + blockers.append("Nur Übungen mit Status approved können freigegeben werden.") + texts = " ".join( + str(exercise.get(field) or "") + for field in ("goal", "execution", "preparation", "trainer_notes", "summary") + ) + selected_media = {str(item.get("media_id")) for item in cut.get("assets") or []} + known_media = {str(item.get("public_id")): item for item in media} + referenced = inline_media_ids(texts) + for media_id in referenced: + match = next((item for item in media if int(item.get("id") or 0) == media_id), None) + if match is None or str(match.get("public_id")) not in selected_media: + blockers.append("Ein Medienanker im Text ist nicht als Medium im Paket enthalten.") + break + part_keys = [part.get("key") for part in cut.get("parts") or []] + if len(part_keys) != len(set(part_keys)): + blockers.append("Teilschlüssel sind nicht eindeutig.") + if not any(part.get("role") == "goal" and str(part.get("text") or "").strip() for part in cut.get("parts") or []): + blockers.append("Das Paket braucht ein Lernziel.") + rights = {item.get("id"): item for item in cut.get("rights") or []} + if None in rights or "" in rights: + blockers.append("Jeder Rechtevermerk braucht eine Kennung.") + for right in cut.get("rights") or []: + actions = set(right.get("actions") or []) + unknown = actions - set(ACTIONS) + if unknown: + blockers.append("Unbekannte Nutzungsaktion im Rechtevermerk.") + if "store" not in actions: + blockers.append("Jeder Rechtevermerk muss die Übernahme erlauben.") + if not str(right.get("evidence_ref") or "").strip(): + blockers.append("Jeder Rechtevermerk braucht eine Nachweisreferenz.") + try: + start = parse_utc(right["valid_from"]) + except Exception: + blockers.append("valid_from ist kein UTC-Zeitpunkt.") + continue + until_raw = right.get("valid_until") + until = None + if until_raw is not None: + try: + until = parse_utc(until_raw) + except Exception: + blockers.append("valid_until ist kein UTC-Zeitpunkt.") + continue + if start > now or (until is not None and not (start <= now < until)): + blockers.append("Ein Rechtevermerk ist zum Freigabezeitpunkt nicht wirksam.") + territories = right.get("territories") + if territories is not None: + if not isinstance(territories, list) or any(not re.fullmatch(r"[A-Z]{2}", str(code)) for code in territories): + blockers.append("territories sind ISO-Ländercodes oder null.") + editorial = cut.get("editorial_rights_id") + if editorial not in rights: + blockers.append("Die redaktionellen Angaben brauchen einen Rechtevermerk.") + used_parts: set[str] = set(cut.get("common_part_keys") or []) + used_media: set[str] = set(str(item) for item in (cut.get("common_media_ids") or [])) + variant_keys = [] + for variant in cut.get("variants") or []: + variant_keys.append(variant.get("key")) + used_parts.update(variant.get("part_keys") or []) + used_media.update(str(item) for item in (variant.get("media_ids") or [])) + for key in variant.get("part_keys") or []: + if key not in part_keys: + blockers.append("Eine Variante verweist auf einen unbekannten Teil.") + for media_id in variant.get("media_ids") or []: + if str(media_id) not in selected_media: + blockers.append("Eine Variante verweist auf ein unbekanntes Medium.") + for key in cut.get("common_part_keys") or []: + if key not in part_keys: + blockers.append("Ein gemeinsamer Teil ist unbekannt.") + for media_id in cut.get("common_media_ids") or []: + if str(media_id) not in selected_media: + blockers.append("Ein gemeinsames Medium ist unbekannt.") + if len(variant_keys) != len(set(variant_keys)) or not variant_keys: + blockers.append("Das Paket braucht mindestens eine Variante.") + for part in cut.get("parts") or []: + if part.get("role") not in PART_ROLES: + blockers.append("Unbekannte Textrolle.") + if part.get("key") not in used_parts: + blockers.append("Ein Textteil hängt an keiner Variante.") + if part.get("rights_id") not in rights: + blockers.append("Ein Textteil hat keinen wirksamen Rechtevermerk.") + for asset in cut.get("assets") or []: + media_id = str(asset.get("media_id")) + if media_id not in used_media: + blockers.append("Ein Medium hängt an keiner Variante.") + if asset.get("role") not in ASSET_ROLES: + blockers.append("Unbekannte Medienrolle.") + if asset.get("rights_id") not in rights: + blockers.append("Ein Medium hat keinen wirksamen Rechtevermerk.") + stored = known_media.get(media_id) + if stored is None: + blockers.append("Ein ausgewähltes Medium gehört nicht zu dieser Übung.") + continue + if stored.get("legal_hold_active"): + blockers.append("Ein ausgewähltes Medium ist gesperrt.") + if not stored.get("file_path"): + blockers.append("Ein ausgewähltes Medium hat keine gespeicherten Bytes.") + if (stored.get("rights_status") or "legacy_unreviewed") in ("legacy_unreviewed", "blocked", ""): + blockers.append("Die Upload-Erklärung eines Mediums trägt die Herausgabe nicht.") + if variants: + known_variant_ids = {str(item.get("public_id")) for item in variants} + for variant in cut.get("variants") or []: + if variant.get("key") not in known_variant_ids and variant.get("key") != "default": + blockers.append("Eine Variante gehört nicht zur Übung.") + return list(dict.fromkeys(blockers)) + + +def resolved_asset_ids(manifest: dict, variant_id: str) -> set[str]: + exercise = manifest["exercise"] + variant = next(item for item in exercise["variants"] if item["id"] == variant_id) + return set(exercise["common_asset_ids"]) | set(variant["asset_ids"]) + + +def package_fetch_blocked(events: Iterable[dict], release_id: str) -> bool: + return any( + event.get("type") in WITHDRAW_TYPES and event.get("release_id") == release_id + for event in events + ) + + +def retrievable_release_ids(events: Iterable[dict]) -> set[str]: + published: set[str] = set() + blocked: set[str] = set() + for event in events: + if event.get("type") == "release.published": + published.add(event["release_id"]) + elif event.get("type") in WITHDRAW_TYPES: + blocked.add(event["release_id"]) + return published - blocked + + +def plan_available(plan: dict, manifest: dict, events: Iterable[dict]) -> bool: + release_id = plan["release_id"] + variant_id = plan["variant_id"] + relevant = [event for event in events if event.get("release_id") == release_id] + if any(event.get("type") == "release.withdrawn" for event in relevant): + return False + if any(event.get("type") == "variant.withdrawn" and event.get("target_id") == variant_id for event in relevant): + return False + withdrawn_assets = { + event["target_id"] for event in relevant if event.get("type") == "asset.withdrawn" + } + if withdrawn_assets & resolved_asset_ids(manifest, variant_id): + return False + return True + + +def actions_cover(actions: Iterable[str], required: Iterable[str]) -> bool: + return set(required).issubset(set(actions)) + + +def new_id() -> str: + return str(uuid.uuid4()) diff --git a/backend/distribution_service.py b/backend/distribution_service.py new file mode 100644 index 0000000..6c6b37a --- /dev/null +++ b/backend/distribution_service.py @@ -0,0 +1,1093 @@ +"""Datenbank und Bytekopien der Distributionsfreigabe.""" +from __future__ import annotations + +import os +import shutil +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +from fastapi import HTTPException + +from auth import hash_pin, verify_pin +from club_tenancy import has_club_role +from db import r2d +from distribution_contract import ( + LEGAL_HOLD_REASON, + REASON_CODES, + can_withdraw, + canonical_json, + collect_blockers, + cut_hash, + decide_confirm, + exercise_offerable, + package_state, + default_cut, + distribution_enabled, + format_utc, + manifest_bytes, + new_id, + order_event, + parse_utc, + rate_decision, + release_denial, + sha256_bytes, + snapshot_hash, +) + +_MEDIA_TYPE = { + "video": "video/mp4", + "image": "image/jpeg", + "document": "application/pdf", + "pdf": "application/pdf", + "sketch": "image/png", +} + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _rows(cur) -> list: + rows = cur.fetchall() + if not isinstance(rows, list): + return [] + return rows + + +def _one(cur) -> Optional[dict]: + row = cur.fetchone() + if row is None or not isinstance(row, (dict, tuple)): + try: + mapped = r2d(row) + except Exception: + return None + return mapped + return r2d(row) + + +def distribution_media_root() -> Path: + base = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")) + root = Path(base) / "distribution" + root.mkdir(parents=True, exist_ok=True) + return root + + +def require_enabled() -> None: + if not distribution_enabled(): + raise HTTPException( + status_code=403, + detail={ + "code": "distribution_disabled", + "message": "Die Distribution ist auf dieser Instanz nicht aktiv.", + }, + ) + + +def blocks_exercise_delete(cur, exercise_id: int) -> bool: + cur.execute( + """ + SELECT dr.release_id + FROM distribution_releases dr + JOIN exercises e ON e.public_id = dr.source_id + WHERE e.id = %s + LIMIT 1 + """, + (exercise_id,), + ) + return len(_rows(cur)) > 0 + + +def blocks_media_delete(cur, media_id: int) -> bool: + cur.execute( + """ + SELECT a.asset_id + FROM distribution_release_assets a + JOIN exercise_media em ON em.public_id = a.source_media_public_id + WHERE em.id = %s + LIMIT 1 + """, + (media_id,), + ) + return len(_rows(cur)) > 0 + + +def blocks_variant_delete(cur, variant_id: int) -> bool: + cur.execute( + """ + SELECT dr.release_id + FROM distribution_releases dr + JOIN exercise_variants v ON position(v.public_id::text in dr.manifest_text) > 0 + WHERE v.id = %s + LIMIT 1 + """, + (variant_id,), + ) + return len(_rows(cur)) > 0 + + +def _lock_recipient(cur, recipient_id: str) -> None: + cur.execute( + "SELECT id FROM distribution_recipients WHERE id = %s FOR UPDATE", + (str(recipient_id),), + ) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="Empfänger nicht gefunden") + + +def append_event(cur, recipient_id: str, event: dict) -> int: + _lock_recipient(cur, recipient_id) + cur.execute( + "SELECT COALESCE(MAX(seq), 0) AS seq FROM distribution_events WHERE recipient_id = %s", + (str(recipient_id),), + ) + seq = int((_one(cur) or {"seq": 0})["seq"]) + 1 + ordered = order_event(event) + cur.execute( + """ + INSERT INTO distribution_events (event_id, recipient_id, seq, event_type, release_id, occurred_at, body) + VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb) + """, + ( + ordered["event_id"], + str(recipient_id), + seq, + ordered["type"], + ordered["release_id"], + parse_utc(ordered["occurred_at"]), + canonical_json(ordered).decode("utf-8"), + ), + ) + return seq + + +def _mark_blocked(cur, release_id: str) -> None: + cur.execute( + "UPDATE distribution_releases SET fetch_blocked = true WHERE release_id = %s", + (str(release_id),), + ) + + +def withdraw_assets_for_media_asset(cur, asset_id: int, legal_reason: str) -> None: + reason = LEGAL_HOLD_REASON.get(legal_reason, "safety") + cur.execute( + """ + SELECT a.release_id, a.asset_id, r.recipient_id + FROM distribution_release_assets a + JOIN distribution_releases r ON r.release_id = a.release_id + WHERE a.source_asset_id = %s + """, + (asset_id,), + ) + rows = _rows(cur) + now = format_utc(_now()) + for row in rows: + item = r2d(row) + event = { + "event_id": new_id(), + "type": "asset.withdrawn", + "release_id": str(item["release_id"]), + "occurred_at": now, + "target_id": str(item["asset_id"]), + "reason_code": reason, + } + append_event(cur, str(item["recipient_id"]), event) + _mark_blocked(cur, str(item["release_id"])) + + +def _load_exercise(cur, exercise_id: int) -> dict: + cur.execute( + """ + SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes, + equipment, duration_min, duration_max, status, visibility, club_id, + exercise_kind, created_by + FROM exercises WHERE id = %s + """, + (exercise_id,), + ) + row = _one(cur) + if not row: + raise HTTPException(status_code=404, detail="Übung nicht gefunden") + return row + + +def _load_variants(cur, exercise_id: int) -> list[dict]: + cur.execute( + """ + SELECT id, public_id, variant_name, description, execution_changes, duration_min, duration_max + FROM exercise_variants + WHERE exercise_id = %s + ORDER BY id + """, + (exercise_id,), + ) + return [r2d(row) for row in _rows(cur)] + + +def _load_media(cur, exercise_id: int) -> list[dict]: + cur.execute( + """ + SELECT em.id, em.public_id, em.media_type, em.file_path, em.title, em.media_asset_id, + COALESCE(ma.legal_hold_active, false) AS legal_hold_active, + COALESCE(ma.rights_status, 'declared') AS rights_status, + ma.sha256 AS sha256 + FROM exercise_media em + LEFT JOIN media_assets ma ON ma.id = em.media_asset_id + WHERE em.exercise_id = %s + ORDER BY em.sort_order NULLS LAST, em.id + """, + (exercise_id,), + ) + return [r2d(row) for row in _rows(cur)] + + +def _publisher(cur, publisher_id: str) -> dict: + cur.execute( + "SELECT id, name, kind, club_id, status FROM distribution_publishers WHERE id = %s", + (str(publisher_id),), + ) + row = _one(cur) + if not row or row.get("status") != "active": + raise HTTPException(status_code=403, detail="Herausgeber ist nicht freigeschaltet.") + return row + + +def _is_owner(exercise: dict, profile_id: int) -> bool: + created = exercise.get("created_by") + try: + return created is not None and int(created) == int(profile_id) + except (TypeError, ValueError): + return False + + +def _is_club_admin(cur, exercise: dict, profile_id: int) -> bool: + if (exercise.get("visibility") or "").strip().lower() != "club": + return False + club_id = exercise.get("club_id") + if club_id is None: + return False + try: + return has_club_role(cur, int(profile_id), int(club_id), "club_admin") + except (TypeError, ValueError): + return False + + +def _denial_for(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> Optional[str]: + return release_denial( + visibility=exercise.get("visibility"), + role=role, + publisher_kind=publisher["kind"], + is_owner=_is_owner(exercise, profile_id), + is_club_admin=_is_club_admin(cur, exercise, profile_id), + publisher_club_id=publisher.get("club_id"), + exercise_club_id=exercise.get("club_id"), + ) + + +def _assert_may_release(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> None: + denial = _denial_for(cur, exercise, publisher, profile_id, role) + if denial: + raise HTTPException(status_code=403, detail=denial) + + +def _relationship_ok(cur, publisher_id: str, recipient_id: str) -> bool: + cur.execute( + """ + SELECT 1 AS ok + FROM distribution_relationships rel + JOIN distribution_recipients rec ON rec.id = rel.recipient_id + WHERE rel.publisher_id = %s AND rel.recipient_id = %s + AND rel.status = 'active' AND rec.status = 'active' + """, + (str(publisher_id), str(recipient_id)), + ) + return _one(cur) is not None + + +def _part_id(cur, source_id: str, part_key: str) -> str: + cur.execute( + """ + SELECT part_id FROM distribution_part_identities + WHERE source_id = %s AND part_key = %s + """, + (str(source_id), part_key), + ) + row = _one(cur) + if row: + return str(row["part_id"]) + part_id = new_id() + cur.execute( + """ + INSERT INTO distribution_part_identities (source_id, part_key, part_id) + VALUES (%s, %s, %s) + """, + (str(source_id), part_key, part_id), + ) + return part_id + + +def _variant_id(cur, source_id: str, variant_key: str, public_id: Optional[str]) -> str: + if public_id: + return str(public_id) + return _part_id(cur, source_id, f"variant-id:{variant_key}") + + +def _revision_for(cur, source_id: str, snap: str) -> int: + cur.execute( + """ + SELECT revision FROM distribution_source_revisions + WHERE source_id = %s AND snapshot_hash = %s + """, + (str(source_id), snap), + ) + row = _one(cur) + if row: + return int(row["revision"]) + cur.execute( + "SELECT COALESCE(MAX(revision), 0) AS revision FROM distribution_source_revisions WHERE source_id = %s", + (str(source_id),), + ) + revision = int((_one(cur) or {"revision": 0})["revision"]) + 1 + cur.execute( + """ + INSERT INTO distribution_source_revisions (source_id, revision, snapshot_hash) + VALUES (%s, %s, %s) + """, + (str(source_id), revision, snap), + ) + return revision + + +def hashlib_file(path: Path) -> tuple[str, int]: + import hashlib + + hasher = hashlib.sha256() + size = 0 + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + hasher.update(chunk) + size += len(chunk) + return hasher.hexdigest(), size + + +def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict: + exercise = _load_exercise(cur, exercise_id) + cur.execute( + """ + SELECT dr.release_id, dr.revision, dr.published_at, dr.fetch_blocked, dr.recipient_id, + rec.name AS recipient_name + FROM distribution_releases dr + JOIN distribution_recipients rec ON rec.id = dr.recipient_id + JOIN exercises e ON e.public_id = dr.source_id + WHERE e.id = %s + ORDER BY dr.published_at + """, + (exercise_id,), + ) + releases = [] + for row in _rows(cur): + item = r2d(row) + releases.append( + { + "release_id": str(item["release_id"]), + "revision": item["revision"], + "published_at": format_utc(item["published_at"]) if not isinstance(item["published_at"], str) else item["published_at"], + "fetch_blocked": bool(item["fetch_blocked"]), + "recipient_id": str(item["recipient_id"]), + "recipient_name": item["recipient_name"], + } + ) + cur.execute( + """ + SELECT p.id, p.name, p.kind, p.club_id + FROM distribution_publishers p + WHERE p.status = 'active' + ORDER BY p.name + """ + ) + publishers = [] + for row in _rows(cur): + item = r2d(row) + if _denial_for(cur, exercise, item, profile_id, role): + continue + publishers.append( + {"id": str(item["id"]), "name": item["name"], "kind": item["kind"], "club_id": item["club_id"]} + ) + release_block = None + if not publishers: + release_block = _denial_for( + cur, + exercise, + { + "kind": {"official": "platform", "club": "club"}.get( + (exercise.get("visibility") or "").strip().lower(), "own" + ), + "club_id": exercise.get("club_id"), + }, + profile_id, + role, + ) or "Für diesen Bestand ist noch kein Herausgeber eingerichtet." + return { + "enabled": distribution_enabled(), + "visibility": exercise.get("visibility"), + "may_release": release_block is None, + "release_block": release_block, + "releases": releases, + "publishers": publishers, + "profile_id": profile_id, + "role": role, + } + + +def create_draft(cur, exercise_id: int, publisher_id: str, recipient_id: str, profile_id: int, role: str, cut: Optional[dict]) -> dict: + require_enabled() + exercise = _load_exercise(cur, exercise_id) + variants = _load_variants(cur, exercise_id) + media = _load_media(cur, exercise_id) + publisher = _publisher(cur, publisher_id) + _assert_may_release(cur, exercise, publisher, profile_id, role) + if not _relationship_ok(cur, publisher_id, recipient_id): + raise HTTPException(status_code=403, detail="Für diesen Empfänger besteht keine zugelassene Beziehung.") + payload = cut if cut is not None else default_cut(exercise, variants, media) + blockers = collect_blockers(exercise, variants, media, payload, _now()) + draft_id = new_id() + snap = snapshot_hash(exercise, variants, media) + cur.execute( + """ + INSERT INTO distribution_drafts ( + id, exercise_id, publisher_id, recipient_id, prepared_by, cut, preview_hash + ) VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s) + """, + (draft_id, exercise_id, str(publisher_id), str(recipient_id), profile_id, canonical_json(payload).decode("utf-8"), snap), + ) + return {"draft_id": draft_id, "cut": payload, "blockers": blockers, "preview_hash": snap} + + +def update_draft(cur, exercise_id: int, draft_id: str, cut: dict, profile_id: int, role: str) -> dict: + require_enabled() + exercise = _load_exercise(cur, exercise_id) + variants = _load_variants(cur, exercise_id) + media = _load_media(cur, exercise_id) + cur.execute( + "SELECT id, publisher_id, release_id FROM distribution_drafts WHERE id = %s AND exercise_id = %s FOR UPDATE", + (str(draft_id), exercise_id), + ) + draft = _one(cur) + if not draft: + raise HTTPException(status_code=404, detail="Entwurf nicht gefunden") + if draft.get("release_id"): + raise HTTPException(status_code=409, detail="Dieser Entwurf ist bereits bestätigt.") + _assert_may_release(cur, exercise, _publisher(cur, str(draft["publisher_id"])), profile_id, role) + snap = snapshot_hash(exercise, variants, media) + cur.execute( + """ + UPDATE distribution_drafts SET cut = %s::jsonb, preview_hash = %s WHERE id = %s + """, + (canonical_json(cut).decode("utf-8"), snap, str(draft_id)), + ) + return {"draft_id": str(draft_id), "cut": cut, "blockers": collect_blockers(exercise, variants, media, cut, _now()), "preview_hash": snap} + + +def _load_cut(value) -> dict: + if isinstance(value, str): + import json + return json.loads(value) + return dict(value) + + +def confirm_draft(cur, exercise_id: int, draft_id: str, profile_id: int, role: str) -> dict: + require_enabled() + cur.execute("SELECT id FROM exercises WHERE id = %s FOR UPDATE", (exercise_id,)) + if cur.fetchone() is None: + raise HTTPException(status_code=404, detail="Übung nicht gefunden") + cur.execute( + """ + SELECT id, publisher_id, recipient_id, cut, preview_hash, release_id + FROM distribution_drafts + WHERE id = %s AND exercise_id = %s + FOR UPDATE + """, + (str(draft_id), exercise_id), + ) + draft = _one(cur) + if not draft: + raise HTTPException(status_code=404, detail="Entwurf nicht gefunden") + exercise = _load_exercise(cur, exercise_id) + publisher = _publisher(cur, str(draft["publisher_id"])) + _assert_may_release(cur, exercise, publisher, profile_id, role) + release_id, created = decide_confirm( + str(draft["release_id"]) if draft.get("release_id") else None, + new_id(), + ) + if not created: + cur.execute( + "SELECT manifest_sha256 FROM distribution_releases WHERE release_id = %s", + (release_id,), + ) + stored = _one(cur) or {} + return {"release_id": release_id, "replayed": True, "manifest_sha256": stored.get("manifest_sha256")} + + variants = _load_variants(cur, exercise_id) + media = _load_media(cur, exercise_id) + snap = snapshot_hash(exercise, variants, media) + if snap != draft["preview_hash"]: + raise HTTPException( + status_code=409, + detail="Die Übung wurde seit der Vorschau geändert. Bitte die Vorschau neu erstellen.", + ) + cut = _load_cut(draft["cut"]) + blockers = collect_blockers(exercise, variants, media, cut, _now()) + if blockers: + raise HTTPException(status_code=400, detail={"code": "release_blocked", "blockers": blockers}) + source_id = str(exercise["public_id"]) + revision = _revision_for(cur, source_id, snap) + published_at = format_utc(_now()) + part_ids = {part["key"]: _part_id(cur, source_id, part["key"]) for part in cut["parts"]} + variant_ids = {} + known_variants = {str(item["public_id"]): str(item["public_id"]) for item in variants} + for variant in cut["variants"]: + variant_ids[variant["key"]] = known_variants.get(variant["key"]) or _variant_id( + cur, source_id, variant["key"], None + ) + media_by_public = {str(item["public_id"]): item for item in media} + copied: list[Path] = [] + asset_rows = [] + try: + for asset in cut["assets"]: + stored = media_by_public[str(asset["media_id"])] + source = Path(stored["file_path"]) + if not source.is_file(): + raise HTTPException(status_code=400, detail="Mediendatei fehlt auf dem Speicher.") + digest, size = hashlib_file(source) + asset_id = str(stored["public_id"]) + target = distribution_media_root() / release_id / asset_id + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + copied.append(target) + asset_rows.append( + { + "id": asset_id, + "role": asset["role"], + "media_type": _MEDIA_TYPE.get((stored.get("media_type") or "").lower(), "application/octet-stream"), + "size_bytes": size, + "sha256": digest, + "rights_id": asset["rights_id"], + "label": asset.get("label"), + "source_media_public_id": asset_id, + "source_asset_id": stored.get("media_asset_id"), + "path": str(target), + } + ) + manifest = { + "schema_version": 1, + "resource_type": "exercise", + "release_id": release_id, + "source_id": source_id, + "revision": revision, + "publisher_id": str(publisher["id"]), + "published_at": published_at, + "exercise": { + "title": cut["title"], + "summary": cut.get("summary"), + "audience": cut.get("audience"), + "rights_id": cut["editorial_rights_id"], + "parts": [ + { + "id": part_ids[part["key"]], + "role": part["role"], + "text": part["text"], + "rights_id": part["rights_id"], + } + for part in cut["parts"] + ], + "assets": [ + { + "id": row["id"], + "role": row["role"], + "media_type": row["media_type"], + "size_bytes": row["size_bytes"], + "sha256": row["sha256"], + "rights_id": row["rights_id"], + "label": row["label"], + } + for row in asset_rows + ], + "common_part_ids": [part_ids[key] for key in cut.get("common_part_keys") or []], + "common_asset_ids": [str(item) for item in cut.get("common_media_ids") or []], + "variants": [ + { + "id": variant_ids[variant["key"]], + "label": variant["label"], + "part_ids": [part_ids[key] for key in variant.get("part_keys") or []], + "asset_ids": [str(item) for item in variant.get("media_ids") or []], + } + for variant in cut["variants"] + ], + }, + "rights": [ + { + "id": right["id"], + "evidence_ref": right["evidence_ref"], + "actions": right["actions"], + "territories": right.get("territories"), + "valid_from": right["valid_from"], + "valid_until": right.get("valid_until"), + "attribution": right.get("attribution"), + } + for right in cut["rights"] + ], + } + body = manifest_bytes(manifest) + digest = sha256_bytes(body) + cur.execute( + """ + INSERT INTO distribution_releases ( + release_id, recipient_id, publisher_id, source_id, revision, cut_hash, + manifest_text, manifest_sha256, published_at, fetch_blocked, confirmed_by + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, false, %s) + """, + ( + release_id, + str(draft["recipient_id"]), + str(publisher["id"]), + source_id, + revision, + cut_hash(cut), + body.decode("utf-8"), + digest, + parse_utc(published_at), + profile_id, + ), + ) + for row in asset_rows: + cur.execute( + """ + INSERT INTO distribution_release_assets ( + release_id, asset_id, sha256, size_bytes, media_type, storage_path, + source_media_public_id, source_asset_id + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + release_id, + row["id"], + row["sha256"], + row["size_bytes"], + row["media_type"], + row["path"], + row["source_media_public_id"], + row["source_asset_id"], + ), + ) + for right in cut["rights"]: + note = right.get("note") + if note: + cur.execute( + """ + INSERT INTO distribution_evidence (id, publisher_id, note, created_by) + VALUES (%s, %s, %s, %s) + ON CONFLICT (id) DO NOTHING + """, + (right["evidence_ref"], str(publisher["id"]), note, profile_id), + ) + append_event( + cur, + str(draft["recipient_id"]), + { + "event_id": new_id(), + "type": "release.published", + "release_id": release_id, + "occurred_at": published_at, + "source_id": source_id, + "revision": revision, + "manifest_sha256": digest, + }, + ) + cur.execute( + "UPDATE distribution_drafts SET release_id = %s, confirmed_at = NOW() WHERE id = %s", + (release_id, str(draft_id)), + ) + return {"release_id": release_id, "replayed": False, "manifest_sha256": digest} + except Exception: + for path in copied: + path.unlink(missing_ok=True) + raise + + +def _release_row(cur, release_id: str) -> dict: + cur.execute( + """ + SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text + FROM distribution_releases WHERE release_id = %s + """, + (str(release_id),), + ) + row = _one(cur) + if not row: + raise HTTPException(status_code=404, detail="Paket nicht gefunden") + return row + + +def _assert_withdraw(cur, release: dict, profile_id: int, role: str) -> None: + require_enabled() + publisher = _publisher(cur, str(release["publisher_id"])) + cur.execute( + """ + SELECT id, public_id, visibility, club_id, created_by + FROM exercises WHERE public_id = %s + """, + (str(release["source_id"]),), + ) + exercise = _one(cur) + denial = ( + "Paket ohne zugehörige Übung." + if not exercise + else _denial_for(cur, exercise, publisher, profile_id, role) + ) + if not can_withdraw(role=role, denial=denial): + raise HTTPException(status_code=403, detail=denial or "Keine Befugnis für diesen Rückzug.") + + +def retire_release(cur, release_id: str, profile_id: int, role: str) -> dict: + release = _release_row(cur, release_id) + _assert_withdraw(cur, release, profile_id, role) + cur.execute( + """ + SELECT 1 AS ok FROM distribution_events + WHERE release_id = %s AND event_type = 'release.retired' + """, + (str(release_id),), + ) + if _one(cur): + return {"release_id": str(release_id), "replayed": True} + append_event( + cur, + str(release["recipient_id"]), + { + "event_id": new_id(), + "type": "release.retired", + "release_id": str(release_id), + "occurred_at": format_utc(_now()), + }, + ) + return {"release_id": str(release_id), "replayed": False} + + +def withdraw_release(cur, release_id: str, reason_code: str, profile_id: int, role: str, kind: str, target_id: Optional[str]) -> dict: + if reason_code not in REASON_CODES: + raise HTTPException(status_code=400, detail="Unbekannte Grundklasse.") + release = _release_row(cur, release_id) + _assert_withdraw(cur, release, profile_id, role) + event_type = { + "release": "release.withdrawn", + "variant": "variant.withdrawn", + "asset": "asset.withdrawn", + }[kind] + if kind != "release" and not target_id: + raise HTTPException(status_code=400, detail="Ziel fehlt.") + event = { + "event_id": new_id(), + "type": event_type, + "release_id": str(release_id), + "occurred_at": format_utc(_now()), + "reason_code": reason_code, + } + if target_id: + event["target_id"] = str(target_id) + append_event(cur, str(release["recipient_id"]), event) + _mark_blocked(cur, str(release_id)) + return {"release_id": str(release_id), "type": event_type} + + +def enforce_expiry(cur, release: dict, now: Optional[datetime] = None) -> None: + if release.get("fetch_blocked"): + return + import json + + manifest = json.loads(release["manifest_text"]) + moment = now or _now() + expired = set() + for right in manifest.get("rights") or []: + until = right.get("valid_until") + if until and parse_utc(until) <= moment: + expired.add(right["id"]) + if not expired: + return + exercise = manifest["exercise"] + events = [] + if exercise.get("rights_id") in expired: + events.append({"type": "release.withdrawn"}) + else: + for asset in exercise.get("assets") or []: + if asset.get("rights_id") in expired: + events.append({"type": "asset.withdrawn", "target_id": asset["id"]}) + if not events: + events.append({"type": "release.withdrawn"}) + stamp = format_utc(moment) + for event in events: + payload = { + "event_id": new_id(), + "type": event["type"], + "release_id": str(release["release_id"]), + "occurred_at": stamp, + "reason_code": "expired", + } + if event.get("target_id"): + payload["target_id"] = event["target_id"] + append_event(cur, str(release["recipient_id"]), payload) + _mark_blocked(cur, str(release["release_id"])) + release["fetch_blocked"] = True + + +def backlog_count(cur) -> int: + cur.execute( + "SELECT manifest_text, fetch_blocked FROM distribution_releases WHERE fetch_blocked = false" + ) + import json + + count = 0 + moment = _now() + for row in _rows(cur): + item = r2d(row) + manifest = json.loads(item["manifest_text"]) + for right in manifest.get("rights") or []: + until = right.get("valid_until") + if until and parse_utc(until) <= moment: + count += 1 + break + return count + + +def issue_key(cur, binding_id: str, expires_at: Optional[str]) -> dict: + cur.execute( + "SELECT id, status, recipient_id FROM distribution_bindings WHERE id = %s", + (str(binding_id),), + ) + binding = _one(cur) + if not binding or binding.get("status") != "active": + raise HTTPException(status_code=404, detail="Anbindung nicht gefunden") + import secrets + + prefix = secrets.token_hex(6) + secret = secrets.token_urlsafe(32) + token = f"shk.{prefix}.{secret}" + cur.execute( + """ + INSERT INTO distribution_keys (id, binding_id, key_prefix, secret_hash, expires_at) + VALUES (%s, %s, %s, %s, %s) + """, + (new_id(), str(binding_id), prefix, hash_pin(token), parse_utc(expires_at) if expires_at else None), + ) + return {"token": token, "prefix": prefix, "expires_at": expires_at} + + +def resolve_bearer(cur, token: str) -> dict: + if not token or not token.startswith("shk.") or token.count(".") < 2: + raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."}) + prefix = token.split(".", 2)[1] + cur.execute( + """ + SELECT k.secret_hash, k.expires_at, k.revoked_at, b.id AS binding_id, b.status AS binding_status, + b.recipient_id, r.status AS recipient_status + FROM distribution_keys k + JOIN distribution_bindings b ON b.id = k.binding_id + JOIN distribution_recipients r ON r.id = b.recipient_id + WHERE k.key_prefix = %s + """, + (prefix,), + ) + row = _one(cur) + if not row or row.get("revoked_at") is not None or not verify_pin(token, row["secret_hash"]): + raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."}) + expires = row.get("expires_at") + if expires is not None: + exp = expires if isinstance(expires, datetime) else parse_utc(str(expires)) + if exp <= _now(): + raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel abgelaufen."}) + if row.get("binding_status") != "active" or row.get("recipient_status") != "active": + raise HTTPException(status_code=403, detail={"code": "binding_suspended", "message": "Anbindung ohne Abrufumfang."}) + allowed, blocked = touch_rate(cur, str(row["binding_id"])) + if blocked: + raise HTTPException( + status_code=429, + detail={"code": "rate_limited", "message": "Abrufgrenze erreicht."}, + headers={"Retry-After": "60", "Cache-Control": "private, no-store"}, + ) + return {"binding_id": str(row["binding_id"]), "recipient_id": str(row["recipient_id"]), "hits": allowed} + + +def touch_rate(cur, binding_id: str) -> tuple[int, bool]: + cur.execute( + "SELECT window_start, hits FROM distribution_rate_windows WHERE binding_id = %s FOR UPDATE", + (binding_id,), + ) + row = _one(cur) + now = _now() + if row is None: + cur.execute( + """ + INSERT INTO distribution_rate_windows (binding_id, window_start, hits) + VALUES (%s, %s, 1) + """, + (binding_id, now), + ) + return 1, False + started = row["window_start"] + if not isinstance(started, datetime): + started = parse_utc(str(started)) + hits, blocked = rate_decision(int(row["hits"]), (now - started).total_seconds()) + if (now - started).total_seconds() >= 60: + cur.execute( + "UPDATE distribution_rate_windows SET window_start = %s, hits = %s WHERE binding_id = %s", + (now, hits, binding_id), + ) + else: + cur.execute( + "UPDATE distribution_rate_windows SET hits = %s WHERE binding_id = %s", + (hits, binding_id), + ) + return hits, blocked + + +def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict: + cur.execute( + """ + SELECT seq, body FROM distribution_events + WHERE recipient_id = %s AND seq > %s + ORDER BY seq + LIMIT %s + """, + (str(recipient_id), cursor_seq, limit + 1), + ) + rows = _rows(cur) + page = rows[:limit] + import json + + events = [] + last_seq = cursor_seq + for row in page: + item = r2d(row) + body = item["body"] + if isinstance(body, str): + body = json.loads(body) + events.append(order_event(body)) + last_seq = int(item["seq"]) + from distribution_contract import cursor_secret, encode_cursor + + return { + "events": events, + "next_cursor": encode_cursor(cursor_secret(), recipient_id, last_seq), + "has_more": len(rows) > limit, + } + + +def load_availability(cur, recipient_id: str, source_id: str) -> dict: + import json + import uuid + + try: + uuid.UUID(str(source_id)) + except ValueError: + raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht gefunden."}) + cur.execute( + """ + SELECT release_id, revision, fetch_blocked, manifest_text, publisher_id, recipient_id + FROM distribution_releases + WHERE source_id = %s AND recipient_id = %s + ORDER BY revision, published_at + """, + (str(source_id), str(recipient_id)), + ) + rows = [r2d(row) for row in _rows(cur)] + if not rows: + raise HTTPException( + status_code=404, + detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."}, + ) + cur.execute("SELECT status FROM exercises WHERE public_id = %s", (str(source_id),)) + source = _one(cur) + releases = [] + for row in rows: + enforce_expiry(cur, row) + cur.execute( + """ + SELECT event_type, body + FROM distribution_events + WHERE release_id = %s + AND event_type IN ('release.retired', 'release.withdrawn', 'variant.withdrawn', 'asset.withdrawn') + ORDER BY seq DESC + """, + (str(row["release_id"]),), + ) + retired = False + reason = None + for event in _rows(cur): + item = r2d(event) + if item["event_type"] == "release.retired": + retired = True + continue + if reason is None: + body = item["body"] + if isinstance(body, str): + body = json.loads(body) + reason = (body or {}).get("reason_code") + state = package_state(fetch_blocked=bool(row.get("fetch_blocked")), retired=retired) + releases.append( + { + "release_id": str(row["release_id"]), + "revision": row["revision"], + "package": state, + "fetchable": state != "withdrawn", + "reason_code": reason if state == "withdrawn" else None, + } + ) + status, offerable = exercise_offerable( + source.get("status") if source else None, + [item["package"] for item in releases], + ) + return { + "source_id": str(source_id), + "source_status": status, + "offerable": offerable, + "releases": releases, + } + + +def load_manifest(cur, recipient_id: str, release_id: str) -> bytes: + cur.execute( + """ + SELECT release_id, recipient_id, publisher_id, fetch_blocked, manifest_text + FROM distribution_releases WHERE release_id = %s + """, + (str(release_id),), + ) + 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."}) + 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) -> tuple[Path, str]: + cur.execute( + """ + SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, + a.storage_path, a.media_type, a.sha256 + FROM distribution_releases r + JOIN distribution_release_assets a ON a.release_id = r.release_id + WHERE r.release_id = %s AND a.asset_id = %s + """, + (str(release_id), str(asset_id)), + ) + 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."}) + enforce_expiry(cur, row) + if row.get("fetch_blocked"): + raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."}) + path = Path(row["storage_path"]) + digest, _size = hashlib_file(path) + if digest != row["sha256"]: + raise HTTPException(status_code=500, detail={"code": "integrity", "message": "Medienprüfsumme stimmt nicht."}) + return path, row["media_type"] diff --git a/backend/main.py b/backend/main.py index 8ab8407..617a6b5 100644 --- a/backend/main.py +++ b/backend/main.py @@ -243,7 +243,7 @@ def read_root(): return out # Register routers -from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin +from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin, distribution app.include_router(auth.router) app.include_router(profiles.router) @@ -281,6 +281,8 @@ app.include_router(ai_prompts_admin.router) app.include_router(openrouter_admin.router) app.include_router(ai_skill_retrieval_admin.router) app.include_router(exercise_enrichment_admin.router) +app.include_router(distribution.router) +app.include_router(distribution.editorial) # Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad # GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken). diff --git a/backend/media_legal_hold.py b/backend/media_legal_hold.py index 04fce0c..4e62127 100644 --- a/backend/media_legal_hold.py +++ b/backend/media_legal_hold.py @@ -134,6 +134,10 @@ def set_legal_hold( updated_row = cur.fetchone() updated = r2d(updated_row) + from distribution_service import withdraw_assets_for_media_asset + + withdraw_assets_for_media_asset(cur, asset_id, reason_code) + write_audit_log_entry( cur, asset_id=asset_id, diff --git a/backend/migrations/099_distribution.sql b/backend/migrations/099_distribution.sql new file mode 100644 index 0000000..e783162 --- /dev/null +++ b/backend/migrations/099_distribution.sql @@ -0,0 +1,191 @@ +-- Distribution v1: eingefrorene Übungspakete für Empfängerkanäle. +-- Produktiver Abruf bleibt über DISTRIBUTION_ENABLED aus, bis die Testinstanz ihn einschaltet. + +ALTER TABLE exercises + ADD COLUMN IF NOT EXISTS public_id UUID; + +UPDATE exercises SET public_id = gen_random_uuid() WHERE public_id IS NULL; + +ALTER TABLE exercises + ALTER COLUMN public_id SET DEFAULT gen_random_uuid(); + +ALTER TABLE exercises + ALTER COLUMN public_id SET NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_exercises_public_id ON exercises (public_id); + +ALTER TABLE exercise_variants + ADD COLUMN IF NOT EXISTS public_id UUID; + +UPDATE exercise_variants SET public_id = gen_random_uuid() WHERE public_id IS NULL; + +ALTER TABLE exercise_variants + ALTER COLUMN public_id SET DEFAULT gen_random_uuid(); + +ALTER TABLE exercise_variants + ALTER COLUMN public_id SET NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_variants_public_id ON exercise_variants (public_id); + +ALTER TABLE exercise_media + ADD COLUMN IF NOT EXISTS public_id UUID; + +UPDATE exercise_media SET public_id = gen_random_uuid() WHERE public_id IS NULL; + +ALTER TABLE exercise_media + ALTER COLUMN public_id SET DEFAULT gen_random_uuid(); + +ALTER TABLE exercise_media + ALTER COLUMN public_id SET NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_media_public_id ON exercise_media (public_id); + +CREATE TABLE IF NOT EXISTS distribution_publishers ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('platform', 'own', 'club')), + club_id INT REFERENCES clubs (id), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT distribution_publishers_kind_club CHECK ( + (kind = 'club' AND club_id IS NOT NULL) + OR (kind <> 'club' AND club_id IS NULL) + ) +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_distribution_platform_publisher + ON distribution_publishers (kind) + WHERE kind = 'platform'; + +CREATE TABLE IF NOT EXISTS distribution_recipients ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS distribution_relationships ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + recipient_id UUID NOT NULL REFERENCES distribution_recipients (id), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')), + UNIQUE (publisher_id, recipient_id) +); + +CREATE TABLE IF NOT EXISTS distribution_bindings ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + recipient_id UUID NOT NULL REFERENCES distribution_recipients (id), + name TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS distribution_keys ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + binding_id UUID NOT NULL REFERENCES distribution_bindings (id), + key_prefix TEXT NOT NULL UNIQUE, + secret_hash TEXT NOT NULL, + expires_at TIMESTAMPTZ, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS distribution_releasers ( + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + profile_id INT NOT NULL REFERENCES profiles (id), + PRIMARY KEY (publisher_id, profile_id) +); + +CREATE TABLE IF NOT EXISTS distribution_publisher_exercises ( + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + exercise_id INT NOT NULL REFERENCES exercises (id), + PRIMARY KEY (publisher_id, exercise_id) +); + +CREATE TABLE IF NOT EXISTS distribution_part_identities ( + source_id UUID NOT NULL, + part_key TEXT NOT NULL, + part_id UUID NOT NULL, + PRIMARY KEY (source_id, part_key) +); + +CREATE TABLE IF NOT EXISTS distribution_source_revisions ( + source_id UUID NOT NULL, + revision INT NOT NULL CHECK (revision > 0), + snapshot_hash TEXT NOT NULL, + PRIMARY KEY (source_id, revision), + UNIQUE (source_id, snapshot_hash) +); + +CREATE TABLE IF NOT EXISTS distribution_drafts ( + id UUID PRIMARY KEY, + exercise_id INT NOT NULL REFERENCES exercises (id), + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + recipient_id UUID NOT NULL REFERENCES distribution_recipients (id), + prepared_by INT NOT NULL REFERENCES profiles (id), + cut JSONB NOT NULL, + preview_hash TEXT NOT NULL, + release_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + confirmed_at TIMESTAMPTZ +); + +CREATE TABLE IF NOT EXISTS distribution_releases ( + release_id UUID PRIMARY KEY, + recipient_id UUID NOT NULL REFERENCES distribution_recipients (id), + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + source_id UUID NOT NULL, + revision INT NOT NULL, + cut_hash TEXT NOT NULL, + manifest_text TEXT NOT NULL, + manifest_sha256 TEXT NOT NULL, + published_at TIMESTAMPTZ NOT NULL, + fetch_blocked BOOLEAN NOT NULL DEFAULT FALSE, + confirmed_by INT REFERENCES profiles (id) +); + +CREATE INDEX IF NOT EXISTS idx_distribution_releases_source ON distribution_releases (source_id); +CREATE INDEX IF NOT EXISTS idx_distribution_releases_recipient ON distribution_releases (recipient_id); + +CREATE TABLE IF NOT EXISTS distribution_release_assets ( + release_id UUID NOT NULL REFERENCES distribution_releases (release_id), + asset_id UUID NOT NULL, + sha256 TEXT NOT NULL, + size_bytes INT NOT NULL, + media_type TEXT NOT NULL, + storage_path TEXT NOT NULL, + source_media_public_id UUID, + source_asset_id INT, + PRIMARY KEY (release_id, asset_id) +); + +CREATE INDEX IF NOT EXISTS idx_distribution_release_assets_source + ON distribution_release_assets (source_asset_id); + +CREATE TABLE IF NOT EXISTS distribution_events ( + event_id UUID PRIMARY KEY, + recipient_id UUID NOT NULL REFERENCES distribution_recipients (id), + seq BIGINT NOT NULL, + event_type TEXT NOT NULL, + release_id UUID NOT NULL, + occurred_at TIMESTAMPTZ NOT NULL, + body JSONB NOT NULL, + UNIQUE (recipient_id, seq) +); + +CREATE INDEX IF NOT EXISTS idx_distribution_events_feed + ON distribution_events (recipient_id, seq); + +CREATE TABLE IF NOT EXISTS distribution_evidence ( + id TEXT PRIMARY KEY, + publisher_id UUID NOT NULL REFERENCES distribution_publishers (id), + note TEXT NOT NULL, + created_by INT NOT NULL REFERENCES profiles (id), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE TABLE IF NOT EXISTS distribution_rate_windows ( + binding_id UUID PRIMARY KEY REFERENCES distribution_bindings (id), + window_start TIMESTAMPTZ NOT NULL, + hits INT NOT NULL +); diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py new file mode 100644 index 0000000..2dc97fc --- /dev/null +++ b/backend/routers/distribution.py @@ -0,0 +1,460 @@ +"""Distributionsfreigabe: Maschinenabruf und Redaktion. + +Maschinenabruf authentifiziert allein über den Distributions-Schlüssel. +# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung. +Die Redaktions- und Verwaltungsrouten nutzen TenantContext. +""" +from __future__ import annotations + +from typing import Optional + +from fastapi import APIRouter, Depends, Header, HTTPException, Query +from fastapi.responses import FileResponse, Response +from pydantic import BaseModel, Field + +from club_tenancy import is_superadmin +from db import get_cursor, get_db +from distribution_contract import ( + InvalidCursor, + cursor_secret, + decode_cursor, + distribution_enabled, +) +from distribution_service import ( + backlog_count, + confirm_draft, + create_draft, + issue_key, + list_changes, + load_asset, + load_availability, + load_manifest, + overview, + resolve_bearer, + retire_release, + update_draft, + withdraw_release, +) +from tenant_context import TenantContext, get_tenant_context + +router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"]) +editorial = APIRouter(tags=["distribution-editorial"]) + +NO_STORE = {"Cache-Control": "private, no-store"} + + +def _machine(authorization: Optional[str]): + if not distribution_enabled(): + raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE) + if not authorization or not authorization.lower().startswith("bearer "): + raise HTTPException( + status_code=401, + detail={"code": "invalid_key", "message": "Schlüssel ungültig."}, + headers=NO_STORE, + ) + token = authorization.split(" ", 1)[1].strip() + held: Optional[HTTPException] = None + binding = None + with get_db() as conn: + cur = get_cursor(conn) + try: + binding = resolve_bearer(cur, token) + except HTTPException as exc: + held = exc + if held is not None: + held.headers = {**(held.headers or {}), **NO_STORE} + raise held + return binding + + +def _superadmin(tenant: TenantContext) -> None: + if not is_superadmin(tenant.global_role): + raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.") + + +class PublisherBody(BaseModel): + name: str = Field(min_length=1, max_length=200) + kind: str + club_id: Optional[int] = None + + +class RecipientBody(BaseModel): + name: str = Field(min_length=1, max_length=200) + + +class RelationshipBody(BaseModel): + publisher_id: str + recipient_id: str + + +class BindingBody(BaseModel): + recipient_id: str + name: str = Field(min_length=1, max_length=200) + + +class KeyBody(BaseModel): + expires_at: Optional[str] = None + + +class ProfileBody(BaseModel): + profile_id: int + + +class ExerciseAssignBody(BaseModel): + exercise_id: int + + +class SuspendBody(BaseModel): + kind: str + id: str + + +class DraftBody(BaseModel): + publisher_id: str + recipient_id: str + cut: Optional[dict] = None + + +class CutBody(BaseModel): + cut: dict + + +class ReasonBody(BaseModel): + reason_code: str + + +@router.get("/changes") +def get_changes( + cursor: Optional[str] = None, + limit: Optional[int] = Query(default=None), + authorization: Optional[str] = Header(default=None), +): + binding = _machine(authorization) + if limit is None: + limit = 50 + elif limit < 1 or limit > 100: + raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE) + try: + seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor) + except InvalidCursor: + raise HTTPException( + status_code=400, + detail={"code": "invalid_cursor", "message": "Cursor ungültig."}, + headers=NO_STORE, + ) + with get_db() as conn: + cur = get_cursor(conn) + payload = list_changes(cur, binding["recipient_id"], seq, limit) + return Response( + content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")), + media_type="application/json", + headers=NO_STORE, + ) + + +@router.get("/exercises/{source_id}/availability") +def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)): + binding = _machine(authorization) + held: Optional[HTTPException] = None + payload = None + with get_db() as conn: + cur = get_cursor(conn) + try: + payload = load_availability(cur, binding["recipient_id"], source_id) + except HTTPException as exc: + held = exc + if held is not None: + held.headers = {**(held.headers or {}), **NO_STORE} + raise held + return Response( + content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")), + media_type="application/json", + headers=NO_STORE, + ) + + +@router.get("/releases/{release_id}") +def get_release(release_id: str, authorization: Optional[str] = Header(default=None)): + binding = _machine(authorization) + held: Optional[HTTPException] = None + body = b"" + with get_db() as conn: + cur = get_cursor(conn) + try: + body = load_manifest(cur, binding["recipient_id"], release_id) + except HTTPException as exc: + held = exc + if held is not None: + held.headers = {**(held.headers or {}), **NO_STORE} + raise held + return Response(content=body, media_type="application/json", headers=NO_STORE) + + +@router.get("/releases/{release_id}/assets/{asset_id}") +def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)): + binding = _machine(authorization) + held: Optional[HTTPException] = None + path = None + media_type = "application/octet-stream" + with get_db() as conn: + cur = get_cursor(conn) + try: + path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id) + except HTTPException as exc: + held = exc + if held is not None: + held.headers = {**(held.headers or {}), **NO_STORE} + raise held + return FileResponse(path, media_type=media_type, headers=NO_STORE) + + +@editorial.get("/api/exercises/{exercise_id}/distribution") +def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "") + + +@editorial.post("/api/exercises/{exercise_id}/distribution/drafts") +def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + from routers.exercises import _assert_can_edit_exercise + + _assert_can_edit_exercise(cur, exercise_id, tenant) + result = create_draft( + cur, + exercise_id, + body.publisher_id, + body.recipient_id, + tenant.profile_id, + tenant.global_role or "", + body.cut, + ) + conn.commit() + return result + + +@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}") +def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + from routers.exercises import _assert_can_edit_exercise + + _assert_can_edit_exercise(cur, exercise_id, tenant) + result = update_draft( + cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or "" + ) + conn.commit() + return result + + +@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm") +def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "") + conn.commit() + return result + + +@editorial.post("/api/distribution/releases/{release_id}/retire") +def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "") + conn.commit() + return result + + +@editorial.post("/api/distribution/releases/{release_id}/withdraw") +def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None) + conn.commit() + return result + + +@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw") +def post_withdraw_variant( + release_id: str, + variant_id: str, + body: ReasonBody, + tenant: TenantContext = Depends(get_tenant_context), +): + with get_db() as conn: + cur = get_cursor(conn) + result = withdraw_release( + cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id + ) + conn.commit() + return result + + +@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw") +def post_withdraw_asset( + release_id: str, + asset_id: str, + body: ReasonBody, + tenant: TenantContext = Depends(get_tenant_context), +): + with get_db() as conn: + cur = get_cursor(conn) + result = withdraw_release( + cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id + ) + conn.commit() + return result + + +@editorial.post("/api/distribution/admin/publishers") +def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + if body.kind not in ("platform", "own", "club"): + raise HTTPException(status_code=400, detail="kind ist platform, own oder club.") + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + """ + INSERT INTO distribution_publishers (name, kind, club_id) + VALUES (%s, %s, %s) + RETURNING id + """, + (body.name, body.kind, body.club_id), + ) + row = cur.fetchone() + conn.commit() + return {"id": str(row["id"])} + + +@editorial.post("/api/distribution/admin/recipients") +def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + "INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id", + (body.name,), + ) + row = cur.fetchone() + conn.commit() + return {"id": str(row["id"])} + + +@editorial.post("/api/distribution/admin/relationships") +def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + """ + INSERT INTO distribution_relationships (publisher_id, recipient_id) + VALUES (%s, %s) + RETURNING id + """, + (body.publisher_id, body.recipient_id), + ) + row = cur.fetchone() + conn.commit() + return {"id": str(row["id"])} + + +@editorial.post("/api/distribution/admin/bindings") +def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + """ + INSERT INTO distribution_bindings (recipient_id, name) + VALUES (%s, %s) + RETURNING id + """, + (body.recipient_id, body.name), + ) + row = cur.fetchone() + conn.commit() + return {"id": str(row["id"])} + + +@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys") +def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + result = issue_key(cur, binding_id, body.expires_at) + conn.commit() + return result + + +@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke") +def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + "UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL", + (key_prefix,), + ) + conn.commit() + return {"ok": True} + + +@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers") +def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + """ + INSERT INTO distribution_releasers (publisher_id, profile_id) + VALUES (%s, %s) + ON CONFLICT DO NOTHING + """, + (publisher_id, body.profile_id), + ) + conn.commit() + return {"ok": True} + + +@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises") +def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + cur.execute( + """ + INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id) + VALUES (%s, %s) + ON CONFLICT DO NOTHING + """, + (publisher_id, body.exercise_id), + ) + conn.commit() + return {"ok": True} + + +@editorial.post("/api/distribution/admin/suspend") +def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + table = { + "publisher": "distribution_publishers", + "recipient": "distribution_recipients", + "binding": "distribution_bindings", + }.get(body.kind) + if table is None: + raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.") + with get_db() as conn: + cur = get_cursor(conn) + cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,)) + conn.commit() + return {"ok": True} + + +@editorial.get("/api/distribution/admin/backlog") +def get_backlog(tenant: TenantContext = Depends(get_tenant_context)): + _superadmin(tenant) + with get_db() as conn: + cur = get_cursor(conn) + return {"count": backlog_count(cur)} diff --git a/backend/routers/exercises.py b/backend/routers/exercises.py index 0df30ee..7778789 100644 --- a/backend/routers/exercises.py +++ b/backend/routers/exercises.py @@ -29,6 +29,7 @@ from club_tenancy import ( club_admin_shares_club_with_creator, has_club_role, is_platform_admin, + is_superadmin, library_content_visible_to_profile, ) from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql @@ -39,6 +40,8 @@ from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContex from ai_prompt_job import run_exercise_form_ai_suggestion from account_lifecycle import assert_min_account_state from capabilities import probe_capability +from distribution_contract import OFFICIAL_WRITE_DENIED, official_write_allowed +from distribution_service import blocks_exercise_delete, blocks_media_delete, blocks_variant_delete from club_features import ( consume_club_feature_with_usage, merge_feature_usage_into_response, @@ -563,11 +566,13 @@ def _assert_can_edit_exercise(cur, exercise_id: int, tenant: TenantContext) -> N owner = rd.get("created_by") if owner is not None: owner = int(owner) + ex_vis = (rd.get("visibility") or "private").strip().lower() + if not official_write_allowed(ex_vis, role): + raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED) if owner == profile_id: return if is_platform_admin(role): return - ex_vis = (rd.get("visibility") or "private").strip().lower() ex_cid_raw = rd.get("club_id") ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role): @@ -1458,9 +1463,13 @@ def _exercise_delete_usage_message(counts: dict) -> str: def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None: pid = tenant.profile_id role = tenant.global_role + vis = str(row.get("visibility") or "private").strip().lower() + if vis == "official": + if not is_superadmin(role): + raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED) + return if is_platform_admin(role): return - vis = str(row.get("visibility") or "private").strip().lower() cid = row.get("club_id") creator = row.get("created_by") try: @@ -1468,11 +1477,6 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None: except (TypeError, ValueError): creator_int = None - if vis == "official": - raise HTTPException( - status_code=403, - detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.", - ) if vis == "club": try: ex_club = int(cid) if cid is not None else None @@ -1598,6 +1602,9 @@ def bulk_patch_exercises_metadata( owner = int(owner) ex_vis = (rowd.get("visibility") or "private").strip().lower() + if not official_write_allowed(ex_vis, role): + failed.append({"id": ex_id, "detail": OFFICIAL_WRITE_DENIED}) + continue ex_cid_raw = rowd.get("club_id") ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None @@ -2833,6 +2840,11 @@ def delete_exercise( usage_msg = _exercise_delete_usage_message(counts) if usage_msg: raise HTTPException(status_code=409, detail=usage_msg) + if blocks_exercise_delete(cur, exercise_id): + raise HTTPException( + status_code=409, + detail="Die Übung hat eine externe Freigabe und kann nicht gelöscht werden.", + ) cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,)) conn.commit() @@ -3040,6 +3052,11 @@ def delete_exercise_variant( cur = get_cursor(conn) _assert_can_edit_exercise(cur, exercise_id, tenant) assert_exercise_not_combination(cur, exercise_id) + if blocks_variant_delete(cur, variant_id): + raise HTTPException( + status_code=409, + detail="Die Variante ist Teil einer externen Freigabe und kann nicht gelöscht werden.", + ) _fetch_variant_row(cur, exercise_id, variant_id) cur.execute( @@ -3840,6 +3857,11 @@ def delete_exercise_media( row = cur.fetchone() if not row: raise HTTPException(status_code=404, detail="Medium nicht gefunden") + if blocks_media_delete(cur, media_id): + raise HTTPException( + status_code=409, + detail="Das Medium ist Teil einer externen Freigabe und kann nicht gelöst werden.", + ) rec = r2d(row) media_asset_id = rec.get("media_asset_id") if media_asset_id: diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py new file mode 100644 index 0000000..a71cb96 --- /dev/null +++ b/backend/tests/test_distribution_contract.py @@ -0,0 +1,259 @@ +"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug.""" +from __future__ import annotations + +import inspect +import json +import os +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from fastapi import HTTPException +from fastapi.testclient import TestClient + +os.environ.setdefault("SKIP_DB_MIGRATE", "1") + +from auth import require_auth +from distribution_service import _lock_recipient +from distribution_contract import ( + InvalidCursor, + actions_cover, + cursor_secret, + decide_confirm, + decode_cursor, + encode_cursor, + exercise_offerable, + package_state, + manifest_bytes, + official_write_allowed, + plan_available, + rate_decision, + release_denial, + retrievable_release_ids, + sha256_bytes, +) +from main import app +from routers.exercises import _assert_can_edit_exercise +from tenant_context import TenantContext, get_tenant_context + +FIXTURE = json.loads( + (Path(__file__).resolve().parents[2] / "docs" / "architecture" / "distribution" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text( + encoding="utf-8" + ) +) + + +def test_fixture_manifest_hashes_match_contract_order() -> None: + for release in FIXTURE["releases"].values(): + body = manifest_bytes(release["manifest"]) + assert sha256_bytes(body) == release["manifest_sha256"] + assert not body.endswith(b"\n") + + +def test_reference_case_retrieval_and_plan_effect() -> None: + lara_events = FIXTURE["channels"]["lara_felix"]["events"] + second_events = FIXTURE["channels"]["zweiter_verein"]["events"] + assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"]) + assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"]) + manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()} + blocked = [] + available = [] + for name, plan in FIXTURE["plans"].items(): + if plan_available(plan, manifests[plan["release_id"]], lara_events): + available.append(name) + else: + blocked.append(name) + assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"]) + assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"]) + film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"] + assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"] + assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"] + + +def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None: + drafts: dict[str, str] = {} + releases: dict[str, dict] = {} + events: list[tuple[str, str]] = [] + + def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]: + release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}") + if created: + drafts[draft_id] = release_id + releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut} + events.append(("published", release_id)) + return release_id, created + + first, created = confirm("draft-1", 1, "same-cut") + again, replayed = confirm("draft-1", 1, "same-cut") + assert first == again + assert created is True + assert replayed is False + assert events == [("published", first)] + + releases[first]["withdrawn"] = True + second, created_again = confirm("draft-2", 1, "same-cut") + assert created_again is True + assert second != first + assert releases[first]["withdrawn"] is True + assert releases[second]["revision"] == 1 + assert releases[second]["cut"] == "same-cut" + assert [kind for kind, _ in events] == ["published", "published"] + + +def test_availability_keeps_the_copy_and_stops_new_offers() -> None: + assert package_state(fetch_blocked=False, retired=False) == "available" + assert package_state(fetch_blocked=False, retired=True) == "retired" + assert package_state(fetch_blocked=True, retired=True) == "withdrawn" + status, offerable = exercise_offerable("approved", ["available"]) + assert status == "approved" and offerable is True + status, offerable = exercise_offerable("archived", ["available"]) + assert status == "archived" and offerable is False + status, offerable = exercise_offerable(None, ["withdrawn"]) + assert status == "deleted" and offerable is False + status, offerable = exercise_offerable("approved", ["retired", "withdrawn"]) + assert offerable is False + + +def test_cursor_is_bound_to_recipient() -> None: + secret = cursor_secret() + token = encode_cursor(secret, "recipient-a", 4) + assert decode_cursor(secret, "recipient-a", token) == 4 + assert decode_cursor(secret, "recipient-a", None) == 0 + with pytest.raises(InvalidCursor): + decode_cursor(secret, "recipient-b", token) + + +def test_rate_window_blocks_at_sixty() -> None: + hits, blocked = rate_decision(59, 10) + assert hits == 60 and blocked is False + hits, blocked = rate_decision(60, 10) + assert blocked is True + hits, blocked = rate_decision(60, 61) + assert hits == 1 and blocked is False + + +def test_official_release_and_edit_roles() -> None: + assert official_write_allowed("official", "superadmin") is True + assert official_write_allowed("official", "admin") is False + assert official_write_allowed("official", "club_admin") is False + assert official_write_allowed("club", "admin") is True + assert release_denial( + visibility="official", + role="admin", + publisher_kind="platform", + is_owner=True, + is_club_admin=False, + ) + assert release_denial( + visibility="official", + role="superadmin", + publisher_kind="platform", + is_owner=False, + is_club_admin=False, + ) is None + assert release_denial( + visibility="private", + role="trainer", + publisher_kind="own", + is_owner=True, + is_club_admin=False, + ) is None + assert release_denial( + visibility="private", + role="admin", + publisher_kind="own", + is_owner=False, + is_club_admin=False, + ) + assert release_denial( + visibility="club", + role="trainer", + publisher_kind="club", + is_owner=True, + is_club_admin=False, + publisher_club_id=4, + exercise_club_id=4, + ) + assert release_denial( + visibility="club", + role="trainer", + publisher_kind="club", + is_owner=False, + is_club_admin=True, + publisher_club_id=4, + exercise_club_id=4, + ) is None + assert release_denial( + visibility="club", + role="trainer", + publisher_kind="club", + is_owner=False, + is_club_admin=True, + publisher_club_id=9, + exercise_club_id=4, + ) + + +def _tenant(role: str, profile_id: int = 7) -> TenantContext: + return TenantContext( + profile_id=profile_id, + global_role=role, + effective_club_id=None, + club_ids=frozenset(), + memberships=[], + ) + + +def test_assert_edit_rejects_admin_and_club_role_for_official() -> None: + cur = MagicMock() + cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None} + for role in ("admin", "trainer", "club_admin"): + with pytest.raises(HTTPException) as caught: + _assert_can_edit_exercise(cur, 3, _tenant(role)) + assert caught.value.status_code == 403 + _assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1)) + + +@pytest.fixture +def client() -> TestClient: + return TestClient(app) + + +def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False) + response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"}) + assert response.status_code == 404 + assert response.headers.get("cache-control") == "private, no-store" + + +def test_channel_sequence_is_locked() -> None: + assert "FOR UPDATE" in inspect.getsource(_lock_recipient) + + +def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None: + app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"} + app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4) + mock_cur = MagicMock() + mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None} + mock_cm = MagicMock() + mock_cm.__enter__.return_value = MagicMock() + mock_cm.__exit__.return_value = False + try: + with patch("routers.exercises.get_db", return_value=mock_cm), patch( + "routers.exercises.get_cursor", return_value=mock_cur + ): + variant = client.post( + "/api/exercises/9/variants", + headers={"X-Auth-Token": "t"}, + json={"variant_name": "Kartenweg"}, + ) + media = client.post( + "/api/exercises/9/media/from-asset", + headers={"X-Auth-Token": "t"}, + json={"media_asset_id": 3}, + ) + assert variant.status_code == 403 + assert media.status_code == 403 + finally: + app.dependency_overrides.pop(require_auth, None) + app.dependency_overrides.pop(get_tenant_context, None) diff --git a/backend/version.py b/backend/version.py index bb8e470..3bb3871 100644 --- a/backend/version.py +++ b/backend/version.py @@ -1,8 +1,8 @@ # Shinkan Jinkendo Version Information -APP_VERSION = "0.8.250" +APP_VERSION = "0.8.252" BUILD_DATE = "2026-11-23" -DB_SCHEMA_VERSION = "20261123098" +DB_SCHEMA_VERSION = "20261123099" MODULE_VERSIONS = { "legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste) @@ -38,7 +38,8 @@ MODULE_VERSIONS = { "skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder "skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions "methods": "0.1.0", - "exercises": "2.37.2", # Upload-MIME nur aus Magic Bytes; PDF als Anhang; Rich-Text-Allowlist beim Speichern + "exercises": "2.38.0", # Globale Übungen schreibt und gibt nur superadmin frei + "distribution": "1.1.0", # Freigabe folgt der Übung: Besitzer, Vereinsadmin, Superadmin für global "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", @@ -54,6 +55,21 @@ MODULE_VERSIONS = { } CHANGELOG = [ + { + "version": "0.8.252", + "date": "2026-11-23", + "changes": [ + "Externe Freigabe folgt der Übung: private Übungen gibt der Besitzer frei, Vereinsübungen der Vereinsadmin, globale Übungen nur ein Superadmin.", + "Empfänger fragen die Verfügbarkeit einer freigegebenen Übung ab. Archiv und Löschung der Quelle beenden neue Angebote, die eingefrorene Kopie bleibt bis zum Rückzug abrufbar.", + ], + }, + { + "version": "0.8.251", + "date": "2026-11-23", + "changes": [ + "Eingefrorene Übungsfassungen können für einen Empfängerkanal freigegeben und per Distributions-Schlüssel abgerufen werden. Globale Übungen bearbeitet und gibt nur ein Superadmin frei. Die Distribution bleibt aus, bis DISTRIBUTION_ENABLED gesetzt ist.", + ], + }, { "version": "0.8.250", "date": "2026-11-23", diff --git a/docker-compose.dev-env.yml b/docker-compose.dev-env.yml index b24d4d3..bd2b27c 100644 --- a/docker-compose.dev-env.yml +++ b/docker-compose.dev-env.yml @@ -38,6 +38,7 @@ services: APP_URL: "${APP_URL:-https://dev.shinkan.jinkendo.de}" ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098}" ENVIRONMENT: "${ENVIRONMENT:-development}" + DISTRIBUTION_ENABLED: "${DISTRIBUTION_ENABLED:-1}" AUTO_ADMIN_FIRST_USER: "${AUTO_ADMIN_FIRST_USER:-false}" REQUIRE_ADMIN_TOTP: "${REQUIRE_ADMIN_TOTP:-false}" # M5: Hard-Block Vereins-Kontingente (Default aus — in .env auf 1 setzen zum Testen) diff --git a/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json b/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json new file mode 100644 index 0000000..51820e8 --- /dev/null +++ b/docs/architecture/distribution/Shinkan_Lara_Felix_Referenzfall_v1.json @@ -0,0 +1,493 @@ +{ + "fixture_version": 1, + "note": "Synthetische Inhalte ohne produktive Rechte. Die Medienbytes dienen der Testung von Groesse und Hash. Sie sind keine abspielbare Filmdatei.", + "manifest_serialization": "UTF-8, JSON ohne Leerraum, Reihenfolge der Felder aus manifest, kein abschliessender Zeilenumbruch", + "channels": { + "lara_felix": { + "recipient_id": "caa20000-0000-4000-8000-0000000001f5", + "events": [ + { + "event_id": "caa20000-0000-4000-8000-000000000258", + "type": "release.published", + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "occurred_at": "2026-11-23T09:01:00Z", + "source_id": "caa20000-0000-4000-8000-00000000000a", + "revision": 1, + "manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c" + }, + { + "event_id": "caa20000-0000-4000-8000-000000000259", + "type": "release.published", + "release_id": "caa20000-0000-4000-8000-0000000000ca", + "occurred_at": "2026-11-23T09:02:00Z", + "source_id": "caa20000-0000-4000-8000-00000000000b", + "revision": 1, + "manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744" + }, + { + "event_id": "caa20000-0000-4000-8000-00000000025a", + "type": "release.published", + "release_id": "caa20000-0000-4000-8000-0000000000cb", + "occurred_at": "2026-11-23T09:03:00Z", + "source_id": "caa20000-0000-4000-8000-00000000000a", + "revision": 2, + "manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0" + }, + { + "event_id": "caa20000-0000-4000-8000-00000000025b", + "type": "release.retired", + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "occurred_at": "2026-11-23T09:04:00Z" + }, + { + "event_id": "caa20000-0000-4000-8000-00000000025c", + "type": "asset.withdrawn", + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "occurred_at": "2026-11-23T09:05:00Z", + "target_id": "caa20000-0000-4000-8000-00000000012c", + "reason_code": "rights" + }, + { + "event_id": "caa20000-0000-4000-8000-00000000025d", + "type": "asset.withdrawn", + "release_id": "caa20000-0000-4000-8000-0000000000cb", + "occurred_at": "2026-11-23T09:05:00Z", + "target_id": "caa20000-0000-4000-8000-00000000012c", + "reason_code": "rights" + } + ] + }, + "zweiter_verein": { + "recipient_id": "caa20000-0000-4000-8000-0000000001f6", + "events": [ + { + "event_id": "caa20000-0000-4000-8000-0000000002bc", + "type": "release.published", + "release_id": "caa20000-0000-4000-8000-0000000000cc", + "occurred_at": "2026-11-23T09:03:00Z", + "source_id": "caa20000-0000-4000-8000-00000000000c", + "revision": 1, + "manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603" + } + ] + } + }, + "releases": { + "vereinsfassung_1": { + "channel": "lara_felix", + "manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c", + "manifest": { + "schema_version": 1, + "resource_type": "exercise", + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "source_id": "caa20000-0000-4000-8000-00000000000a", + "revision": 1, + "publisher_id": "caa20000-0000-4000-8000-00000000177a", + "published_at": "2026-11-23T09:01:00Z", + "exercise": { + "title": "Raum und Wege wahrnehmen", + "audience": "Kursleitungen", + "rights_id": "caa20000-0000-4000-8000-000000000191", + "parts": [ + { + "id": "caa20000-0000-4000-8000-000000000065", + "role": "goal", + "text": "Die Gruppe nimmt freie Wege im Raum wahr.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000066", + "role": "instructions", + "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000067", + "role": "trainer_notes", + "text": "Vorab genug Platz vorsehen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000068", + "role": "instructions", + "text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + } + ], + "assets": [ + { + "id": "caa20000-0000-4000-8000-00000000012c", + "role": "demonstration", + "media_type": "video/mp4", + "size_bytes": 32, + "sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915", + "rights_id": "caa20000-0000-4000-8000-000000000192", + "label": "Demonstrationsfilm" + } + ], + "common_part_ids": [ + "caa20000-0000-4000-8000-000000000065", + "caa20000-0000-4000-8000-000000000067" + ], + "common_asset_ids": [], + "variants": [ + { + "id": "caa20000-0000-4000-8000-00000000006b", + "label": "Kartenvariante", + "part_ids": [ + "caa20000-0000-4000-8000-000000000066" + ], + "asset_ids": [] + }, + { + "id": "caa20000-0000-4000-8000-00000000006c", + "label": "Filmvariante", + "part_ids": [ + "caa20000-0000-4000-8000-000000000068" + ], + "asset_ids": [ + "caa20000-0000-4000-8000-00000000012c" + ] + } + ] + }, + "rights": [ + { + "id": "caa20000-0000-4000-8000-000000000191", + "evidence_ref": "test-textrechte", + "actions": [ + "store", + "render", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + }, + { + "id": "caa20000-0000-4000-8000-000000000192", + "evidence_ref": "test-filmrechte", + "actions": [ + "store", + "stream", + "course_display", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + } + ] + }, + "synthetic_asset_base64_by_id": { + "caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo=" + } + }, + "eigener_bestand": { + "channel": "lara_felix", + "manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744", + "manifest": { + "schema_version": 1, + "resource_type": "exercise", + "release_id": "caa20000-0000-4000-8000-0000000000ca", + "source_id": "caa20000-0000-4000-8000-00000000000b", + "revision": 1, + "publisher_id": "caa20000-0000-4000-8000-00000000177b", + "published_at": "2026-11-23T09:02:00Z", + "exercise": { + "title": "Aufmerksam im Raum ankommen", + "audience": "Kursleitungen", + "rights_id": "caa20000-0000-4000-8000-000000000191", + "parts": [ + { + "id": "caa20000-0000-4000-8000-00000000006f", + "role": "goal", + "text": "Die Gruppe nimmt freie Wege im Raum wahr.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000070", + "role": "instructions", + "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000071", + "role": "trainer_notes", + "text": "Vorab genug Platz vorsehen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + } + ], + "assets": [], + "common_part_ids": [ + "caa20000-0000-4000-8000-00000000006f", + "caa20000-0000-4000-8000-000000000071" + ], + "common_asset_ids": [], + "variants": [ + { + "id": "caa20000-0000-4000-8000-000000000075", + "label": "Kartenvariante", + "part_ids": [ + "caa20000-0000-4000-8000-000000000070" + ], + "asset_ids": [] + } + ] + }, + "rights": [ + { + "id": "caa20000-0000-4000-8000-000000000191", + "evidence_ref": "test-textrechte", + "actions": [ + "store", + "render", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + } + ] + }, + "synthetic_asset_base64_by_id": {} + }, + "vereinsfassung_2": { + "channel": "lara_felix", + "manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0", + "manifest": { + "schema_version": 1, + "resource_type": "exercise", + "release_id": "caa20000-0000-4000-8000-0000000000cb", + "source_id": "caa20000-0000-4000-8000-00000000000a", + "revision": 2, + "publisher_id": "caa20000-0000-4000-8000-00000000177a", + "published_at": "2026-11-23T09:03:00Z", + "exercise": { + "title": "Raum und Wege wahrnehmen", + "audience": "Kursleitungen", + "rights_id": "caa20000-0000-4000-8000-000000000191", + "parts": [ + { + "id": "caa20000-0000-4000-8000-000000000065", + "role": "goal", + "text": "Die Gruppe nimmt freie Wege im Raum wahr.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000066", + "role": "instructions", + "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000067", + "role": "trainer_notes", + "text": "Vorab genug Platz vorsehen und die Laufwege gemeinsam prüfen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-000000000068", + "role": "instructions", + "text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + } + ], + "assets": [ + { + "id": "caa20000-0000-4000-8000-00000000012c", + "role": "demonstration", + "media_type": "video/mp4", + "size_bytes": 32, + "sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915", + "rights_id": "caa20000-0000-4000-8000-000000000192", + "label": "Demonstrationsfilm" + } + ], + "common_part_ids": [ + "caa20000-0000-4000-8000-000000000065", + "caa20000-0000-4000-8000-000000000067" + ], + "common_asset_ids": [], + "variants": [ + { + "id": "caa20000-0000-4000-8000-00000000006b", + "label": "Kartenvariante", + "part_ids": [ + "caa20000-0000-4000-8000-000000000066" + ], + "asset_ids": [] + }, + { + "id": "caa20000-0000-4000-8000-00000000006c", + "label": "Filmvariante", + "part_ids": [ + "caa20000-0000-4000-8000-000000000068" + ], + "asset_ids": [ + "caa20000-0000-4000-8000-00000000012c" + ] + } + ] + }, + "rights": [ + { + "id": "caa20000-0000-4000-8000-000000000191", + "evidence_ref": "test-textrechte", + "actions": [ + "store", + "render", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + }, + { + "id": "caa20000-0000-4000-8000-000000000192", + "evidence_ref": "test-filmrechte", + "actions": [ + "store", + "stream", + "course_display", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + } + ] + }, + "synthetic_asset_base64_by_id": { + "caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo=" + } + }, + "zweiter_verein": { + "channel": "zweiter_verein", + "manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603", + "manifest": { + "schema_version": 1, + "resource_type": "exercise", + "release_id": "caa20000-0000-4000-8000-0000000000cc", + "source_id": "caa20000-0000-4000-8000-00000000000c", + "revision": 1, + "publisher_id": "caa20000-0000-4000-8000-00000000177c", + "published_at": "2026-11-23T09:03:00Z", + "exercise": { + "title": "Gemeinsam den Raum erkunden", + "audience": "Kursleitungen", + "rights_id": "caa20000-0000-4000-8000-000000000191", + "parts": [ + { + "id": "caa20000-0000-4000-8000-000000000079", + "role": "goal", + "text": "Die Gruppe nimmt freie Wege im Raum wahr.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-00000000007a", + "role": "instructions", + "text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + }, + { + "id": "caa20000-0000-4000-8000-00000000007b", + "role": "trainer_notes", + "text": "Vorab genug Platz vorsehen.", + "rights_id": "caa20000-0000-4000-8000-000000000191" + } + ], + "assets": [], + "common_part_ids": [ + "caa20000-0000-4000-8000-000000000079", + "caa20000-0000-4000-8000-00000000007b" + ], + "common_asset_ids": [], + "variants": [ + { + "id": "caa20000-0000-4000-8000-00000000007f", + "label": "Kartenvariante", + "part_ids": [ + "caa20000-0000-4000-8000-00000000007a" + ], + "asset_ids": [] + } + ] + }, + "rights": [ + { + "id": "caa20000-0000-4000-8000-000000000191", + "evidence_ref": "test-textrechte", + "actions": [ + "store", + "render", + "grant_customer_use", + "commercial_course_use" + ], + "territories": [ + "DE" + ], + "valid_from": "2026-11-23T09:00:00Z", + "valid_until": null + } + ] + }, + "synthetic_asset_base64_by_id": {} + } + }, + "plans": { + "plan_a_mit_film": { + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "variant_id": "caa20000-0000-4000-8000-00000000006c" + }, + "plan_b_mit_karten": { + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "variant_id": "caa20000-0000-4000-8000-00000000006b" + }, + "plan_c_mit_film_neuere_fassung": { + "release_id": "caa20000-0000-4000-8000-0000000000cb", + "variant_id": "caa20000-0000-4000-8000-00000000006c" + }, + "plan_d_eigener_bestand": { + "release_id": "caa20000-0000-4000-8000-0000000000ca", + "variant_id": "caa20000-0000-4000-8000-000000000075" + } + }, + "expected": { + "plan_binding_after_revision": { + "release_id": "caa20000-0000-4000-8000-0000000000c9", + "variant_id": "caa20000-0000-4000-8000-00000000006c" + }, + "blocked_plans_after_withdrawal": [ + "plan_a_mit_film", + "plan_c_mit_film_neuere_fassung" + ], + "available_plans_after_withdrawal": [ + "plan_b_mit_karten", + "plan_d_eigener_bestand" + ], + "lara_felix_can_retrieve_after_withdrawal": [ + "caa20000-0000-4000-8000-0000000000ca" + ], + "zweiter_verein_can_retrieve": [ + "caa20000-0000-4000-8000-0000000000cc" + ], + "course_film_allowed": true, + "film_download_allowed": false + } +} diff --git a/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md b/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md new file mode 100644 index 0000000..097e835 --- /dev/null +++ b/docs/architecture/distribution/Shinkan_Lara_Felix_Uebergabevertrag_v1.md @@ -0,0 +1,70 @@ +# Übergabevertrag für Übungsfassungen aus Shinkan · Version 1.0 + +**23.11.2026 · Spezifikationsstand für die Beauftragung auf der Testinstanz** + +Shinkan führt die importierten Übungsoriginale. Es gibt ausgewählte Fassungen pro Empfänger frei. Lara & Felix übernimmt sie als lokale Übungsfassungen und bindet sie in seine Trainingspläne und Artikel-Stände ein. Die Veröffentlichung für Kundinnen und Kunden, die Lizenzprüfung und die Auslieferung liegen bei Lara & Felix. Planeditor, Angebotsmodell und dauerhafte Pflege eigener Lara-&-Felix-Übungsoriginale können gesondert entschieden werden. Die Freigabe des Produktivbetriebs erfordert beiderseitige Abnahme und belegte Nutzungsrechte. + +## 1. Identität, Herausgabe und Fassung + +| Begriff | Bedeutung im Vertrag | +|---|---| +| Herausgeber | Verantwortet eine Freigabe aus dem eigenen oder gemeinsam gepflegten Vereinsbestand. Der Empfänger erhält eine opaque UUID und gegebenenfalls die vereinbarte öffentliche Namensnennung. | +| Empfänger und Anbindung | Ein Empfänger hat einen eigenen Lieferkanal. Eine Maschinenanbindung ist an einen Kanal gebunden, mit einem separat widerrufbaren Schlüssel. Mehrere Herausgeber können für denselben Empfänger freigeben, sofern jede Herausgeber-Empfänger-Beziehung autorisiert ist. | +| `source_id` | Stabile öffentliche Übungs-UUID in Shinkan. Sie bleibt bei redaktionellen Änderungen und einem autorisierten Wechsel des Verantwortlichen erhalten. | +| `revision` | Positive Ganzzahl je `source_id` für den eingefrorenen fachlichen Stand. Dasselbe unveränderte Quellabbild kann für mehrere Kanäle verwendet werden. Redaktionelle Änderungen an einer Arbeitsfassung verändern einen eingefrorenen Stand nicht. | +| `release_id` | UUID des unveränderlichen Lieferpakets für einen Empfänger. Ein erneuter Zuschnitt von Auswahl oder Rechten führt zu einem neuen Paket, auch wenn die Quellrevision gleich bleibt. Mehrere Pakete derselben Revision erhalten im Änderungsverlauf eine eindeutige Reihenfolge. | + +Lara & Felix ordnet `source_id` einer stabilen lokalen Übung zu und `release_id` einem lokalen übernommenen Stand. Der Schlüssel hierfür umfasst das konfigurierte Quellsystem beziehungsweise die Quellinstanz. Die Prüfsumme dient der Integritätsprüfung. Gleiche Bytes mit unterschiedlicher Freigabe können einen unterschiedlichen Nutzungsumfang haben. Technische Schlüssel, Zugangsdaten, Vereinslisten, Profile, Gruppen, interne IDs und vertrauliche Nachweise sind von der Ausgabe ausgeschlossen. Die interne Shinkan-Sichtbarkeit regelt weiterhin die Nutzung im Trainerbereich. + +## 2. Das unveränderliche Paket + +`GET /api/distribution/v1/releases/{release_id}` liefert folgende Struktur als UTF-8-JSON. Zeiten im Vertrag verwenden UTC im Format `YYYY-MM-DDTHH:mm:ssZ`. Die angegebenen Objektfelder sind erforderlich, sofern sie hier als optional oder nullfähig beschrieben werden. + +| Feld | Inhalt | +|---|---| +| `schema_version`, `resource_type` | Ganzzahl `1`, Zeichenkette `exercise`. Ein neuer fachlicher Ressourcentyp benötigt eine eigene Vereinbarung. | +| `release_id`, `source_id`, `revision`, `publisher_id`, `published_at` | Kennungen und Zeitpunkt gemäß Abschnitt 1. | +| `exercise` | `title`, optionale `summary`, optionales `audience` und `rights_id` für diese redaktionellen Angaben. Dazu `parts`, `assets`, `common_part_ids`, `common_asset_ids` und `variants`. `parts` enthält mindestens einen Eintrag für das Lernziel. Jede Variante kann nach Auflösung eine Durchführung anzeigen. | +| `parts[]` | `id` als UUID, `role`, `text` als Klartext und `rights_id`. Rollen in v1 sind `goal`, `prerequisites`, `preparation`, `instructions`, `trainer_notes`, `equipment` und `duration_note`. Trainerhinweise behalten eine eigene Rolle für die spätere Rechteprüfung in Lara & Felix. | +| `assets[]` | `id` als UUID, `role`, `media_type`, `size_bytes`, `sha256`, `rights_id` und optionales `label`. Rollen in v1 sind `demonstration`, `worksheet` und `illustration`. SHA-256 steht als 64-stellige kleingeschriebene Hex-Zeichenkette. | +| `common_part_ids`, `common_asset_ids` | Geordnete Referenzen auf die Bestandteile, die jede Variante nutzt. | +| `variants[]` | `id` als UUID, `label`, `part_ids` und `asset_ids` als geordnete zusätzliche Referenzen. Eine Übung ohne redaktionelle Alternativen erhält eine Standardvariante. Eine wiederverwendete Varianten-UUID bezeichnet dieselbe fachliche Variante über Fassungen hinweg. | +| `rights[]` | `id` als UUID, `evidence_ref` als opaque Nachweisreferenz, `actions`, `territories`, `valid_from`, `valid_until` und optional `attribution`. `territories` ist eine Liste von ISO-Ländercodes oder explizit `null` für räumlich unbeschränkt. `valid_until` ist exklusiv oder explizit `null` für unbefristet. | + +Für `actions` gelten `store`, `render`, `stream`, `download`, `print`, `course_display`, `commercial_course_use`, `adapt`, `public_preview` und `grant_customer_use`. `store` erlaubt die Übernahme durch den Empfänger, `render` die Anzeige eines Textes oder Bildes und `grant_customer_use` die Einräumung des abgedeckten Nutzungsumfangs an Endkunden. Die übrigen Aktionen begrenzen die jeweilige Nutzung. Kombinationen werden gemeinsam geprüft. Für kommerzielle Vorführung sind zum Beispiel neben `course_display` auch `commercial_course_use` und, bei gestreamtem Material, `stream` erforderlich. Lara & Felix prüft zusätzlich das eigene Rechteprofil. Auflagen außerhalb des Schemas müssen vor Veröffentlichung operationalisiert werden. [§ 31 UrhG](https://www.gesetze-im-internet.de/urhg/__31.html) + +Alle IDs innerhalb ihrer Listen sind eindeutig. Alle Referenzen müssen im selben Paket aufgehen. Jeder übermittelte Teil und jedes Medium gehört zu mindestens einer freigegebenen Variante und verweist auf einen wirksamen Rechtevermerk, der die Übernahme abdeckt. Variantenbeschriftungen sind vom Rechtevermerk der redaktionellen Angaben abgedeckt. Zum Freigabezeitpunkt muss die vorgesehene Nutzung möglich sein. Die exportierte Fassung v1 verwendet Klartext und separate Medienreferenzen. Sind Inline-Medien oder die Anordnung für das Verständnis wesentlich, prüft die Redaktion die aufbereitete Exportfassung und ihre Medien vor Freigabe. Unaufgelöste Anker, fremde URLs im Medienmanifest und nicht exportierbare Kombinationsabhängigkeiten sperren die Freigabe. + +Shinkan speichert den exakten JSON-Body und veröffentlicht seinen SHA-256 als `manifest_sha256` im Änderungsverlauf. Gehasht werden die UTF-8-Bytes des gespeicherten JSON-Bodys vor HTTP-Komprimierung. Der Empfänger hasht die empfangenen dekomprimierten Bytes vor dem Parsen. Für Medien werden die unveränderten Originalbytes geprüft. Setzt eine neue Paketfassung Teile neu zusammen, entsteht ein eigener Manifest-Hash. Der Status der Freigabe steht im Änderungsverlauf und verändert die gespeicherten Paketbytes nicht. + +## 3. Schnittstelle und Änderungsverlauf + +Die drei Lesezugriffe laufen serverseitig über TLS unter `/api/distribution/v1` mit `Authorization: Bearer `. Shinkan leitet Empfänger und Kanal aus der Anbindung ab. Eine Änderung der URL-Parameter oder der Ressourcen-UUID wechselt den Kanal nicht. + +| Zugriff | Verhalten | +|---|---| +| `GET /changes?cursor=&limit=` | Liefert `events`, `next_cursor` und `has_more`. Ohne Cursor beginnt die Wiedergabe am Anfang der für den Kanal verfügbaren v1-Historie. `limit` ist optional und auf 1–100 begrenzt, Standard 50. Ein Cursor ist opaque, kanalgebunden und bezieht sich auf die letzte gelieferte Position. | +| `GET /releases/{release_id}` | Liefert Manifestbytes für zugängliche Pakete. | +| `GET /releases/{release_id}/assets/{asset_id}` | Liefert die im Manifest festgeschriebenen Medienbytes. Der Abruf prüft zusätzlich die Verfügbarkeit und die Zugehörigkeit des Mediums zum Paket. | + +Ein Ereignis enthält `event_id`, `type`, `release_id`, `occurred_at` und bei zielgenauen Rückzügen `target_id`. `release.published` enthält zusätzlich `source_id`, `revision` und `manifest_sha256`. Rückzüge enthalten `reason_code` aus `rights`, `safety`, `privacy`, `expired` und `editorial_error`. Vertrauliche Begründungen bleiben in Shinkan. `release.retired` sperrt eine redaktionell abgelöste Fassung für neue Planbindungen. Sie kann bei weiterbestehenden Rechten für bereits veröffentlichte Stände auslieferbar bleiben. `release.withdrawn`, `variant.withdrawn` und `asset.withdrawn` sperren das bezeichnete Ziel. Eine spätere Freigabe erfolgt als neues Paket. Ein unbekannter Ereignistyp in v1 löst einen Abgleichfehler aus. Der Empfänger bestätigt die Position erst, wenn das Ereignis verarbeitet werden kann. + +Ereignisse sind je Kanal ab der letzten bestätigten Position lückenlos und in Commit-Reihenfolge abrufbar. Gleichzeitige Freigaben dürfen einen später bestätigten Cursor nicht an einer noch ungesicherten Änderung vorbeiführen. Lara & Felix verarbeitet eine Seite dauerhaft und speichert erst dann `next_cursor`. Nach einem Abbruch darf die Seite erneut bearbeitet werden. Fehlgeschlagene Downloads werden aus einer dauerhaften Importaufgabe wiederholt. So kann ein späterer Rückzug verarbeitet werden, während ein früherer Download noch aussteht. Ein Rückzug, den Lara & Felix vor dem Import erhält, wird vorgemerkt und verhindert ein verspätetes Freischalten. + +Für v1 bleibt der Änderungsverlauf seit Einführung des Kanals abrufbar, soweit die erforderlichen Nachweise rechtmäßig gespeichert werden dürfen. Die Historie enthält Kennungen, Prüfsummen, Zeiten und Grundklassen. Ein unbrauchbarer Cursor liefert `400` mit `invalid_cursor`. Wiederaufbau erfolgt durch vollständige Wiedergabe und Abgleich mit der lokalen Sperrliste. Ungültige Schlüssel liefern `401`, gültige Schlüssel ohne Abrufumfang `403`, unbekannte oder kanal­fremde Ressourcen `404`. Für zum Kanal gehörende Pakete mit Rückzug liefern Manifest und Medien `410`. Unterschreitet die Verfügbarkeit die technischen Anforderungen, sind vorübergehende Serverfehler wiederholbar. Abgerufene Daten und Antworten auf gesperrte Abrufe werden von gemeinsam genutzten HTTP-Zwischenspeichern ausgeschlossen. + +## 4. Rückzug, Übernahme und lokale Verwendung + +Beim Rückzug eines einzelnen Mediums oder einer Variante sperrt Shinkan das ursprüngliche Paket für weitere Übernahmen. Bereits übernommene lokale Daten werden anhand der gelieferten Ziel-ID bewertet. Ein bestehender Plan kann weiter ausgeliefert werden, sofern sein veröffentlichter Stand das gesperrte Ziel und alle davon abhängigen Bestandteile ausklammert, die Durchführung vollständig bleibt und die übrigen Freigaben wirksam sind. Für neue Übernahmen gibt der Herausgeber ein neues Paket ohne das gesperrte Material frei. Ein vollständiger Paketrückzug sperrt alle lokalen Verwendungen dieses Pakets. Bei einer Sperre am zentralen Quellmedium werden alle freigegebenen Pakete mit diesem Medium ermittelt und adressatengerecht gemeldet. + +Lara & Felix nimmt Pakete zunächst in einen geschützten Importbereich auf und stellt sie nach vollständiger Prüfung der Redaktion bereit. Ein eindeutiger Schlüssel aus Quellinstanz und `release_id` verhindert Duplikate. Ändert sich das Manifest unter derselben ID, wird die Übernahme als Integritätsfehler gestoppt. Der veröffentlichte Trainingsplan bindet lokale Übungsfassung, Variante und tatsächlich eingeschlossene Teile und Medien. Eine neue Shinkan-Fassung erzeugt einen Hinweis mit Verwendungsnachweis. Übernahme in einen Plan und Veröffentlichung eines neuen Artikel-Stands sind lokale Redaktionsentscheidungen. [Fassungsbindung und Rückzug in Lara & Felix](C:/dev/lara-und-felix.de/docs/architektur/06_Versionierung_und_Veroeffentlichung.md:161) + +Lara & Felix berücksichtigt Rechtefristen bei Veröffentlichung und Abruf anhand der gelieferten Gültigkeit. Shinkan setzt abgelaufene Freigaben beim Abruf durch und schreibt Rückzugseinträge. Die Aufnahme eines älteren Pakets in einen laufenden Lizenzartikel richtet sich nach der lokalen Freigabeentscheidung und dem Rechteumfang. Die Auslieferung aus Lara & Felix läuft bei einem gewöhnlichen Shinkan-Ausfall mit den dort gültigen und lokal ungesperrten Fassungen weiter. Bei einer dringenden Meldung kann der Betreiber in Lara & Felix direkt sperren. Bereits heruntergeladene Kopien werden über den dokumentierten Folgeprozess behandelt. + +Als Startwerte für die Testinstanz gelten Abruf im 60-Sekunden-Takt und ein Ziel von höchstens fünf Minuten vom bestätigten Shinkan-Rückzug bis zur lokalen Sperre bei erreichbaren Systemen. Die Zeit schließt im End-to-End-Test die tatsächlich auslaufenden oder widerrufenen Abruflinks ein. Störungen werden über Abgleichalter und Rückzugslaufzeit sichtbar. Vor dem Produktivstart legen beide Betreiber Betriebsziel, Alarmweg, Zuständigkeit und Regeln für eine länger unterbrochene Synchronisation fest. Ein optionaler Hinweis über einen Webhook kann später denselben Abgleich anstoßen. + +## 5. Referenzfall für beide Projekte + +Die Übung „Raum und Wege wahrnehmen“ hat zwei Varianten. Die Filmvariante braucht das Medium, die Kartenvariante kommt mit ihrer eigenen Anleitung aus. Plan A bindet die Filmvariante, Plan B die Kartenvariante. Eine Korrektur in Shinkan erzeugt ein neues Paket. Beide bestehenden Pläne behalten ihre Bindung. Wird das gemeinsame Filmmedium der bisherigen Fassungen zurückgezogen, endet die Ausgabe von Plan A. Plan B bleibt bei vollständig aufgelöster Kartenvariante verfügbar. Für die nächste Übernahme kann eine bereinigte Übungsfassung veröffentlicht werden. Ein zweiter Testverein veröffentlicht eine eigene Übung für seine Website und erhält ausschließlich die Freigaben seines Kanals. + +Das [maschinenlesbare Referenzpaket](./Shinkan_Lara_Felix_Referenzfall_v1.json) enthält vier Lieferpakete, sieben Ereignisse und vier Planbindungen. Die Medienbytes sind synthetisches Testmaterial für Prüfsummen und Übernahmelogik. Die Spezifikationsprobe vom 23.11.2026 prüfte die Referenzen, Hashes, Kanalzuordnung, wiederholte Ereignisverarbeitung, lokale Fassungsbindung und die Auswirkungen des Rückzugs. Beide Filmpläne waren betroffen. Der Kartenplan und der Plan aus dem eigenen Bestand blieben im Modell verfügbar. Die Probe lief mit Beispieldaten außerhalb der laufenden Anwendungen. Die technische Abnahme auf der Testinstanz steht aus. Die Fachanforderungen an den Shinkan-Teil stehen im [Shinkan-Fachkonzept v1](./Shinkan_Uebungsfreigabe_Fachkonzept_v1.md). diff --git a/docs/architecture/distribution/Shinkan_Uebungsfreigabe_Fachkonzept_v1.md b/docs/architecture/distribution/Shinkan_Uebungsfreigabe_Fachkonzept_v1.md new file mode 100644 index 0000000..a86e42b --- /dev/null +++ b/docs/architecture/distribution/Shinkan_Uebungsfreigabe_Fachkonzept_v1.md @@ -0,0 +1,58 @@ +# Shinkan-Fachkonzept für die mandantenfähige Übungsfreigabe · Version 1.0 + +**23.11.2026 · Umsetzungsauftrag für die Testinstanz** + +Implementiere in Shinkan die Freigabe eingefrorener Übungsfassungen für vereinbarte Empfänger. Der Pilot deckt einen eigenen Bestand, einen gemeinsam gepflegten Vereinsbestand und einen unabhängigen zweiten Verein mit eigener Website-Anbindung ab. Lara & Felix ist der erste produktive Anwendungsfall. Der Daten- und Schnittstellenvertrag gilt für alle Empfänger. Er steht im [Übergabevertrag v1](./Shinkan_Lara_Felix_Uebergabevertrag_v1.md). Die Freischaltung für reale Inhalte und Kunden erfolgt nach gesonderter Betriebsabnahme. + +## 1. Ausgangslage und Umfang + +Der geprüfte Repository-Stand meldet Shinkan 0.8.250. Übungen führen heute unter anderem interne Sichtbarkeit, Status, Ersteller und Vereinsbezug. Shinkan prüft Bearbeitungsrechte anhand von Ersteller, Plattformrolle und Vereinsfunktion. Medien können im Text eingebettet sein, und Kombinationsübungen können auf weitere Übungen verweisen. Die vorhandene Mediensperre erfasst unter anderem Rechtekonflikte. Diese Funktionen sind Anknüpfungspunkte für die neue externe Freigabe. [Versionsstand](C:/Dev/shinkan-jinkendo/backend/version.py:3) · [Übungsschema](C:/Dev/shinkan-jinkendo/backend/migrations/005_exercises.sql:6) · [Bearbeitungsrechte](C:/Dev/shinkan-jinkendo/backend/routers/exercises.py:551) · [Mediensperre](C:/Dev/shinkan-jinkendo/backend/media_legal_hold.py:68) + +Der Auftrag umfasst einfache Übungen, deren Varianten, Texte und freigegebene Medien, einen Freigabeablauf an der Übung, einen lesenden Distributionszugang und einen nachholbaren Rückzug. Die v1-Anbindung nutzt eine administrativ eingerichtete Integration je Empfänger. Vereins-Selbstverwaltung für die Einrichtung, Webhooks, der Export von Kombinationsübungen oder ganzen Trainingsrahmen und die Umsetzung des Lara-&-Felix-Planeditors sind eigenständige Ausbauschritte. Alle Änderungen sind additiv zur produktiven Mandanten- und Sichtbarkeitslogik zu implementieren. + +## 2. Zuständigkeiten im Pilot + +| Rolle | Aufgabe und Prüfung | +|---|---| +| Person mit privater Übung | Gibt die Übungen frei, die ihr gehören. Das ist der gewöhnliche Fall. Sie sieht vor dem Absenden, welche Texte, Varianten und Medien im Lieferpaket landen. | +| Vereinsadmin | Gibt die Vereinsübungen seines Vereins frei. Mitgliedschaft oder allgemeines Bearbeitungsrecht allein reichen nicht. | +| Superadmin | Gibt globale Übungen frei. Das ist der seltene Fall. Der Plattformzugriff auf fremde private oder Vereinsübungen begründet keine Herausgabe. | +| Shinkan-Betrieb | Richtet im Pilot Herausgeber, Empfänger, zugelassene Beziehungen und Anbindungen ein. Er kann im Eskalationsfall sperren und Zugänge widerrufen. | +| Maschinenanbindung | Liest freigegebene Pakete ihres Empfängers mit eigenem Schlüssel. Freigeben, Bearbeiten und Wechseln des Quell- oder Empfängerkontexts bleiben menschlichen Rollen vorbehalten. | + +Die Herkunft aus eigenem oder Vereinsbestand verwendet denselben Freigabeablauf. Austritt oder Entfernen der Rolle beendet die Berechtigung zu weiteren Freigaben. Bestehende Freigaben bleiben beim verantwortlichen Herausgeber und werden anhand der belegten Rechte und Laufzeit bewertet. Für verwaiste Bestände und das Ende einer Herausgeber-Empfänger-Beziehung muss der Betrieb klären können, wer übernimmt oder welche laufenden Freigaben auslaufen beziehungsweise zurückgezogen werden. + +## 3. Redaktionsablauf + +1. **Freigabe vorbereiten.** Die berechtigte Person wählt an der Übung einen zugelassenen Empfänger. Shinkan zeigt die Übungsdaten, Varianten, zugehörigen Medien, Rechtevermerke und gegebenenfalls blockierende Abhängigkeiten in einer Vorschau. Die kanalspezifische Auswahl bleibt ein Freigabeentwurf. +2. **Rechte und Nutzbarkeit prüfen.** Für die Pilotfunktion sind einfache Übungen mit Shinkan-Status `approved` zur externen Freigabe zugelassen. Die Freigabe prüft den aktuellen Status, Befugnis, Herausgeber-Empfänger-Zuordnung, Rechteumfang, zeitliche Gültigkeit, Medienzustand und alle ausgewählten Abhängigkeiten. Material mit unbekanntem oder gesperrtem Status erfordert Klärung oder eine fachlich vollständige alternative Zusammenstellung. Die Vorschau muss für Klartext und Medienzuordnung vollständig sein. [Medienrechte](C:/Dev/shinkan-jinkendo/backend/media_rights.py:21) · [Inline-Medien](C:/Dev/shinkan-jinkendo/backend/exercise_rich_text.py:167) +3. **Verbindlich freigeben.** Shinkan zeigt Empfänger, Titel, Varianten, Medien und Nutzungsumfang zur Bestätigung. Haben sich fachlicher Stand, Rechte oder Medien seit der Vorschau geändert, ist die Vorschau vor einer Bestätigung neu zu erstellen. Freigabe erzeugt ein unveränderliches Paket und einen Eintrag im Änderungsverlauf. Der Vorgang protokolliert verantwortliche Person, Zeitpunkt und private Nachweisreferenz. Wiederholen derselben Bestätigung erzeugt kein zweites Paket. Ein ausdrücklich neuer Empfängerzuschnitt darf eine neue Freigabe erzeugen. +4. **Überarbeiten und zurückziehen.** Die Übung zeigt, welche Fassungen für welche Empfänger freigegeben sind. Eine Änderung am Original bleibt normale Redaktion. Eine neue Freigabe kann die bisherige für neue Pläne ablösen. Ein Rückzug kann ein gesamtes Paket, eine Variante oder ein Medium betreffen. Die Redaktion sieht vor der Bestätigung die betroffenen Pakete und Empfänger und erfasst eine Grundklasse. Ein bestätigter akuter Rückzug blockiert den Quellabruf und ist über den Änderungsverlauf nachholbar. + +Der Freigabe-Check muss für Texte, Filme, Bilder und PDFs nachvollziehbar sein. Die Rechte an Training, Kursvorführung, kommerzieller Nutzung, Kopien und Bearbeitung folgen den belegten Vereinbarungen. Eine bestätigte Upload-Erklärung oder die Shinkan-Sichtbarkeit allein trägt die externe Veröffentlichung nicht. Bei erkennbaren Personen sind Rechtsgrundlage, Zweck, erforderliche Nachweise und Löschprozess zu klären. Vertrauliche Belege werden in Shinkan zugriffsbeschränkt gehalten. [§ 31 UrhG](https://www.gesetze-im-internet.de/urhg/__31.html) · [DSGVO, insbesondere Art. 5, 7, 17 und 19](https://eur-lex.europa.eu/legal-content/DE/TXT/?uri=CELEX%3A32016R0679) + +## 4. Anforderungen an Daten und Betrieb + +- **Unveränderliche Medien und nachvollziehbare Quelle.** Speichere oder referenziere persistente Medienobjekte mit überprüften Bytes und Hash. Eine Änderung oder Löschung am Arbeitsmaterial darf freigegebene Bytes nicht unbemerkt ändern. Erhalte stabile Übungs- und Variantenkennungen. Halte getrennt, welche Quellrevision eingefroren wurde und wie das Paket für den Empfänger zugeschnitten ist. +- **Vollständige Freigabe.** Stelle die Medien vor der abschließenden Datenbankfreigabe bereit. Prüfe unmittelbar vor dem Commit Quellstatus, Rechte und Sperren. Paket, auditierbare Entscheidung und Ereignis werden gemeinsam sichtbar. Ein abgebrochener Vorgang hinterlässt keine abrufbare Teilfreigabe. Verwende für Freigabe und Sperre eine gemeinsame Synchronisationsgrenze pro betroffenem Objekt. Sichere die Commit-Reihenfolge des kanalgebundenen Änderungsverlaufs. +- **Zugriff je Anbindung.** Schlüssel werden einmal angezeigt, serverseitig als nicht rückrechenbarer Prüfwert gespeichert und außerhalb von Logs, URLs und Browser-Auslieferung gehalten. Ziehe bestehenden Infrastruktur- und Schlüssellebenszyklus heran. Richte Ablauf, Widerruf, Rotation mit kontrollierter Übergangszeit und angemessene Abrufbegrenzung pro Anbindung ein. Prüfe Kanal und Ressource bei jedem Abruf von Liste, Manifest und Medium. Deaktiviere gemeinsam genutzte Caches für die Distributionspfade. Der Zugriff alter Schlüssel endet zum vorgesehenen Zeitpunkt, auch bei laufenden Abrufen in den vereinbarten Zeitgrenzen. +- **Quellsperre und Verwendungen.** Halte fest, welche Pakete das jeweilige Quellmedium enthalten. Eine zentrale Mediensperre verhindert weiteren Abruf und erzeugt für alle betroffenen Kanäle und Pakete dauerhafte Rückzugsinformationen. Für einen Rückzug durch Datenbereinigung oder Löschung bleibt ein minimaler, rechtmäßig aufbewahrbarer Nachweis über Paket-ID, Zeitpunkt und Grundklasse nutzbar. Überprüfe Übungs-, Varianten- und Medienlöschung sowie Aufbewahrung und Löschung personenbezogener Inhalte bei aktiven Freigaben. Eine Löschkaskade darf laufende Veröffentlichungen nicht unbemerkt in einen unauflösbaren Zustand bringen. +- **Wiederanlauf.** Protokolliere Freigaben, Rückzüge, Schlüsselereignisse und blockierte Vorgänge ohne Schlüssel oder vertrauliche Nachweise im Log. Mache Rückstand bei ausstehenden Rückzügen sichtbar. Das Wiederherstellungsverfahren muss Rückzüge und Medienzustände vor erneuter Auslieferung abgleichen. Der Ausfall der neuen Distributionsfunktion darf Planung und Übungen im bestehenden Trainerbetrieb nicht blockieren. + +## 5. Umsetzung und Abnahme auf der Testinstanz + +| Fall | Beobachtbares Ergebnis | +|---|---| +| Eigener Bestand und gemeinsam gepflegter Vereinsbestand | Beide veröffentlichen über dieselbe Freigabefunktion an Lara & Felix. Herkunft, befugte Person, Paket und Nutzungsumfang sind nachvollziehbar. | +| Unabhängiger zweiter Verein | Der Verein veröffentlicht eine eigene Übung für seine Website. Beide Anbindungen rufen nur ihren Kanal ab. Für Paket, Medien und Änderungsverlauf ist dies durch positive und negative Mandantentests belegt. Empfänger und Zugangsdaten stammen aus Konfiguration und Verwaltung. | +| Rollen und Status | Bearbeitung, interne Sichtbarkeit und externe Freigabebefugnis werden getrennt entschieden. Fehlende Rolle, ausgetretener Vereinsnutzer, falscher Empfänger, fehlender Nachweis, unzulässige Medien und gesperrter Übungsstand führen zu verständlichen Ablehnungen. | +| Stabilität und Integrität | Die publizierte Fassung bleibt bei späterer Bearbeitung bytegleich. Bei Wiederholung, Abbruch oder paralleler Änderung entstehen weder doppelte Bestätigungen noch halbe Pakete. Der Hash für Manifest und Medien stimmt mit dem Abruf überein. | +| Abruf und Schlüssel | Schlüsselwechsel, Ablauf und Widerruf wirken pro Anbindung. Ein neu autorisierter Schlüssel für denselben Kanal kann den bestehenden Änderungsverlauf weiter abrufen. Der Trainer-Login arbeitet nach den bisherigen Regeln. | +| Rückzug und Wiederanlauf | Publizieren und Sperren können sich bei Parallelität nicht gegenseitig übergehen. Ein Medienrückzug erreicht jede betroffene Fassung und jeden berechtigten Kanal. Mehrseitiger Abruf mit Absturz, Wiederholung und Wiederherstellung verliert keine Rückzugsmeldung. Gesperrte Paket- und Medienrouten lehnen den Abruf auch direkt ab. | +| Gemeinsamer Film- und Kartenfall | Eine Korrektur ergibt eine neue Fassung. Beim Filmrückzug liefern die Ereignisse genügend Informationen, damit ein Testempfänger Filmplan und Kartenplan gezielt beurteilen kann. Ein echter Lara-&-Felix-End-to-End-Test folgt vor produktiver Auslieferung. | + +Bereitstellung als additive Migration mit zunächst deaktivierter produktiver Distribution. Verwende die vorhandenen Shinkan-Standards für Migrationen, Testinstanz und Deployment. Der Agent liefert den Abgleich mit dem aktuellen Repository, die Umsetzung, Testbefehle und Ergebnisse, Beispielantworten für beide Empfänger, den Ablauf für Schlüssel und Störung sowie offene Abweichungen. Vor Freischaltung ist ein Rückfalltest vorzulegen, bei dem die Distribution pausiert, Rückzüge erhalten bleiben und der Trainerbetrieb weiterläuft. + +## 6. Freigabe für reale Inhalte + +Für die technische Umsetzung auf der Testinstanz gelten synthetische Inhalte und Testbefugnisse. Für die produktive Freigabe müssen die tatsächlichen Pilotübungen aus beiden Beständen, Rechtebelege und vertretungsberechtigten Personen feststehen. Beide Betreiber stimmen Rechteablauf, Meldeweg und Reaktionszeit bei Rückzug ab. Lara & Felix weist die Sperre bis zur tatsächlichen Ausgabe einschließlich Altständen und noch gültiger Abruflinks nach. Änderungen an bestehendem Produktivbestand und eine Freischaltung von Vereinen erfolgen auf Grundlage dieser Abnahme. diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 715cfe9..cc03314 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -59,6 +59,7 @@ const MediaWikiImportPage = lazyWithRetry(() => import('./pages/MediaWikiImportP const AdminUsersPage = lazyWithRetry(() => import('./pages/AdminUsersPage')) const AdminClubCreationRequestsPage = lazyWithRetry(() => import('./pages/AdminClubCreationRequestsPage')) const AdminRightsPage = lazyWithRetry(() => import('./pages/AdminRightsPage')) +const AdminDistributionPage = lazyWithRetry(() => import('./pages/AdminDistributionPage')) const MediaLibraryPage = lazyWithRetry(() => import('./pages/MediaLibraryPage')) const LegalPage = lazyWithRetry(() => import('./pages/LegalPage')) const AdminLegalDocumentsPage = lazyWithRetry(() => import('./pages/AdminLegalDocumentsPage')) @@ -323,6 +324,14 @@ const appRouter = createBrowserRouter([ ), }, + { + path: 'admin/distribution', + element: ( + + + + ), + }, { path: 'admin/rights', element: ( diff --git a/frontend/src/api/distribution.js b/frontend/src/api/distribution.js new file mode 100644 index 0000000..9f2f2dc --- /dev/null +++ b/frontend/src/api/distribution.js @@ -0,0 +1,78 @@ +import { request } from './client.js' + +export function getExerciseDistribution(exerciseId) { + return request(`/api/exercises/${exerciseId}/distribution`) +} + +export function createDistributionDraft(exerciseId, body) { + return request(`/api/exercises/${exerciseId}/distribution/drafts`, { + method: 'POST', + body: JSON.stringify(body), + }) +} + +export function updateDistributionDraft(exerciseId, draftId, cut) { + return request(`/api/exercises/${exerciseId}/distribution/drafts/${draftId}`, { + method: 'PUT', + body: JSON.stringify({ cut }), + }) +} + +export function confirmDistributionDraft(exerciseId, draftId) { + return request(`/api/exercises/${exerciseId}/distribution/drafts/${draftId}/confirm`, { + method: 'POST', + body: '{}', + }) +} + +export function withdrawDistributionRelease(releaseId, reasonCode) { + return request(`/api/distribution/releases/${releaseId}/withdraw`, { + method: 'POST', + body: JSON.stringify({ reason_code: reasonCode }), + }) +} + +export function retireDistributionRelease(releaseId) { + return request(`/api/distribution/releases/${releaseId}/retire`, { method: 'POST', body: '{}' }) +} + +export function createDistributionPublisher(body) { + return request('/api/distribution/admin/publishers', { method: 'POST', body: JSON.stringify(body) }) +} + +export function createDistributionRecipient(body) { + return request('/api/distribution/admin/recipients', { method: 'POST', body: JSON.stringify(body) }) +} + +export function createDistributionRelationship(body) { + return request('/api/distribution/admin/relationships', { method: 'POST', body: JSON.stringify(body) }) +} + +export function createDistributionBinding(body) { + return request('/api/distribution/admin/bindings', { method: 'POST', body: JSON.stringify(body) }) +} + +export function issueDistributionKey(bindingId, expiresAt) { + return request(`/api/distribution/admin/bindings/${bindingId}/keys`, { + method: 'POST', + body: JSON.stringify({ expires_at: expiresAt || null }), + }) +} + +export function assignDistributionReleaser(publisherId, profileId) { + return request(`/api/distribution/admin/publishers/${publisherId}/releasers`, { + method: 'POST', + body: JSON.stringify({ profile_id: profileId }), + }) +} + +export function assignDistributionExercise(publisherId, exerciseId) { + return request(`/api/distribution/admin/publishers/${publisherId}/exercises`, { + method: 'POST', + body: JSON.stringify({ exercise_id: exerciseId }), + }) +} + +export function getDistributionBacklog() { + return request('/api/distribution/admin/backlog') +} diff --git a/frontend/src/components/AdminPageNav.jsx b/frontend/src/components/AdminPageNav.jsx index 564b05b..fe47e3f 100644 --- a/frontend/src/components/AdminPageNav.jsx +++ b/frontend/src/components/AdminPageNav.jsx @@ -1,5 +1,5 @@ import { NavLink } from 'react-router-dom' -import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield } from 'lucide-react' +import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield, Share2 } from 'lucide-react' /** * Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant). @@ -18,6 +18,7 @@ export default function AdminPageNav() { { to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles }, { to: '/admin/openrouter', label: 'KI-Modell', icon: Bot }, { to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 }, + { to: '/admin/distribution', label: 'Distribution', icon: Share2 }, ] return ( diff --git a/frontend/src/components/exercises/ExerciseDistributionPanel.jsx b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx new file mode 100644 index 0000000..2743acd --- /dev/null +++ b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx @@ -0,0 +1,262 @@ +import React, { useCallback, useEffect, useState } from 'react' +import { + confirmDistributionDraft, + createDistributionDraft, + getExerciseDistribution, + retireDistributionRelease, + updateDistributionDraft, + withdrawDistributionRelease, +} from '../../api/distribution' + +const ACTIONS = [ + 'store', + 'render', + 'stream', + 'download', + 'print', + 'course_display', + 'commercial_course_use', + 'adapt', + 'public_preview', + 'grant_customer_use', +] + +const REASONS = [ + ['rights', 'Rechte'], + ['safety', 'Sicherheit'], + ['privacy', 'Privatsphäre'], + ['expired', 'Frist'], + ['editorial_error', 'Redaktionsfehler'], +] + +export default function ExerciseDistributionPanel({ exerciseId }) { + const [overview, setOverview] = useState(null) + const [error, setError] = useState('') + const [publisherId, setPublisherId] = useState('') + const [recipientId, setRecipientId] = useState('') + const [draft, setDraft] = useState(null) + const [evidence, setEvidence] = useState('nachweis') + const [actions, setActions] = useState(['store', 'render']) + const [retirePrevious, setRetirePrevious] = useState(true) + const [reason, setReason] = useState('rights') + const [busy, setBusy] = useState(false) + + const load = useCallback(async () => { + try { + const data = await getExerciseDistribution(exerciseId) + setOverview(data) + setError('') + } catch (err) { + setError(err.message || 'Distribution konnte nicht geladen werden.') + } + }, [exerciseId]) + + useEffect(() => { + load() + }, [load]) + + function toggleAction(action) { + setActions((current) => + current.includes(action) ? current.filter((item) => item !== action) : [...current, action] + ) + } + + function withRights(cut) { + const rightsId = 'rights-main' + const next = { + ...cut, + editorial_rights_id: rightsId, + rights: [ + { + id: rightsId, + evidence_ref: evidence.trim(), + actions, + territories: ['DE'], + valid_from: new Date(Date.now() - 60000).toISOString().replace(/\.\d{3}Z$/, 'Z'), + valid_until: null, + note: '', + }, + ], + parts: (cut.parts || []).map((part) => ({ ...part, rights_id: rightsId })), + assets: (cut.assets || []).map((asset) => ({ ...asset, rights_id: rightsId })), + } + return next + } + + async function prepare() { + setBusy(true) + setError('') + try { + const created = await createDistributionDraft(exerciseId, { + publisher_id: publisherId.trim(), + recipient_id: recipientId.trim(), + }) + const cut = withRights(created.cut) + const updated = await updateDistributionDraft(exerciseId, created.draft_id, cut) + setDraft(updated) + } catch (err) { + setError(err.message || 'Vorschau fehlgeschlagen.') + } finally { + setBusy(false) + } + } + + async function confirm() { + if (!draft) return + setBusy(true) + setError('') + try { + const cut = withRights(draft.cut) + await updateDistributionDraft(exerciseId, draft.draft_id, cut) + const result = await confirmDistributionDraft(exerciseId, draft.draft_id) + if (retirePrevious && overview?.releases?.length && !result.replayed) { + const previous = [...overview.releases] + .reverse() + .find((item) => item.recipient_id === recipientId.trim() && !item.fetch_blocked) + if (previous) { + await retireDistributionRelease(previous.release_id) + } + } + setDraft(null) + await load() + } catch (err) { + setError(err.message || 'Freigabe fehlgeschlagen.') + } finally { + setBusy(false) + } + } + + async function withdraw(releaseId) { + setBusy(true) + setError('') + try { + await withdrawDistributionRelease(releaseId, reason) + await load() + } catch (err) { + setError(err.message || 'Rückzug fehlgeschlagen.') + } finally { + setBusy(false) + } + } + + if (!overview) { + return
Distribution wird geladen …
+ } + + return ( +
+

Externe Freigabe

+ {!overview.enabled ? ( +

Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.

+ ) : ( + <> +

+ Private Übungen gibt die Person frei, der sie gehören. Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei. + Globale Übungen gibt nur ein Superadmin frei. +

+ {overview.release_block ?

{overview.release_block}

: null} +
+ + +
+ {overview.publishers?.length ? ( +
    + {overview.publishers.map((publisher) => ( +
  • + +
  • + ))} +
+ ) : null} +
+ Nutzungsumfang + {ACTIONS.map((action) => ( + + ))} +
+ + +
+ + +
+ {draft ? ( +
+ Vorschau + {draft.blockers?.length ? ( +
    + {draft.blockers.map((item) => ( +
  • {item}
  • + ))} +
+ ) : ( +

Keine blockierenden Punkte.

+ )} +
    + {(draft.cut?.parts || []).map((part) => ( +
  • + {part.role}: {part.text} +
  • + ))} + {(draft.cut?.assets || []).map((asset) => ( +
  • + Medium {asset.role} {asset.label || ''} +
  • + ))} +
+
+ ) : null} + + )} + {overview.releases?.length ? ( + <> +

Freigegebene Fassungen

+ +
    + {overview.releases.map((release) => ( +
  • + {release.recipient_name} · Revision {release.revision} · {release.fetch_blocked ? 'zurückgezogen' : 'abrufbar'} + {overview.enabled && !release.fetch_blocked ? ( + + ) : null} +
  • + ))} +
+ + ) : null} + {error ?

{error}

: null} +
+ ) +} diff --git a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx index caacfe6..e848b22 100644 --- a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx +++ b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx @@ -32,6 +32,7 @@ import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as Ima import UnsavedChangesPrompt from '../UnsavedChangesPrompt' import PageFormEditorChrome from '../PageFormEditorChrome' import { ExerciseFormTabBar, ExerciseFormPanel } from './ExerciseFormLayout' +import ExerciseDistributionPanel from './ExerciseDistributionPanel' import { useNavReturn } from '../../hooks/useNavReturn' import { EXERCISES_LIST_PATH, @@ -1611,6 +1612,8 @@ function ExerciseFormPageRoot() {

) : null} + {isEdit && exerciseId ? : null} +
{ + getDistributionBacklog() + .then((data) => setBacklog(data.count)) + .catch(() => setBacklog(null)) + }, []) + + async function run(action) { + setError('') + setMessage('') + setToken('') + try { + const result = await action() + setMessage(result?.id ? `Angelegt: ${result.id}` : 'Gespeichert.') + return result + } catch (err) { + setError(err.message || 'Speichern fehlgeschlagen.') + return null + } + } + + return ( +
+ +

Distribution

+

Herausgeber, Empfänger und Schlüssel richtet der Betrieb ein. Der Schlüssel wird nur einmal angezeigt.

+

Ausstehende Fristabläufe: {backlog === null ? '—' : backlog}

+ {message ?

{message}

: null} + {error ?

{error}

: null} + {token ? ( +

+ Schlüssel: {token} +

+ ) : null} + +
+

Herausgeber

+ + + {kind === 'club' ? ( + + ) : null} + +
+ +
+

Empfänger und Anbindung

+ + + + + + + + + +
+ +
+

Zuordnung

+ + + + +
+
+ ) +} diff --git a/frontend/src/utils/api.js b/frontend/src/utils/api.js index 488c48c..0db7824 100644 --- a/frontend/src/utils/api.js +++ b/frontend/src/utils/api.js @@ -5,6 +5,7 @@ */ import { request, ACTIVE_CLUB_STORAGE_KEY, requestText } from '../api/client.js' +import * as distributionApi from '../api/distribution.js' import * as exercises from '../api/exercises.js' import * as planning from '../api/planning.js' import * as skillProfiles from '../api/skillProfiles.js' @@ -13,6 +14,7 @@ export { ACTIVE_CLUB_STORAGE_KEY } export * from '../api/exercises.js' export * from '../api/planning.js' export * from '../api/skillProfiles.js' +export * from '../api/distribution.js' // ============================================================================ // Auth @@ -1320,6 +1322,8 @@ export const api = { request(`/api/content-reports/${id}`, { method: 'PATCH', body: JSON.stringify(body) }), setLegalHoldFromReport: (id, body) => request(`/api/content-reports/${id}/legal-hold`, { method: 'POST', body: JSON.stringify(body) }), + + ...distributionApi, } export default api -- 2.43.0 From 1527a430b9dba9c973f4cc098fcaf7a06be63c18 Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:07:31 +0100 Subject: [PATCH 2/8] Let each tenant create named API keys with content and visibility scope. Superadmins enable a club for the interface. Club admins and members create the keys. Exercise release lives on its own tab and picks one of those keys. Co-authored-by: Cursor --- .../working/ACCESS_LAYER_ENDPOINT_AUDIT.md | 2 +- backend/distribution_contract.py | 31 ++ backend/distribution_service.py | 437 ++++++++++++++++-- .../migrations/100_distribution_access.sql | 25 + backend/routers/distribution.py | 94 +++- backend/tests/test_distribution_contract.py | 10 + backend/version.py | 13 +- frontend/src/App.jsx | 6 +- frontend/src/api/distribution.js | 22 + frontend/src/components/AdminPageNav.jsx | 2 +- .../exercises/ExerciseDistributionPanel.jsx | 90 +--- .../exercises/ExerciseFormPageRoot.jsx | 14 +- frontend/src/pages/AccountSettingsPage.jsx | 4 + frontend/src/pages/AdminDistributionPage.jsx | 382 ++++++++------- 14 files changed, 842 insertions(+), 290 deletions(-) create mode 100644 backend/migrations/100_distribution_access.sql diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md index a58435b..197a080 100644 --- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md +++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md @@ -30,7 +30,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C. | media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung | | exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv | | distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals | -| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/admin/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` dieses Vereins; global: nur `superadmin`; Verwaltung nur `superadmin` | +| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` und freigeschalteter Verein; global: nur `superadmin`. Schlüssel legt der Mandant an. Vereinsfreischaltung nur `superadmin` | | auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT | | catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen | | skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT | diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py index cce746f..7f6cbb9 100644 --- a/backend/distribution_contract.py +++ b/backend/distribution_contract.py @@ -286,6 +286,37 @@ def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool: return denial is None +OBJECT_SCOPES = ("exercise", "training_plan", "framework", "training_module") +CONTEXT_VISIBILITIES = { + "platform": ("official", "private"), + "club": ("club", "private"), + "personal": ("private",), +} + + +def scope_denial(context_kind: str, objects: Iterable[str], visibilities: Iterable[str]) -> Optional[str]: + allowed = CONTEXT_VISIBILITIES.get(context_kind) + if allowed is None: + return "Unbekannter Schlüsselkontext." + chosen_objects = [str(item) for item in objects] + chosen_visibilities = [str(item) for item in visibilities] + if not chosen_objects: + return "Der Schlüssel braucht mindestens eine Objektart." + if any(item not in OBJECT_SCOPES for item in chosen_objects): + return "Unbekannte Objektart." + if not chosen_visibilities: + return "Der Schlüssel braucht mindestens eine Sichtbarkeit." + if any(item not in allowed for item in chosen_visibilities): + return "Diese Sichtbarkeit ist in diesem Kontext nicht erlaubt." + return None + + +def key_covers(objects: Optional[Iterable[str]], visibilities: Optional[Iterable[str]], *, resource: str, visibility: str) -> bool: + chosen_objects = list(objects) if objects else ["exercise"] + chosen_visibilities = list(visibilities) if visibilities else ["official", "club", "private"] + return resource in chosen_objects and visibility in chosen_visibilities + + def package_state(*, fetch_blocked: bool, retired: bool) -> str: if fetch_blocked: return "withdrawn" diff --git a/backend/distribution_service.py b/backend/distribution_service.py index 6c6b37a..3d719e2 100644 --- a/backend/distribution_service.py +++ b/backend/distribution_service.py @@ -10,7 +10,7 @@ from typing import Any, Optional from fastapi import HTTPException from auth import hash_pin, verify_pin -from club_tenancy import has_club_role +from club_tenancy import has_club_role, is_superadmin from db import r2d from distribution_contract import ( LEGAL_HOLD_REASON, @@ -21,7 +21,9 @@ from distribution_contract import ( cut_hash, decide_confirm, exercise_offerable, + key_covers, package_state, + scope_denial, default_cut, distribution_enabled, format_utc, @@ -405,35 +407,14 @@ def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict: ORDER BY p.name """ ) - publishers = [] - for row in _rows(cur): - item = r2d(row) - if _denial_for(cur, exercise, item, profile_id, role): - continue - publishers.append( - {"id": str(item["id"]), "name": item["name"], "kind": item["kind"], "club_id": item["club_id"]} - ) - release_block = None - if not publishers: - release_block = _denial_for( - cur, - exercise, - { - "kind": {"official": "platform", "club": "club"}.get( - (exercise.get("visibility") or "").strip().lower(), "own" - ), - "club_id": exercise.get("club_id"), - }, - profile_id, - role, - ) or "Für diesen Bestand ist noch kein Herausgeber eingerichtet." + keys, release_block = release_keys_for_exercise(cur, exercise, profile_id, role) return { "enabled": distribution_enabled(), "visibility": exercise.get("visibility"), - "may_release": release_block is None, + "may_release": release_block is None and bool(keys), "release_block": release_block, "releases": releases, - "publishers": publishers, + "keys": keys, "profile_id": profile_id, "role": role, } @@ -886,7 +867,8 @@ def resolve_bearer(cur, token: str) -> dict: prefix = token.split(".", 2)[1] cur.execute( """ - SELECT k.secret_hash, k.expires_at, k.revoked_at, b.id AS binding_id, b.status AS binding_status, + SELECT k.secret_hash, k.expires_at, k.revoked_at, k.objects, k.visibilities, + b.id AS binding_id, b.status AS binding_status, b.recipient_id, r.status AS recipient_status FROM distribution_keys k JOIN distribution_bindings b ON b.id = k.binding_id @@ -912,7 +894,13 @@ def resolve_bearer(cur, token: str) -> dict: detail={"code": "rate_limited", "message": "Abrufgrenze erreicht."}, headers={"Retry-After": "60", "Cache-Control": "private, no-store"}, ) - return {"binding_id": str(row["binding_id"]), "recipient_id": str(row["recipient_id"]), "hits": allowed} + return { + "binding_id": str(row["binding_id"]), + "recipient_id": str(row["recipient_id"]), + "hits": allowed, + "objects": list(row.get("objects") or ["exercise"]), + "visibilities": list(row.get("visibilities") or ["official", "club", "private"]), + } def touch_rate(cur, binding_id: str) -> tuple[int, bool]: @@ -948,6 +936,30 @@ def touch_rate(cur, binding_id: str) -> tuple[int, bool]: return hits, blocked +def assert_exercise_object(objects) -> None: + if "exercise" not in list(objects or ["exercise"]): + raise HTTPException( + status_code=403, + detail={"code": "scope", "message": "Dieser Schlüssel darf Übungen nicht abrufen."}, + ) + + +def _source_visibility(cur, source_id: str) -> Optional[str]: + cur.execute("SELECT visibility FROM exercises WHERE public_id = %s", (str(source_id),)) + row = _one(cur) + if not row: + return None + return (row.get("visibility") or "private").strip().lower() + + +def assert_visibility_scope(visibilities, visibility: Optional[str]) -> None: + if visibility is None: + return + allowed = list(visibilities) if visibilities else ["official", "club", "private"] + if visibility not in allowed: + 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: cur.execute( """ @@ -980,7 +992,7 @@ def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> dict: } -def load_availability(cur, recipient_id: str, source_id: str) -> dict: +def load_availability(cur, recipient_id: str, source_id: str, visibilities=None) -> dict: import json import uuid @@ -1003,7 +1015,7 @@ def load_availability(cur, recipient_id: str, source_id: str) -> dict: status_code=404, detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."}, ) - cur.execute("SELECT status FROM exercises WHERE public_id = %s", (str(source_id),)) + cur.execute("SELECT status, visibility FROM exercises WHERE public_id = %s", (str(source_id),)) source = _one(cur) releases = [] for row in rows: @@ -1044,18 +1056,23 @@ def load_availability(cur, recipient_id: str, source_id: str) -> dict: source.get("status") if source else 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() + ) return { "source_id": str(source_id), "source_status": status, - "offerable": offerable, + "in_scope": in_scope, + "offerable": bool(offerable and in_scope), "releases": releases, } -def load_manifest(cur, recipient_id: str, release_id: str) -> bytes: +def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None) -> bytes: cur.execute( """ - SELECT release_id, recipient_id, publisher_id, fetch_blocked, manifest_text + SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text FROM distribution_releases WHERE release_id = %s """, (str(release_id),), @@ -1063,16 +1080,17 @@ def load_manifest(cur, recipient_id: str, release_id: str) -> bytes: 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"]))) 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) -> tuple[Path, str]: +def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilities=None) -> tuple[Path, str]: cur.execute( """ - SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, + SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, r.source_id, a.storage_path, a.media_type, a.sha256 FROM distribution_releases r JOIN distribution_release_assets a ON a.release_id = r.release_id @@ -1083,6 +1101,7 @@ def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[ 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"]))) enforce_expiry(cur, row) if row.get("fetch_blocked"): raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."}) @@ -1091,3 +1110,353 @@ def load_asset(cur, recipient_id: str, release_id: str, asset_id: str) -> tuple[ if digest != row["sha256"]: raise HTTPException(status_code=500, detail={"code": "integrity", "message": "Medienprüfsumme stimmt nicht."}) return path, row["media_type"] + + +def _pg_text_array(values: list[str]) -> str: + return "{" + ",".join(values) + "}" + + +def _api_enabled(cur, club_id: int) -> bool: + cur.execute("SELECT distribution_api_enabled FROM clubs WHERE id = %s", (int(club_id),)) + row = _one(cur) + return bool(row and row.get("distribution_api_enabled")) + + +def _club_ids_with_role(cur, profile_id: int, role_code: Optional[str]) -> set[int]: + if role_code: + cur.execute( + """ + SELECT cm.club_id + FROM club_members cm + JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = %s + WHERE cm.profile_id = %s AND cm.status = 'active' + """, + (role_code, int(profile_id)), + ) + else: + cur.execute( + """ + SELECT club_id FROM club_members + WHERE profile_id = %s AND status = 'active' + """, + (int(profile_id),), + ) + return {int(r2d(row)["club_id"]) for row in _rows(cur)} + + +def _ensure_publisher(cur, kind: str, club_id: Optional[int], name: str) -> str: + if kind == "platform": + cur.execute( + "SELECT id FROM distribution_publishers WHERE kind = 'platform' AND status = 'active' LIMIT 1" + ) + elif kind == "club": + cur.execute( + """ + SELECT id FROM distribution_publishers + WHERE kind = 'club' AND club_id = %s AND status = 'active' LIMIT 1 + """, + (int(club_id),), + ) + else: + cur.execute( + "SELECT id FROM distribution_publishers WHERE kind = 'own' AND status = 'active' ORDER BY created_at LIMIT 1" + ) + row = _one(cur) + if row: + return str(row["id"]) + cur.execute( + """ + INSERT INTO distribution_publishers (name, kind, club_id) + VALUES (%s, %s, %s) + RETURNING id + """, + (name, kind, int(club_id) if kind == "club" else None), + ) + return str(_one(cur)["id"]) + + +def _ensure_relationship(cur, publisher_id: str, recipient_id: str) -> None: + cur.execute( + """ + INSERT INTO distribution_relationships (publisher_id, recipient_id) + VALUES (%s, %s) + ON CONFLICT (publisher_id, recipient_id) DO UPDATE SET status = 'active' + """, + (str(publisher_id), str(recipient_id)), + ) + + +def _key_visible(item: dict, profile_id: int, role: str, admin_ids: set[int]) -> bool: + kind = item.get("context_kind") + if kind == "platform": + return is_superadmin(role) + if kind == "personal": + return int(item.get("context_profile_id") or 0) == int(profile_id) + if kind == "club": + return int(item.get("context_club_id") or 0) in admin_ids + return False + + +def access_home(cur, profile_id: int, role: str) -> dict: + admin_ids = _club_ids_with_role(cur, profile_id, "club_admin") + if is_superadmin(role): + cur.execute( + """ + SELECT id, name, distribution_api_enabled + FROM clubs + WHERE status = 'active' + ORDER BY name + """ + ) + else: + if not admin_ids: + cur.execute("SELECT id, name, distribution_api_enabled FROM clubs WHERE false") + else: + ids = list(admin_ids) + placeholders = ", ".join(["%s"] * len(ids)) + cur.execute( + f""" + SELECT id, name, distribution_api_enabled + FROM clubs + WHERE status = 'active' AND id IN ({placeholders}) + ORDER BY name + """, + tuple(ids), + ) + clubs = [] + for row in _rows(cur): + item = r2d(row) + clubs.append( + { + "id": int(item["id"]), + "name": item["name"], + "api_enabled": bool(item.get("distribution_api_enabled")), + "is_club_admin": int(item["id"]) in admin_ids, + } + ) + 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 + FROM distribution_keys k + LEFT JOIN clubs c ON c.id = k.context_club_id + WHERE k.revoked_at IS NULL + ORDER BY k.created_at DESC + """ + ) + keys = [] + for row in _rows(cur): + item = r2d(row) + if not _key_visible(item, profile_id, role, admin_ids): + continue + created = item.get("created_at") + keys.append( + { + "id": str(item["id"]), + "label": item.get("label") or item.get("key_prefix"), + "prefix": item.get("key_prefix"), + "objects": list(item.get("objects") or []), + "visibilities": list(item.get("visibilities") or []), + "context_kind": item.get("context_kind"), + "club_id": item.get("context_club_id"), + "club_name": item.get("club_name"), + "created_at": format_utc(created) if created and not isinstance(created, str) else created, + } + ) + return {"is_superadmin": is_superadmin(role), "clubs": clubs, "keys": keys} + + +def set_club_api(cur, club_id: int, enabled: bool, role: str) -> dict: + if not is_superadmin(role): + raise HTTPException(status_code=403, detail="Nur ein Superadmin gibt die Schnittstelle für einen Verein frei.") + cur.execute( + "UPDATE clubs SET distribution_api_enabled = %s WHERE id = %s RETURNING id", + (bool(enabled), int(club_id)), + ) + if _one(cur) is None: + raise HTTPException(status_code=404, detail="Verein nicht gefunden") + return {"club_id": int(club_id), "api_enabled": bool(enabled)} + + +def create_named_key( + cur, + *, + name: str, + objects: list[str], + visibilities: list[str], + context_kind: str, + club_id: Optional[int], + profile_id: int, + role: str, +) -> 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": + 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) + 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): + raise HTTPException(status_code=403, detail="Die API-Schnittstelle ist für diesen Verein nicht freigegeben.") + elif context_kind == "personal": + owner_profile = int(profile_id) + else: + raise HTTPException(status_code=400, detail="Unbekannter Schlüsselkontext.") + + label = name.strip() + cur.execute("INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id", (label,)) + recipient_id = str(_one(cur)["id"]) + cur.execute( + "INSERT INTO distribution_bindings (recipient_id, name) VALUES (%s, %s) RETURNING id", + (recipient_id, label), + ) + 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 "private" in visibilities: + _ensure_relationship(cur, _ensure_publisher(cur, "own", None, "Eigener Bestand"), recipient_id) + + import secrets + + prefix = secrets.token_hex(6) + token = f"shk.{prefix}.{secrets.token_urlsafe(32)}" + cur.execute( + """ + 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) + """, + ( + new_id(), + binding_id, + prefix, + hash_pin(token), + label, + _pg_text_array(objects), + _pg_text_array(visibilities), + context_kind, + stored_club, + owner_profile, + ), + ) + return {"token": token, "prefix": prefix, "label": label} + + +def revoke_named_key(cur, key_id: str, profile_id: int, role: str) -> dict: + cur.execute( + """ + SELECT id, context_kind, context_club_id, context_profile_id + FROM distribution_keys WHERE id = %s AND revoked_at IS NULL + """, + (str(key_id),), + ) + item = _one(cur) + if not item: + raise HTTPException(status_code=404, detail="Schlüssel nicht gefunden") + admin_ids = _club_ids_with_role(cur, profile_id, "club_admin") + if not _key_visible(item, profile_id, role, admin_ids): + raise HTTPException(status_code=403, detail="Keine Befugnis für diesen Schlüssel.") + cur.execute("UPDATE distribution_keys SET revoked_at = NOW() WHERE id = %s", (str(key_id),)) + return {"ok": True} + + +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 vis == "official": + return kind == "platform" and is_superadmin(role) + if vis == "club": + return kind == "club" and club_id is not None and int(club_id) == int(exercise.get("club_id") or 0) and int(club_id) in admin_ids + if kind == "personal": + return int(item.get("context_profile_id") or 0) == int(profile_id) + if kind == "club": + return club_id is not None and int(club_id) in member_ids and _api_enabled_cached(item) + if kind == "platform": + return is_superadmin(role) + return False + + +def _api_enabled_cached(item: dict) -> bool: + return bool(item.get("api_enabled")) + + +def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) -> tuple[list[dict], Optional[str]]: + vis = (exercise.get("visibility") or "private").strip().lower() + kind = {"official": "platform", "club": "club"}.get(vis, "own") + denial = _denial_for( + cur, + exercise, + {"kind": kind, "club_id": exercise.get("club_id")}, + profile_id, + role, + ) + if denial: + return [], denial + if vis == "club" and exercise.get("club_id") is not None and not _api_enabled(cur, int(exercise["club_id"])): + 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, + b.recipient_id, c.distribution_api_enabled AS api_enabled + FROM distribution_keys k + JOIN distribution_bindings b ON b.id = k.binding_id + LEFT JOIN clubs c ON c.id = k.context_club_id + WHERE k.revoked_at IS NULL + AND %s = ANY(k.visibilities) + AND 'exercise' = ANY(k.objects) + ORDER BY k.label + """, + (vis,), + ) + admin_ids = _club_ids_with_role(cur, profile_id, "club_admin") + member_ids = _club_ids_with_role(cur, profile_id, None) + keys = [] + for row in _rows(cur): + item = r2d(row) + if not _key_matches_exercise(item, exercise, profile_id, role, admin_ids, member_ids): + continue + keys.append( + { + "id": str(item["id"]), + "label": item.get("label") or "Schlüssel", + "context_kind": item.get("context_kind"), + "recipient_id": str(item["recipient_id"]), + } + ) + if not keys: + return [], "Für diese Übung gibt es noch keinen passenden API-Schlüssel." + return keys, None + + +def target_for_key(cur, exercise_id: int, key_id: str, profile_id: int, role: str) -> tuple[str, str]: + exercise = _load_exercise(cur, exercise_id) + keys, block = release_keys_for_exercise(cur, exercise, profile_id, role) + match = next((item for item in keys if item["id"] == str(key_id)), None) + if not match: + raise HTTPException(status_code=403, detail=block or "Dieser Schlüssel darf diese Übung nicht empfangen.") + vis = (exercise.get("visibility") or "private").strip().lower() + if vis == "official": + publisher_id = _ensure_publisher(cur, "platform", None, "Plattform") + elif vis == "club": + cur.execute("SELECT name FROM clubs WHERE id = %s", (int(exercise["club_id"]),)) + club = _one(cur) or {} + publisher_id = _ensure_publisher(cur, "club", int(exercise["club_id"]), club.get("name") or "Verein") + else: + publisher_id = _ensure_publisher(cur, "own", None, "Eigener Bestand") + _ensure_relationship(cur, publisher_id, match["recipient_id"]) + return publisher_id, match["recipient_id"] diff --git a/backend/migrations/100_distribution_access.sql b/backend/migrations/100_distribution_access.sql new file mode 100644 index 0000000..107ae5c --- /dev/null +++ b/backend/migrations/100_distribution_access.sql @@ -0,0 +1,25 @@ +-- API-Schnittstelle je Verein und benannte Schlüssel mit Objekt- und Sichtbarkeitsrechten. +-- Bestehende Schlüssel behalten den Abruf von Übungen über alle Sichtbarkeiten, damit die Testschlüssel weiter gelten. + +ALTER TABLE clubs + ADD COLUMN IF NOT EXISTS distribution_api_enabled BOOLEAN NOT NULL DEFAULT false; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS label TEXT; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS objects TEXT[] NOT NULL DEFAULT ARRAY['exercise']::text[]; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS visibilities TEXT[] NOT NULL DEFAULT ARRAY['official', 'club', 'private']::text[]; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS context_kind TEXT NOT NULL DEFAULT 'platform'; + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS context_club_id INT REFERENCES clubs (id); + +ALTER TABLE distribution_keys + ADD COLUMN IF NOT EXISTS context_profile_id INT REFERENCES profiles (id); + +UPDATE distribution_keys SET label = key_prefix WHERE label IS NULL OR btrim(label) = ''; diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py index 2dc97fc..2ab4103 100644 --- a/backend/routers/distribution.py +++ b/backend/routers/distribution.py @@ -21,9 +21,12 @@ from distribution_contract import ( distribution_enabled, ) from distribution_service import ( + access_home, + assert_exercise_object, backlog_count, confirm_draft, create_draft, + create_named_key, issue_key, list_changes, load_asset, @@ -32,6 +35,9 @@ from distribution_service import ( overview, resolve_bearer, retire_release, + revoke_named_key, + set_club_api, + target_for_key, update_draft, withdraw_release, ) @@ -110,11 +116,24 @@ class SuspendBody(BaseModel): class DraftBody(BaseModel): - publisher_id: str - recipient_id: str + publisher_id: Optional[str] = None + recipient_id: Optional[str] = None + key_id: Optional[str] = None cut: Optional[dict] = None +class AccessKeyBody(BaseModel): + name: str = Field(min_length=1, max_length=200) + objects: list[str] + visibilities: list[str] + context_kind: str + club_id: Optional[int] = None + + +class ClubApiBody(BaseModel): + enabled: bool + + class CutBody(BaseModel): cut: dict @@ -142,6 +161,11 @@ def get_changes( detail={"code": "invalid_cursor", "message": "Cursor ungültig."}, headers=NO_STORE, ) + try: + assert_exercise_object(binding.get("objects")) + except HTTPException as exc: + exc.headers = {**(exc.headers or {}), **NO_STORE} + raise exc with get_db() as conn: cur = get_cursor(conn) payload = list_changes(cur, binding["recipient_id"], seq, limit) @@ -160,7 +184,8 @@ def get_availability(source_id: str, authorization: Optional[str] = Header(defau with get_db() as conn: cur = get_cursor(conn) try: - payload = load_availability(cur, binding["recipient_id"], source_id) + assert_exercise_object(binding.get("objects")) + payload = load_availability(cur, binding["recipient_id"], source_id, binding.get("visibilities")) except HTTPException as exc: held = exc if held is not None: @@ -181,7 +206,8 @@ def get_release(release_id: str, authorization: Optional[str] = Header(default=N with get_db() as conn: cur = get_cursor(conn) try: - body = load_manifest(cur, binding["recipient_id"], release_id) + assert_exercise_object(binding.get("objects")) + body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities")) except HTTPException as exc: held = exc if held is not None: @@ -199,7 +225,10 @@ def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Hea with get_db() as conn: cur = get_cursor(conn) try: - path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id) + assert_exercise_object(binding.get("objects")) + path, media_type = load_asset( + cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities") + ) except HTTPException as exc: held = exc if held is not None: @@ -222,11 +251,19 @@ def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depend from routers.exercises import _assert_can_edit_exercise _assert_can_edit_exercise(cur, exercise_id, tenant) + if body.key_id: + publisher_id, recipient_id = target_for_key( + cur, exercise_id, body.key_id, tenant.profile_id, tenant.global_role or "" + ) + elif body.publisher_id and body.recipient_id: + publisher_id, recipient_id = body.publisher_id, body.recipient_id + else: + raise HTTPException(status_code=400, detail="Wähle einen API-Schlüssel.") result = create_draft( cur, exercise_id, - body.publisher_id, - body.recipient_id, + publisher_id, + recipient_id, tenant.profile_id, tenant.global_role or "", body.cut, @@ -458,3 +495,46 @@ def get_backlog(tenant: TenantContext = Depends(get_tenant_context)): with get_db() as conn: cur = get_cursor(conn) return {"count": backlog_count(cur)} + + +@editorial.get("/api/distribution/access") +def get_access(tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + return access_home(cur, tenant.profile_id, tenant.global_role or "") + + +@editorial.put("/api/distribution/access/clubs/{club_id}") +def put_club_api(club_id: int, body: ClubApiBody, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = set_club_api(cur, club_id, body.enabled, tenant.global_role or "") + conn.commit() + return result + + +@editorial.post("/api/distribution/access/keys") +def post_access_key(body: AccessKeyBody, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = create_named_key( + cur, + name=body.name, + objects=body.objects, + visibilities=body.visibilities, + context_kind=body.context_kind, + club_id=body.club_id, + profile_id=tenant.profile_id, + role=tenant.global_role or "", + ) + conn.commit() + return result + + +@editorial.post("/api/distribution/access/keys/{key_id}/revoke") +def post_revoke_named(key_id: str, tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + result = revoke_named_key(cur, key_id, tenant.profile_id, tenant.global_role or "") + conn.commit() + return result diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py index a71cb96..446adce 100644 --- a/backend/tests/test_distribution_contract.py +++ b/backend/tests/test_distribution_contract.py @@ -24,6 +24,7 @@ from distribution_contract import ( encode_cursor, exercise_offerable, package_state, + scope_denial, manifest_bytes, official_write_allowed, plan_available, @@ -100,6 +101,15 @@ def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> Non assert [kind for kind, _ in events] == ["published", "published"] +def test_key_scope_follows_the_role_context() -> 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 + assert scope_denial("club", ["exercise"], ["official"]) + assert scope_denial("platform", ["training_plan"], ["official", "private"]) is None + assert scope_denial("platform", [], ["official"]) + + def test_availability_keeps_the_copy_and_stops_new_offers() -> None: assert package_state(fetch_blocked=False, retired=False) == "available" assert package_state(fetch_blocked=False, retired=True) == "retired" diff --git a/backend/version.py b/backend/version.py index 3bb3871..473f306 100644 --- a/backend/version.py +++ b/backend/version.py @@ -1,8 +1,8 @@ # Shinkan Jinkendo Version Information -APP_VERSION = "0.8.252" +APP_VERSION = "0.8.253" BUILD_DATE = "2026-11-23" -DB_SCHEMA_VERSION = "20261123099" +DB_SCHEMA_VERSION = "20261123100" 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.1.0", # Freigabe folgt der Übung: Besitzer, Vereinsadmin, Superadmin für global + "distribution": "1.2.0", # API-Schlüssel je Mandant: Name, Objekte, Sichtbarkeit; Verein schaltet der Superadmin frei "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.253", + "date": "2026-11-23", + "changes": [ + "Die API-Schnittstelle zeigt dem Superadmin die Freigabe je Verein. Vereinsadmins und Nutzer legen selbst Schlüssel mit Namen, Inhaltsarten und Sichtbarkeit an. Die Übungsfreigabe liegt in der Registerkarte Freigabe und wählt einen solchen Schlüssel.", + ], + }, { "version": "0.8.252", "date": "2026-11-23", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index cc03314..859f85d 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -326,11 +326,7 @@ const appRouter = createBrowserRouter([ }, { path: 'admin/distribution', - element: ( - - - - ), + element: , }, { path: 'admin/rights', diff --git a/frontend/src/api/distribution.js b/frontend/src/api/distribution.js index 9f2f2dc..f076f55 100644 --- a/frontend/src/api/distribution.js +++ b/frontend/src/api/distribution.js @@ -76,3 +76,25 @@ export function assignDistributionExercise(publisherId, exerciseId) { export function getDistributionBacklog() { return request('/api/distribution/admin/backlog') } + +export function getDistributionAccess() { + return request('/api/distribution/access') +} + +export function setClubDistributionApi(clubId, enabled) { + return request(`/api/distribution/access/clubs/${clubId}`, { + method: 'PUT', + body: JSON.stringify({ enabled }), + }) +} + +export function createDistributionAccessKey(body) { + return request('/api/distribution/access/keys', { + method: 'POST', + body: JSON.stringify(body), + }) +} + +export function revokeDistributionAccessKey(keyId) { + return request(`/api/distribution/access/keys/${keyId}/revoke`, { method: 'POST', body: '{}' }) +} diff --git a/frontend/src/components/AdminPageNav.jsx b/frontend/src/components/AdminPageNav.jsx index fe47e3f..004bcd5 100644 --- a/frontend/src/components/AdminPageNav.jsx +++ b/frontend/src/components/AdminPageNav.jsx @@ -18,7 +18,7 @@ export default function AdminPageNav() { { to: '/admin/ai-prompts', label: 'KI Prompts', icon: Sparkles }, { to: '/admin/openrouter', label: 'KI-Modell', icon: Bot }, { to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 }, - { to: '/admin/distribution', label: 'Distribution', icon: Share2 }, + { to: '/admin/distribution', label: 'API-Schnittstelle', icon: Share2 }, ] return ( diff --git a/frontend/src/components/exercises/ExerciseDistributionPanel.jsx b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx index 2743acd..9a66024 100644 --- a/frontend/src/components/exercises/ExerciseDistributionPanel.jsx +++ b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx @@ -8,18 +8,7 @@ import { withdrawDistributionRelease, } from '../../api/distribution' -const ACTIONS = [ - 'store', - 'render', - 'stream', - 'download', - 'print', - 'course_display', - 'commercial_course_use', - 'adapt', - 'public_preview', - 'grant_customer_use', -] +const RELEASE_ACTIONS = ['store', 'render', 'stream', 'course_display', 'commercial_course_use'] const REASONS = [ ['rights', 'Rechte'], @@ -32,11 +21,9 @@ const REASONS = [ export default function ExerciseDistributionPanel({ exerciseId }) { const [overview, setOverview] = useState(null) const [error, setError] = useState('') - const [publisherId, setPublisherId] = useState('') - const [recipientId, setRecipientId] = useState('') + const [keyId, setKeyId] = useState('') const [draft, setDraft] = useState(null) const [evidence, setEvidence] = useState('nachweis') - const [actions, setActions] = useState(['store', 'render']) const [retirePrevious, setRetirePrevious] = useState(true) const [reason, setReason] = useState('rights') const [busy, setBusy] = useState(false) @@ -55,12 +42,6 @@ export default function ExerciseDistributionPanel({ exerciseId }) { load() }, [load]) - function toggleAction(action) { - setActions((current) => - current.includes(action) ? current.filter((item) => item !== action) : [...current, action] - ) - } - function withRights(cut) { const rightsId = 'rights-main' const next = { @@ -70,7 +51,7 @@ export default function ExerciseDistributionPanel({ exerciseId }) { { id: rightsId, evidence_ref: evidence.trim(), - actions, + actions: RELEASE_ACTIONS, territories: ['DE'], valid_from: new Date(Date.now() - 60000).toISOString().replace(/\.\d{3}Z$/, 'Z'), valid_until: null, @@ -87,10 +68,7 @@ export default function ExerciseDistributionPanel({ exerciseId }) { setBusy(true) setError('') try { - const created = await createDistributionDraft(exerciseId, { - publisher_id: publisherId.trim(), - recipient_id: recipientId.trim(), - }) + const created = await createDistributionDraft(exerciseId, { key_id: keyId }) const cut = withRights(created.cut) const updated = await updateDistributionDraft(exerciseId, created.draft_id, cut) setDraft(updated) @@ -110,9 +88,10 @@ export default function ExerciseDistributionPanel({ exerciseId }) { await updateDistributionDraft(exerciseId, draft.draft_id, cut) const result = await confirmDistributionDraft(exerciseId, draft.draft_id) if (retirePrevious && overview?.releases?.length && !result.replayed) { + const recipientId = (overview.keys || []).find((item) => item.id === keyId)?.recipient_id const previous = [...overview.releases] .reverse() - .find((item) => item.recipient_id === recipientId.trim() && !item.fetch_blocked) + .find((item) => item.recipient_id === recipientId && !item.fetch_blocked) if (previous) { await retireDistributionRelease(previous.release_id) } @@ -140,53 +119,32 @@ export default function ExerciseDistributionPanel({ exerciseId }) { } if (!overview) { - return
Distribution wird geladen …
+ return

Freigabe wird geladen …

} return ( -
-

Externe Freigabe

+
{!overview.enabled ? (

Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.

) : ( <> -

- Private Übungen gibt die Person frei, der sie gehören. Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei. - Globale Übungen gibt nur ein Superadmin frei. -

{overview.release_block ?

{overview.release_block}

: null} -
- - -
- {overview.publishers?.length ? ( -
    - {overview.publishers.map((publisher) => ( -
  • - -
  • - ))} -
- ) : null} -
- Nutzungsumfang - {ACTIONS.map((action) => ( - - ))} -
+

+ Der Empfänger darf die Fassung übernehmen und im Kurs zeigen, auch kommerziell. Herunterladen und Bearbeiten sind nicht enthalten. +

+
+
) } diff --git a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx index e848b22..285ee3c 100644 --- a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx +++ b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx @@ -28,7 +28,7 @@ import { } from '../../utils/activeClub' import { COMBINATION_ARCHETYPE_OPTIONS, ARCHETYPE_DEFAULT_REP_SERIES_COUNT, defaultRepSeriesCountForArchetype } from '../../constants/combinationArchetypes' import { readSlotProfilesV1, normalizeAdvanceMode, parseComboRepSeriesCountUi } from '../../utils/combinationMethodProfileUi' -import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon } from 'lucide-react' +import { GripVertical, FileText, BookOpen, Tags, Layers, GitBranch, Image as ImageIcon, Share2 } from 'lucide-react' import UnsavedChangesPrompt from '../UnsavedChangesPrompt' import PageFormEditorChrome from '../PageFormEditorChrome' import { ExerciseFormTabBar, ExerciseFormPanel } from './ExerciseFormLayout' @@ -668,9 +668,11 @@ function ExerciseFormPageRoot() { }) } tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon }) + tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2 }) } else { tabs.push({ id: 'varianten', label: 'Varianten', icon: GitBranch, disabled: true }) tabs.push({ id: 'medien', label: 'Medien & Mehr', icon: ImageIcon, disabled: true }) + tabs.push({ id: 'freigabe', label: 'Freigabe', icon: Share2, disabled: true }) } return tabs }, [formData.exercise_kind, isEdit, variants.length]) @@ -1612,8 +1614,6 @@ function ExerciseFormPageRoot() {

) : null} - {isEdit && exerciseId ? : null} -
)} + + + ) : null} diff --git a/frontend/src/pages/AccountSettingsPage.jsx b/frontend/src/pages/AccountSettingsPage.jsx index cb8b782..51c9c07 100644 --- a/frontend/src/pages/AccountSettingsPage.jsx +++ b/frontend/src/pages/AccountSettingsPage.jsx @@ -607,6 +607,10 @@ function AccountSettingsPage() {

+ API-Schlüssel + {' — Schnittstelle für Übungen und spätere Planungsinhalte'} +

+

Technische Systeminformationen {' — App-Version, Build, Umgebung, Datenbankschema'}

diff --git a/frontend/src/pages/AdminDistributionPage.jsx b/frontend/src/pages/AdminDistributionPage.jsx index 12adc33..db5b31e 100644 --- a/frontend/src/pages/AdminDistributionPage.jsx +++ b/frontend/src/pages/AdminDistributionPage.jsx @@ -1,194 +1,236 @@ -import React, { useEffect, useState } from 'react' +import React, { useCallback, useEffect, useState } from 'react' +import { Link } from 'react-router-dom' import AdminPageNav from '../components/AdminPageNav' +import { useAuth } from '../context/AuthContext' import { - assignDistributionExercise, - assignDistributionReleaser, - createDistributionBinding, - createDistributionPublisher, - createDistributionRecipient, - createDistributionRelationship, - getDistributionBacklog, - issueDistributionKey, + createDistributionAccessKey, + getDistributionAccess, + revokeDistributionAccessKey, + setClubDistributionApi, } from '../api/distribution' -export default function AdminDistributionPage() { - const [message, setMessage] = useState('') +const OBJECTS = [ + ['exercise', 'Übung'], + ['training_plan', 'Trainingsplan'], + ['framework', 'Rahmenprogramm'], + ['training_module', 'Trainingsmodul'], +] + +const VISIBILITY = { + official: 'Global', + club: 'Verein', + private: 'Eigene', +} + +function KeyForm({ contextKind, clubId, allowedVisibilities, onCreated }) { + const [name, setName] = useState('') + const [objects, setObjects] = useState(['exercise']) + const [visibilities, setVisibilities] = useState( + allowedVisibilities.length === 1 ? allowedVisibilities : [allowedVisibilities[0]] + ) + const [busy, setBusy] = useState(false) const [error, setError] = useState('') - const [token, setToken] = useState('') - const [backlog, setBacklog] = useState(null) - const [publisherName, setPublisherName] = useState('') - const [kind, setKind] = useState('platform') - const [clubId, setClubId] = useState('') - const [recipientName, setRecipientName] = useState('') - const [publisherId, setPublisherId] = useState('') - const [recipientId, setRecipientId] = useState('') - const [bindingName, setBindingName] = useState('Anbindung') - const [bindingId, setBindingId] = useState('') - const [profileId, setProfileId] = useState('') - const [exerciseId, setExerciseId] = useState('') - useEffect(() => { - getDistributionBacklog() - .then((data) => setBacklog(data.count)) - .catch(() => setBacklog(null)) - }, []) + function toggle(list, value, setter) { + setter(list.includes(value) ? list.filter((item) => item !== value) : [...list, value]) + } - async function run(action) { + async function submit(event) { + event.preventDefault() + setBusy(true) setError('') - setMessage('') - setToken('') try { - const result = await action() - setMessage(result?.id ? `Angelegt: ${result.id}` : 'Gespeichert.') - return result + const result = await createDistributionAccessKey({ + name: name.trim(), + objects, + visibilities, + context_kind: contextKind, + club_id: clubId || null, + }) + setName('') + onCreated(result) } catch (err) { - setError(err.message || 'Speichern fehlgeschlagen.') - return null + setError(err.message || 'Schlüssel konnte nicht angelegt werden.') + } finally { + setBusy(false) } } return ( -
- -

Distribution

-

Herausgeber, Empfänger und Schlüssel richtet der Betrieb ein. Der Schlüssel wird nur einmal angezeigt.

-

Ausstehende Fristabläufe: {backlog === null ? '—' : backlog}

- {message ?

{message}

: null} +
+ +
+ Inhalte + {OBJECTS.map(([value, label]) => ( + + ))} +
+
+ Sichtbarkeit + {allowedVisibilities.map((value) => ( + + ))} +
+ {error ?

{error}

: null} + +
+ ) +} + +function KeyList({ keys, onRevoke }) { + if (!keys.length) return

Noch kein Schlüssel.

+ return ( +
    + {keys.map((item) => ( +
  • + {item.label} + {' · '} + {item.objects.map((object) => OBJECTS.find(([value]) => value === object)?.[1] || object).join(', ')} + {' · '} + {item.visibilities.map((value) => VISIBILITY[value] || value).join(', ')} + +
  • + ))} +
+ ) +} + +export default function AdminDistributionPage() { + const { user } = useAuth() + const superadmin = user?.role === 'superadmin' + const [home, setHome] = useState(null) + const [error, setError] = useState('') + const [token, setToken] = useState('') + + const load = useCallback(async () => { + try { + setHome(await getDistributionAccess()) + setError('') + } catch (err) { + setError(err.message || 'Die API-Schnittstelle konnte nicht geladen werden.') + } + }, []) + + useEffect(() => { + load() + }, [load]) + + async function toggleClub(club, enabled) { + setError('') + try { + await setClubDistributionApi(club.id, enabled) + await load() + } catch (err) { + setError(err.message || 'Die Freigabe konnte nicht gespeichert werden.') + } + } + + async function revoke(keyId) { + setError('') + try { + await revokeDistributionAccessKey(keyId) + await load() + } catch (err) { + setError(err.message || 'Der Schlüssel konnte nicht widerrufen werden.') + } + } + + function created(result) { + setToken(result.token) + load() + } + + const keys = home?.keys || [] + const clubs = home?.clubs || [] + + return ( +
+ {superadmin ? :

Zurück zu Einstellungen

} +

API-Schnittstelle

+

+ Ein Schlüssel hat einen Namen und legt fest, welche Inhalte und welche Sichtbarkeit ein externes Programm abrufen darf. + Trainingsplan, Rahmenprogramm und Trainingsmodul können schon erlaubt werden. Ausgeliefert werden derzeit Übungen. +

{error ?

{error}

: null} {token ? (

- Schlüssel: {token} + Schlüssel, nur jetzt sichtbar: {token}

) : null} + {!home ?

Wird geladen …

: null} + + {superadmin ? ( +
+

Vereine

+

Ein Verein legt seine Schlüssel selbst an, sobald die Schnittstelle für ihn frei ist.

+
    + {clubs.map((club) => ( +
  • + +
  • + ))} +
+
+ ) : null} + + {superadmin ? ( +
+

Plattform

+

Für globale Übungen und eigene Übungen des Superadmins.

+ + item.context_kind === 'platform')} onRevoke={revoke} /> +
+ ) : null} + + {clubs.filter((club) => club.is_club_admin).map((club) => ( +
+

{club.name}

+ {club.api_enabled ? ( + <> +

Schlüssel dieses Vereins. Sichtbar sind Vereinsübungen und, wenn angekreuzt, eigene Übungen der Mitglieder.

+ + item.context_kind === 'club' && item.club_id === club.id)} onRevoke={revoke} /> + + ) : ( +

Die Schnittstelle ist für diesen Verein noch nicht freigegeben.

+ )} +
+ ))}
-

Herausgeber

- - - {kind === 'club' ? ( - - ) : null} - -
- -
-

Empfänger und Anbindung

- - - - - - - - - -
- -
-

Zuordnung

- - - - +

Eigene Übungen

+

Dieser Schlüssel gilt nur für Übungen, die dir gehören.

+ + item.context_kind === 'personal')} onRevoke={revoke} />
) -- 2.43.0 From c08c7c65b5d44968f05ac6fe5c589db4c5902246 Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:10:28 +0100 Subject: [PATCH 3/8] Close the exercise form tabs so the frontend build parses. The release tab sat beside the media tab inside one condition. The build stopped because that expression was not wrapped. Co-authored-by: Cursor --- frontend/src/components/exercises/ExerciseFormPageRoot.jsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx index 285ee3c..85a3993 100644 --- a/frontend/src/components/exercises/ExerciseFormPageRoot.jsx +++ b/frontend/src/components/exercises/ExerciseFormPageRoot.jsx @@ -2603,6 +2603,7 @@ function ExerciseFormPageRoot() { ) : null} {isEdit ? ( + <> + ) : null} -- 2.43.0 From b824115e9b774727e1702cb5e78e3809c58f7b5a Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:25:57 +0100 Subject: [PATCH 4/8] 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 ( -
    +
      {keys.map((item) => ( -
    • +
    • {item.label} - {' · '} - {item.objects.map((object) => OBJECTS.find(([value]) => value === object)?.[1] || object).join(', ')} - {' · '} - {item.visibilities.map((value) => VISIBILITY[value] || value).join(', ')} - +
+ ) : ( +

Dieser ältere Schlüssel kann nicht erneut angezeigt werden.

+ )} + @@ -122,7 +159,6 @@ export default function AdminDistributionPage() { const superadmin = user?.role === 'superadmin' const [home, setHome] = useState(null) const [error, setError] = useState('') - const [token, setToken] = useState('') const load = useCallback(async () => { try { @@ -157,11 +193,6 @@ export default function AdminDistributionPage() { } } - function created(result) { - setToken(result.token) - load() - } - const keys = home?.keys || [] const clubs = home?.clubs || [] @@ -169,31 +200,23 @@ export default function AdminDistributionPage() {
{superadmin ? :

Zurück zu Einstellungen

}

API-Schnittstelle

-

- Ein Schlüssel hat einen Namen und legt fest, welche Inhalte und welche Sichtbarkeit ein externes Programm abrufen darf. +

+ Ein Schlüssel gehört zu einer Anwendung. Du weist ihm die Bereiche zu, die diese Anwendung abrufen darf. + Fällt dir eine Rolle weg, liefert der Schlüssel diesen Bereich nicht mehr aus. Trainingsplan, Rahmenprogramm und Trainingsmodul können schon erlaubt werden. Ausgeliefert werden derzeit Übungen.

{error ?

{error}

: null} - {token ? ( -

- Schlüssel, nur jetzt sichtbar: {token} -

- ) : null} {!home ?

Wird geladen …

: null} {superadmin ? (

Vereine

-

Ein Verein legt seine Schlüssel selbst an, sobald die Schnittstelle für ihn frei ist.

+

Ein Verein kann auf Schlüssel gelegt werden, sobald die Schnittstelle für ihn frei ist.

    {clubs.map((club) => (
  • @@ -202,36 +225,13 @@ export default function AdminDistributionPage() {
) : null} - {superadmin ? ( -
-

Plattform

-

Für globale Übungen und eigene Übungen des Superadmins.

- - item.context_kind === 'platform')} onRevoke={revoke} /> + {home ? ( +
+

Schlüssel

+ load()} /> +
) : null} - - {clubs.filter((club) => club.is_club_admin).map((club) => ( -
-

{club.name}

- {club.api_enabled ? ( - <> -

Schlüssel dieses Vereins. Sichtbar sind Vereinsübungen und, wenn angekreuzt, eigene Übungen der Mitglieder.

- - item.context_kind === 'club' && item.club_id === club.id)} onRevoke={revoke} /> - - ) : ( -

Die Schnittstelle ist für diesen Verein noch nicht freigegeben.

- )} -
- ))} - -
-

Eigene Übungen

-

Dieser Schlüssel gilt nur für Übungen, die dir gehören.

- - item.context_kind === 'personal')} onRevoke={revoke} /> -
) } -- 2.43.0 From 4b33b17b2dd4f359eedbbb727ce631de93233034 Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:34:15 +0100 Subject: [PATCH 5/8] Read the API key list before the next query replaces it. The exercise release screen asked which keys match and then looked up club roles on the same cursor. The key rows were discarded, so a valid key looked missing. Co-authored-by: Cursor --- backend/distribution_service.py | 4 +- backend/tests/test_distribution_contract.py | 46 ++++++++++++++++++++- backend/version.py | 11 ++++- 3 files changed, 56 insertions(+), 5 deletions(-) diff --git a/backend/distribution_service.py b/backend/distribution_service.py index b948ed0..2e42c73 100644 --- a/backend/distribution_service.py +++ b/backend/distribution_service.py @@ -1538,6 +1538,8 @@ def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) - return [], denial if vis == "club" and exercise.get("club_id") is not None and not _api_enabled(cur, int(exercise["club_id"])): return [], "Die API-Schnittstelle ist für diesen Verein nicht freigegeben." + admin_ids = _club_ids_with_role(cur, profile_id, "club_admin") + member_ids = _club_ids_with_role(cur, profile_id, None) cur.execute( """ SELECT k.id, k.label, k.context_kind, k.context_club_id, k.context_profile_id, k.club_ids, @@ -1552,8 +1554,6 @@ def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) - """, (vis,), ) - admin_ids = _club_ids_with_role(cur, profile_id, "club_admin") - member_ids = _club_ids_with_role(cur, profile_id, None) keys = [] for row in _rows(cur): item = r2d(row) diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py index 7262d10..fb99a4a 100644 --- a/backend/tests/test_distribution_contract.py +++ b/backend/tests/test_distribution_contract.py @@ -14,7 +14,7 @@ from fastapi.testclient import TestClient os.environ.setdefault("SKIP_DB_MIGRATE", "1") from auth import require_auth -from distribution_service import _lock_recipient +from distribution_service import _lock_recipient, release_keys_for_exercise from distribution_contract import ( InvalidCursor, actions_cover, @@ -237,6 +237,50 @@ def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypa assert response.headers.get("cache-control") == "private, no-store" +class _DroppingCursor: + """Ein neues execute verwirft ein noch nicht gelesenes Ergebnis, wie psycopg2.""" + + def __init__(self, key: dict) -> None: + self._key = key + self._pending = None + + def execute(self, sql, _params=None): + if self._pending is not None: + raise AssertionError("Ergebnis wurde vor dem Lesen überschrieben") + self._pending = [self._key] if "FROM distribution_keys" in sql else [] + + def fetchall(self): + rows = self._pending + self._pending = None + return rows or [] + + def fetchone(self): + rows = self.fetchall() + return rows[0] if rows else None + + +def test_release_screen_keeps_the_application_key() -> None: + key = { + "id": "key-1", + "label": "Lara", + "context_kind": "user", + "context_club_id": None, + "context_profile_id": 7, + "club_ids": [3], + "recipient_id": "rec-1", + "api_enabled": True, + } + cur = _DroppingCursor(key) + keys, block = release_keys_for_exercise( + cur, + {"visibility": "official", "club_id": None, "created_by": 7}, + 7, + "superadmin", + ) + assert block is None + assert [item["label"] for item in keys] == ["Lara"] + + def test_channel_sequence_is_locked() -> None: assert "FOR UPDATE" in inspect.getsource(_lock_recipient) diff --git a/backend/version.py b/backend/version.py index e85fcef..32e890c 100644 --- a/backend/version.py +++ b/backend/version.py @@ -1,6 +1,6 @@ # Shinkan Jinkendo Version Information -APP_VERSION = "0.8.254" +APP_VERSION = "0.8.255" BUILD_DATE = "2026-11-23" DB_SCHEMA_VERSION = "20261123101" @@ -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.3.0", # Ein Schlüssel je Anwendung, Rechte folgen der aktuellen Rolle, Schlüssel bleibt kopierbar + "distribution": "1.3.1", # Freigabe liest den Schlüssel, bevor weitere Abfragen denselben Cursor benutzen "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.255", + "date": "2026-11-23", + "changes": [ + "Die Übungsfreigabe findet einen angelegten API-Schlüssel. Die Schlüsselabfrage wird gelesen, bevor die Rollenabfrage denselben Cursor überschreibt.", + ], + }, { "version": "0.8.254", "date": "2026-11-23", -- 2.43.0 From 4ad62b6e38f8a6e61d0c479a2a018b732a112e83 Mon Sep 17 00:00:00 2001 From: Lars Date: Mon, 23 Nov 2026 14:56:15 +0100 Subject: [PATCH 6/8] Show which exercises differ from their last published release. The release tab names the changed areas, and an admin list collects those exercises so a new release stays a deliberate publication. Co-authored-by: Cursor --- .../working/ACCESS_LAYER_ENDPOINT_AUDIT.md | 2 +- backend/distribution_contract.py | 65 +++++++++++++ backend/distribution_service.py | 95 +++++++++++++++++++ backend/routers/distribution.py | 8 ++ backend/tests/test_distribution_contract.py | 30 ++++++ backend/version.py | 11 ++- frontend/src/App.jsx | 5 + frontend/src/api/distribution.js | 4 + frontend/src/components/AdminPageNav.jsx | 3 +- .../exercises/ExerciseDistributionPanel.jsx | 9 ++ .../exercises/ExerciseFormPageRoot.jsx | 10 +- frontend/src/pages/AccountSettingsPage.jsx | 2 + frontend/src/pages/AdminDistributionPage.jsx | 3 + .../src/pages/AdminReleaseUpdatesPage.jsx | 64 +++++++++++++ 14 files changed, 305 insertions(+), 6 deletions(-) create mode 100644 frontend/src/pages/AdminReleaseUpdatesPage.jsx diff --git a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md index 197a080..8b557e9 100644 --- a/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md +++ b/.claude/docs/working/ACCESS_LAYER_ENDPOINT_AUDIT.md @@ -30,7 +30,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C. | media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung | | exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv | | distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals | -| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` und freigeschalteter Verein; global: nur `superadmin`. Schlüssel legt der Mandant an. Vereinsfreischaltung nur `superadmin` | +| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*`, `GET /api/distribution/release-updates` | ja | `get_tenant_context` | ja | Privat: Besitzer; Verein: `club_admin` und freigeschalteter Verein; global: nur `superadmin`. Schlüssel legt der Mandant an. Vereinsfreischaltung nur `superadmin`. Der Release-Abgleich zeigt nur Übungen, die der Aufrufer erneut freigeben darf | | auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT | | catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen | | skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT | diff --git a/backend/distribution_contract.py b/backend/distribution_contract.py index b472f99..5cbd1e0 100644 --- a/backend/distribution_contract.py +++ b/backend/distribution_contract.py @@ -410,6 +410,71 @@ def _duration_note(exercise: dict) -> Optional[str]: return None +def _manifest_part_text(manifest: dict, role: str) -> str: + parts = ((manifest.get("exercise") or {}).get("parts") or []) + return "\n".join((part.get("text") or "").strip() for part in parts if part.get("role") == role).strip() + + +def _instruction_texts(exercise: dict, variants: list[dict]) -> list[str]: + texts = [] + base = plaintext(exercise.get("execution")) + if variants: + for variant in variants: + extra = plaintext(variant.get("execution_changes")) + combined = "\n".join(piece for piece in (base, extra) if piece) + if combined: + texts.append(combined) + elif base: + texts.append(base) + return texts + + +def changed_areas(exercise: dict, variants: list[dict], media: list[dict], manifest: dict) -> list[str]: + """Benannte Abweichungen der Arbeitsfassung vom gespeicherten Release-Manifest.""" + body = manifest.get("exercise") or {} + areas: list[str] = [] + if (exercise.get("title") or "") != (body.get("title") or ""): + areas.append("Titel") + if (plaintext(exercise.get("summary")) or "") != (body.get("summary") or ""): + areas.append("Kurztext") + for role, label, current in ( + ("goal", "Ziel", plaintext(exercise.get("goal"))), + ("preparation", "Vorbereitung", plaintext(exercise.get("preparation"))), + ("trainer_notes", "Trainerhinweise", plaintext(exercise.get("trainer_notes"))), + ("equipment", "Material", plaintext(_equipment_text(exercise))), + ("duration_note", "Dauer", plaintext(_duration_note(exercise))), + ): + if (current or "") != _manifest_part_text(manifest, role): + areas.append(label) + released_instructions = sorted( + (part.get("text") or "").strip() + for part in (body.get("parts") or []) + if part.get("role") == "instructions" and (part.get("text") or "").strip() + ) + if sorted(_instruction_texts(exercise, variants)) != released_instructions: + areas.append("Durchführung") + released_variants = list(body.get("variants") or []) + if variants: + current_variants = sorted((str(item.get("public_id")), item.get("variant_name") or "") for item in variants) + released_pairs = sorted((str(item.get("id")), item.get("label") or "") for item in released_variants) + if current_variants != released_pairs: + areas.append("Varianten") + elif len(released_variants) != 1: + areas.append("Varianten") + current_by_id = {str(item.get("public_id")): item.get("sha256") or "" for item in media} + released_by_id = {str(item.get("id")): item.get("sha256") or "" for item in (body.get("assets") or [])} + media_changed = set(current_by_id) != set(released_by_id) + if not media_changed: + for key, digest in current_by_id.items(): + released_digest = released_by_id.get(key) or "" + if digest and released_digest and digest != released_digest: + media_changed = True + break + if media_changed: + areas.append("Medien") + return areas + + def _equipment_text(exercise: dict) -> Optional[str]: raw = exercise.get("equipment") if isinstance(raw, str): diff --git a/backend/distribution_service.py b/backend/distribution_service.py index 2e42c73..9fe0a2e 100644 --- a/backend/distribution_service.py +++ b/backend/distribution_service.py @@ -17,6 +17,7 @@ from distribution_contract import ( REASON_CODES, can_withdraw, canonical_json, + changed_areas, collect_blockers, cut_hash, decide_confirm, @@ -415,6 +416,7 @@ def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict: "release_block": release_block, "releases": releases, "keys": keys, + "drift": exercise_release_drift(cur, exercise), "profile_id": profile_id, "role": role, } @@ -1572,6 +1574,99 @@ def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) - return keys, None +def _latest_release_row(cur, source_id: str) -> Optional[dict]: + cur.execute( + """ + SELECT r.release_id, r.revision, r.published_at, r.manifest_text, sr.snapshot_hash + FROM distribution_releases r + JOIN distribution_source_revisions sr + ON sr.source_id = r.source_id AND sr.revision = r.revision + WHERE r.source_id = %s + ORDER BY r.revision DESC, r.published_at DESC + LIMIT 1 + """, + (str(source_id),), + ) + return _one(cur) + + +def _drift_from_row(exercise: dict, variants: list[dict], media: list[dict], row: dict) -> dict: + published = row.get("published_at") + base = { + "differs": False, + "revision": row.get("revision"), + "release_id": str(row["release_id"]), + "published_at": format_utc(published) if published and not isinstance(published, str) else published, + } + if snapshot_hash(exercise, variants, media) == row.get("snapshot_hash"): + return base + manifest = row.get("manifest_text") + if isinstance(manifest, str): + import json + + manifest = json.loads(manifest) + areas = changed_areas(exercise, variants, media, manifest or {}) + return {**base, "differs": True, "areas": areas or ["Weitere Angaben"]} + + +def exercise_release_drift(cur, exercise: dict) -> dict: + row = _latest_release_row(cur, str(exercise["public_id"])) + if not row: + return {"differs": False} + variants = _load_variants(cur, int(exercise["id"])) + media = _load_media(cur, int(exercise["id"])) + return _drift_from_row(exercise, variants, media, row) + + +def _may_rerelease(cur, exercise: dict, profile_id: int, role: str) -> bool: + vis = (exercise.get("visibility") or "private").strip().lower() + kind = {"official": "platform", "club": "club"}.get(vis, "own") + return _denial_for(cur, exercise, {"kind": kind, "club_id": exercise.get("club_id")}, profile_id, role) is None + + +def list_release_drift(cur, profile_id: int, role: str) -> list[dict]: + cur.execute( + """ + SELECT DISTINCT ON (e.id) + e.id, e.public_id, e.title, e.summary, e.goal, e.execution, e.preparation, + e.trainer_notes, e.equipment, e.duration_min, e.duration_max, e.status, + e.visibility, e.club_id, e.exercise_kind, e.created_by, + c.name AS club_name, + r.release_id, r.revision, r.published_at, r.manifest_text, sr.snapshot_hash + FROM exercises e + JOIN distribution_releases r ON r.source_id = e.public_id + JOIN distribution_source_revisions sr + ON sr.source_id = r.source_id AND sr.revision = r.revision + LEFT JOIN clubs c ON c.id = e.club_id + ORDER BY e.id, r.revision DESC, r.published_at DESC + """ + ) + rows = [r2d(row) for row in _rows(cur)] + items = [] + for exercise in rows: + if not _may_rerelease(cur, exercise, profile_id, role): + continue + variants = _load_variants(cur, int(exercise["id"])) + media = _load_media(cur, int(exercise["id"])) + drift = _drift_from_row(exercise, variants, media, exercise) + if not drift["differs"]: + continue + vis = (exercise.get("visibility") or "private").strip().lower() + items.append( + { + "exercise_id": int(exercise["id"]), + "title": exercise.get("title") or "Übung", + "visibility": vis, + "club_name": exercise.get("club_name"), + "revision": drift["revision"], + "published_at": drift["published_at"], + "areas": drift["areas"], + } + ) + items.sort(key=lambda item: (item["title"] or "").lower()) + return items + + def target_for_key(cur, exercise_id: int, key_id: str, profile_id: int, role: str) -> tuple[str, str]: exercise = _load_exercise(cur, exercise_id) keys, block = release_keys_for_exercise(cur, exercise, profile_id, role) diff --git a/backend/routers/distribution.py b/backend/routers/distribution.py index 884ae83..bdc985b 100644 --- a/backend/routers/distribution.py +++ b/backend/routers/distribution.py @@ -29,6 +29,7 @@ from distribution_service import ( create_named_key, issue_key, list_changes, + list_release_drift, load_asset, load_availability, load_manifest, @@ -500,6 +501,13 @@ def get_backlog(tenant: TenantContext = Depends(get_tenant_context)): return {"count": backlog_count(cur)} +@editorial.get("/api/distribution/release-updates") +def get_release_updates(tenant: TenantContext = Depends(get_tenant_context)): + with get_db() as conn: + cur = get_cursor(conn) + return {"items": list_release_drift(cur, tenant.profile_id, tenant.global_role or "")} + + @editorial.get("/api/distribution/access") def get_access(tenant: TenantContext = Depends(get_tenant_context)): with get_db() as conn: diff --git a/backend/tests/test_distribution_contract.py b/backend/tests/test_distribution_contract.py index fb99a4a..f1d863b 100644 --- a/backend/tests/test_distribution_contract.py +++ b/backend/tests/test_distribution_contract.py @@ -29,6 +29,7 @@ from distribution_contract import ( official_write_allowed, plan_available, rate_decision, + changed_areas, release_denial, retrievable_release_ids, sha256_bytes, @@ -281,6 +282,35 @@ def test_release_screen_keeps_the_application_key() -> None: assert [item["label"] for item in keys] == ["Lara"] +def test_changed_areas_names_the_edited_instruction() -> None: + exercise = { + "title": "Stand", + "summary": "", + "goal": "Sehen", + "execution": "Neuer Weg", + "preparation": "", + "trainer_notes": "", + "equipment": None, + "duration_min": None, + "duration_max": None, + } + manifest = { + "exercise": { + "title": "Stand", + "summary": None, + "parts": [ + {"role": "goal", "text": "Sehen"}, + {"role": "instructions", "text": "Alter Weg"}, + ], + "variants": [{"id": "v", "label": "Standard"}], + "assets": [], + } + } + assert changed_areas(exercise, [], [], manifest) == ["Durchführung"] + exercise["execution"] = "Alter Weg" + assert changed_areas(exercise, [], [], manifest) == [] + + def test_channel_sequence_is_locked() -> None: assert "FOR UPDATE" in inspect.getsource(_lock_recipient) diff --git a/backend/version.py b/backend/version.py index 32e890c..5bb2c5a 100644 --- a/backend/version.py +++ b/backend/version.py @@ -1,6 +1,6 @@ # Shinkan Jinkendo Version Information -APP_VERSION = "0.8.255" +APP_VERSION = "0.8.256" BUILD_DATE = "2026-11-23" DB_SCHEMA_VERSION = "20261123101" @@ -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.3.1", # Freigabe liest den Schlüssel, bevor weitere Abfragen denselben Cursor benutzen + "distribution": "1.4.0", # Arbeitsfassung gegen letztes Release: Übung und zentrale Abgleichliste "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.256", + "date": "2026-11-23", + "changes": [ + "Die Übungsfreigabe zeigt, wo die Arbeitsfassung vom letzten Release abweicht. Eine Adminseite listet diese Übungen zum gezielten neuen Release.", + ], + }, { "version": "0.8.255", "date": "2026-11-23", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 859f85d..94a70d0 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -60,6 +60,7 @@ const AdminUsersPage = lazyWithRetry(() => import('./pages/AdminUsersPage')) const AdminClubCreationRequestsPage = lazyWithRetry(() => import('./pages/AdminClubCreationRequestsPage')) const AdminRightsPage = lazyWithRetry(() => import('./pages/AdminRightsPage')) const AdminDistributionPage = lazyWithRetry(() => import('./pages/AdminDistributionPage')) +const AdminReleaseUpdatesPage = lazyWithRetry(() => import('./pages/AdminReleaseUpdatesPage')) const MediaLibraryPage = lazyWithRetry(() => import('./pages/MediaLibraryPage')) const LegalPage = lazyWithRetry(() => import('./pages/LegalPage')) const AdminLegalDocumentsPage = lazyWithRetry(() => import('./pages/AdminLegalDocumentsPage')) @@ -328,6 +329,10 @@ const appRouter = createBrowserRouter([ path: 'admin/distribution', element: , }, + { + path: 'admin/release-updates', + element: , + }, { path: 'admin/rights', element: ( diff --git a/frontend/src/api/distribution.js b/frontend/src/api/distribution.js index f076f55..c1fddb0 100644 --- a/frontend/src/api/distribution.js +++ b/frontend/src/api/distribution.js @@ -81,6 +81,10 @@ export function getDistributionAccess() { return request('/api/distribution/access') } +export function getDistributionReleaseUpdates() { + return request('/api/distribution/release-updates') +} + export function setClubDistributionApi(clubId, enabled) { return request(`/api/distribution/access/clubs/${clubId}`, { method: 'PUT', diff --git a/frontend/src/components/AdminPageNav.jsx b/frontend/src/components/AdminPageNav.jsx index 004bcd5..cd4cf9c 100644 --- a/frontend/src/components/AdminPageNav.jsx +++ b/frontend/src/components/AdminPageNav.jsx @@ -1,5 +1,5 @@ import { NavLink } from 'react-router-dom' -import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield, Share2 } from 'lucide-react' +import { TreePine, FolderTree, Download, Grid3x3, Users, Scale, Sparkles, Bot, Wand2, Activity, Building2, Shield, Share2, FileDiff } from 'lucide-react' /** * Admin-Seiten-Navigation (horizontal) — nur für Super-Admins (globaler Portal-Mandant). @@ -19,6 +19,7 @@ export default function AdminPageNav() { { to: '/admin/openrouter', label: 'KI-Modell', icon: Bot }, { to: '/admin/exercise-enrichment', label: 'Übungs-Anreicherung', icon: Wand2 }, { to: '/admin/distribution', label: 'API-Schnittstelle', icon: Share2 }, + { to: '/admin/release-updates', label: 'Release-Abgleich', icon: FileDiff }, ] return ( diff --git a/frontend/src/components/exercises/ExerciseDistributionPanel.jsx b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx index 9a66024..5e53069 100644 --- a/frontend/src/components/exercises/ExerciseDistributionPanel.jsx +++ b/frontend/src/components/exercises/ExerciseDistributionPanel.jsx @@ -128,6 +128,15 @@ export default function ExerciseDistributionPanel({ exerciseId }) {

Die Distribution ist auf dieser Instanz nicht aktiv. Bearbeitung und Planung bleiben davon unberührt.

) : ( <> + {overview.drift?.differs ? ( +

+ Die Arbeitsfassung weicht vom Release Revision {overview.drift.revision} ab + {overview.drift.areas?.length ? `: ${overview.drift.areas.join(', ')}` : ''}. Ein neues Release + veröffentlicht diesen Stand. Das bisherige Release bleibt unter seiner ID abrufbar. +

+ ) : overview.releases?.length ? ( +

Die Arbeitsfassung entspricht dem letzten Release.

+ ) : null} {overview.release_block ?

{overview.release_block}

: null}