"""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 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" 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())