Publish frozen exercise releases and report whether they stay offerable.
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s

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 <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-23 13:07:47 +01:00
1 parent b537750671
commit fe3633ba8b
21 files changed
+3862 -12

No files matched your search

+259
View File
@@ -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)