feat(P-11): Implement Legal Hold functionality for media assets
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 34s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 10s
Test Suite / playwright-tests (push) Successful in 54s

- Added backend support for Legal Hold with new endpoints to set and release holds on media assets.
- Introduced new database columns for managing Legal Hold status and reasons.
- Updated frontend to include UI elements for setting and releasing Legal Holds, including a confirmation dialog.
- Enhanced Media Library page to display Legal Hold status and actions for superadmins.
- Implemented comprehensive backend tests covering all aspects of Legal Hold functionality.
- Updated documentation to reflect changes in the upload rights specification and interface models.
- Bumped version to 0.8.84 and updated MediaLibraryPage version to 1.6.0.
This commit is contained in:
Lars committed 2026-05-11 12:33:13 +02:00
1 parent 1640fe6045
commit 1ce6d929ce
16 files changed
+1180 -42

No files matched your search

+4 -1
View File
@@ -30,6 +30,7 @@ from club_tenancy import (
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
from media_rights import assert_rights_for_exercise_link, validate_rights_declaration, write_rights_declaration, update_rights_quick_fields
from media_legal_hold import assert_not_under_legal_hold
from exercise_rich_text import (
RICH_HTML_EXERCISE_FIELDS,
assert_no_inline_media_references_on_create,
@@ -2880,7 +2881,7 @@ def attach_exercise_media_from_asset(
cur.execute(
"""SELECT id, mime_type, byte_size, original_filename, visibility, club_id,
uploaded_by_profile_id, storage_key, lifecycle_state
uploaded_by_profile_id, storage_key, lifecycle_state, legal_hold_active
FROM media_assets WHERE id = %s""",
(body.media_asset_id,),
)
@@ -2893,6 +2894,8 @@ def attach_exercise_media_from_asset(
status_code=400,
detail="Nur aktive Archiv-Medien können verknüpft werden",
)
# P-11: Legal Hold verhindert neue Einbindung in Übungen
assert_not_under_legal_hold(asset)
if not library_content_visible_to_profile(
cur,
+172 -6
View File
@@ -48,6 +48,14 @@ from media_rights import (
check_rights_coverage,
VISIBILITY_LEVELS,
)
from media_legal_hold import (
LEGAL_HOLD_REASON_CODES,
assert_not_under_legal_hold,
assert_superadmin_for_legal_hold,
is_media_available_for_normal_use,
set_legal_hold,
release_legal_hold,
)
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
router = APIRouter(prefix="/api/media-assets", tags=["media-assets"])
@@ -456,8 +464,16 @@ def _relocate_asset_file_if_governance_changed(
def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str, list[Any]]:
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL."""
def _list_active_visibility_clause(
is_plat: bool,
profile_id: int,
include_legal_hold: bool = False,
) -> tuple[str, list[Any]]:
"""Sichtbare aktive Einträge: official; private (eigen oder Plattform-Admin); Verein wie Bibliotheks-SQL.
P-11: Legal-Hold-Medien sind für normale Nutzer nicht sichtbar.
is_plat/is_sup können include_legal_hold=True übergeben, um sie weiterhin zu sehen.
"""
parts = ["lower(trim(ma.visibility)) = 'official'"]
vals: list[Any] = []
@@ -491,8 +507,13 @@ def _list_active_visibility_clause(is_plat: bool, profile_id: int) -> tuple[str,
)
vals.append(profile_id)
sql = "(" + " OR ".join(parts) + ")"
return sql, vals
vis_sql = "(" + " OR ".join(parts) + ")"
# P-11: Legal-Hold-Medien für normale Nutzer ausblenden
if not include_legal_hold:
vis_sql = f"({vis_sql} AND (ma.legal_hold_active = FALSE OR ma.legal_hold_active IS NULL))"
return vis_sql, vals
def _list_trash_visibility_clause(
@@ -530,12 +551,15 @@ def _list_main_visibility_where(
) -> tuple[str, list[Any]]:
"""
Kombiniert lifecycle mit Leserechten. Papierkorb-Stufen für normale Nutzer stark eingeschränkt.
P-11: Plattform-Admins und Superadmins sehen Legal-Hold-Medien in der aktiven Liste.
"""
lc = (lifecycle or "active").strip().lower()
if lc not in _LIFECYCLE_LIST_FILTERS:
raise HTTPException(status_code=400, detail="Ungültiger lifecycle-Filter")
active_sql, active_params = _list_active_visibility_clause(is_plat, profile_id)
active_sql, active_params = _list_active_visibility_clause(
is_plat, profile_id, include_legal_hold=(is_plat or is_sup)
)
trash_sql, trash_params = _list_trash_visibility_clause(
is_plat, is_sup, profile_id, admin_club_ids
)
@@ -1187,9 +1211,30 @@ def download_media_asset_file(
with get_db() as conn:
cur = get_cursor(conn)
asset = _fetch_asset_file_row(cur, asset_id)
# _fetch_asset_file_row wird erweitert um legal_hold_active
cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
storage_key, mime_type, original_filename, legal_hold_active
FROM media_assets WHERE id = %s""",
(asset_id,),
)
row = cur.fetchone()
asset = r2d(row) if row else None
if not asset:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
# P-11: Legal Hold blockiert normalen Dateizugriff (nicht für Superadmin)
if bool(asset.get("legal_hold_active")):
role = tenant.global_role if hasattr(tenant, "global_role") else None
if not is_superadmin(role):
raise HTTPException(
status_code=403,
detail={
"code": "LEGAL_HOLD_ACTIVE",
"message": "Dieses Medium ist sofort gesperrt und nicht verfügbar.",
},
)
lc = (asset.get("lifecycle_state") or "").strip().lower()
if lc == "active":
_assert_can_view_archive_asset(cur, tenant, asset)
@@ -1909,3 +1954,124 @@ def add_rights_correction(
conn.commit()
return {"ok": True, "asset_id": asset_id}
# ---------------------------------------------------------------------------
# P-11: Legal-Hold-Endpoints (Superadmin only)
# ---------------------------------------------------------------------------
admin_legal_hold_router = APIRouter(prefix="/api/admin/media-assets", tags=["admin", "legal-hold"])
class LegalHoldSetBody(BaseModel):
reason_code: str = Field(..., description="Kategorie des Legal Holds")
reason_note: str = Field(..., min_length=5, max_length=2000, description="Pflichtbegründung")
class LegalHoldReleaseBody(BaseModel):
release_note: str = Field(..., min_length=5, max_length=2000, description="Freigabe-Begründung")
@admin_legal_hold_router.post("/{asset_id}/legal-hold")
def post_legal_hold_set(
asset_id: int,
body: LegalHoldSetBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Legal Hold auf ein Medium setzen. Nur Superadmin.
Wirkung: Sofortige Unsichtbarkeit in normalen Nutzerpfaden, rights_status='blocked',
Audit-Log-Eintrag. Keine automatische physische Löschung. Keine Löschfristen.
"""
assert_superadmin_for_legal_hold(tenant.global_role)
with get_db() as conn:
cur = get_cursor(conn)
result = set_legal_hold(
cur, conn,
asset_id=asset_id,
acting_profile_id=int(tenant.profile_id),
reason_code=body.reason_code,
reason_note=body.reason_note,
)
return {
"ok": True,
"asset_id": asset_id,
"legal_hold_active": result.get("legal_hold_active"),
"rights_status": result.get("rights_status"),
"legal_hold_reason_code": result.get("legal_hold_reason_code"),
"legal_hold_set_at": str(result.get("legal_hold_set_at", "")),
}
@admin_legal_hold_router.post("/{asset_id}/legal-hold/release")
def post_legal_hold_release(
asset_id: int,
body: LegalHoldReleaseBody,
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Legal Hold aufheben. Nur Superadmin.
Wirkung: legal_hold_active=FALSE, rights_status wiederhergestellt,
Audit-Log-Eintrag. Vorheriger Lifecycle-Zustand bleibt erhalten.
"""
assert_superadmin_for_legal_hold(tenant.global_role)
with get_db() as conn:
cur = get_cursor(conn)
result = release_legal_hold(
cur, conn,
asset_id=asset_id,
acting_profile_id=int(tenant.profile_id),
release_note=body.release_note,
)
return {
"ok": True,
"asset_id": asset_id,
"legal_hold_active": result.get("legal_hold_active"),
"rights_status": result.get("rights_status"),
"legal_hold_released_at": str(result.get("legal_hold_released_at", "")),
}
@admin_legal_hold_router.get("/legal-hold")
def list_legal_hold_assets(
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
tenant: TenantContext = Depends(get_tenant_context),
):
"""P-11: Admin-Liste aller Medien unter aktivem Legal Hold. Superadmin oder Plattform-Admin."""
if not is_platform_admin(tenant.global_role):
raise HTTPException(
status_code=403,
detail="Keine Berechtigung (Plattform-Admin oder Superadmin erforderlich)",
)
with get_db() as conn:
cur = get_cursor(conn)
cur.execute(
"""
SELECT ma.id, ma.original_filename, ma.visibility, ma.club_id,
ma.lifecycle_state, ma.rights_status,
ma.legal_hold_active, ma.legal_hold_reason_code,
ma.legal_hold_reason_note, ma.legal_hold_set_at,
ma.legal_hold_set_by_profile_id,
p_set.name AS set_by_name,
ma.uploaded_by_profile_id,
p_upl.name AS uploader_name,
cl.name AS club_name,
ma.created_at
FROM media_assets ma
LEFT JOIN profiles p_set ON p_set.id = ma.legal_hold_set_by_profile_id
LEFT JOIN profiles p_upl ON p_upl.id = ma.uploaded_by_profile_id
LEFT JOIN clubs cl ON cl.id = ma.club_id
WHERE ma.legal_hold_active = TRUE
ORDER BY ma.legal_hold_set_at DESC NULLS LAST, ma.id DESC
LIMIT %s OFFSET %s
""",
(limit, offset),
)
assets = [r2d(r) for r in cur.fetchall()]
cur.execute(
"SELECT COUNT(*) AS cnt FROM media_assets WHERE legal_hold_active = TRUE"
)
total_row = cur.fetchone()
total = int(r2d(total_row)["cnt"]) if total_row else 0
return {"total": total, "limit": limit, "offset": offset, "assets": assets}