feat: enhance media access and security for exercises
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Successful in 23s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 25s

- Updated PostgreSQL binding in docker-compose to restrict access to localhost only.
- Implemented a new API endpoint for secure media file delivery, requiring authentication via token.
- Enhanced governance checks for exercise media access, ensuring only authorized users can retrieve files.
- Updated frontend components to utilize the new media file access method, improving user experience while maintaining security.
- Documented changes in production readiness audit and access layer endpoint audit for clarity on security enhancements.
This commit is contained in:
Lars committed 2026-05-07 10:52:14 +02:00
1 parent c2d9eac151
commit b752883392
13 files changed
+235 -42

No files matched your search

+65 -1
View File
@@ -12,6 +12,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, HTTPException, Depends, Query, UploadFile, File, Form
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field, model_validator
from db import get_db, get_cursor, r2d
@@ -23,7 +24,7 @@ from club_tenancy import (
is_platform_admin,
library_content_visible_to_profile,
)
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
logger = logging.getLogger(__name__)
@@ -303,6 +304,36 @@ def _detect_embed_platform(url: str) -> Optional[str]:
return None
def _fetch_exercise_governance_row(cur, exercise_id: int) -> Optional[dict]:
cur.execute(
"SELECT id, visibility, club_id, created_by FROM exercises WHERE id = %s",
(exercise_id,),
)
row = cur.fetchone()
return r2d(row) if row else None
def _assert_can_view_exercise_media(
cur,
exercise_id: int,
tenant: TenantContext,
) -> dict:
"""403 wenn Übung für den Nutzer nicht lesbar (wie GET /exercises/{id})."""
ex = _fetch_exercise_governance_row(cur, exercise_id)
if not ex:
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
if not library_content_visible_to_profile(
cur,
tenant.profile_id,
(ex.get("visibility") or "").strip().lower(),
ex.get("club_id"),
ex.get("created_by"),
tenant.global_role,
):
raise HTTPException(status_code=403, detail="Keine Berechtigung für diese Übung")
return ex
def _assert_can_edit_exercise(cur, exercise_id: int, profile_id: int):
cur.execute("SELECT created_by FROM exercises WHERE id = %s", (exercise_id,))
row = cur.fetchone()
@@ -1801,6 +1832,39 @@ def _fetch_media_row(cur, exercise_id: int, media_id: int) -> Optional[dict]:
return r2d(row) if row else None
@router.get("/exercises/{exercise_id}/media/{media_id}/file")
def download_exercise_media_file(
exercise_id: int,
media_id: int,
tenant: TenantContext = Depends(get_tenant_context_flexible),
):
"""
Dateiauslieferung mit Governance wie GET Übung — Auth via X-Auth-Token oder ?ssetoken (für <img>/<video>).
Direktes /media/... ohne Token ist nicht vorgesehen (kein anonymes Hosting).
"""
with get_db() as conn:
cur = get_cursor(conn)
_assert_can_view_exercise_media(cur, exercise_id, tenant)
media = _fetch_media_row(cur, exercise_id, media_id)
if not media:
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
if (media.get("embed_url") or "").strip():
raise HTTPException(status_code=400, detail="Embed-Medien haben keine Datei-URL")
fp = media.get("file_path")
abs_p = _abs_media_path(fp) if fp else None
if not abs_p or not abs_p.is_file():
raise HTTPException(status_code=404, detail="Datei nicht gefunden")
mime = media.get("mime_type") or "application/octet-stream"
fname = media.get("original_filename") or abs_p.name
return FileResponse(
path=str(abs_p.resolve()),
media_type=mime,
filename=str(fname),
)
@router.post("/exercises/{exercise_id}/media", status_code=201)
async def upload_exercise_media(
exercise_id: int,