feat: live-sync per websocket im backend
- /api/ws authentifiziert über das Session-Cookie, Origin-Pflicht gegen CSWSH - Hub im Prozess verteilt clip.created/updated/deleted an alle Geräte des Benutzers - Ereignisse erst nach erfolgreichem Commit (BackgroundTasks), keine bei Konflikt - Logout, Session-Widerruf, Passwortänderung und Admin-Aktionen schließen betroffene Verbindungen (4401); Session wird alle 5 Minuten neu geprüft - Heartbeat alle 30 s, höchstens 20 Verbindungen pro Benutzer - CSP erlaubt wss:// zur eigenen Domain, eingehende WS-Nachrichten max. 64 KiB Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a444f28681
commit
0d89399090
12 files changed
+483
-38
No files matched your search
@@ -1,10 +1,11 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
|
||||
from app.api.deps import AdminUser, DbSession
|
||||
from app.models import User
|
||||
from app.schemas.auth import UserOut
|
||||
from app.schemas.users import UserCreate, UserUpdate
|
||||
from app.services import users as user_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
@@ -32,13 +33,19 @@ def get_user(user_id: int, _admin: AdminUser, db: DbSession):
|
||||
|
||||
|
||||
@router.patch("/users/{user_id}", response_model=UserOut)
|
||||
def update_user(user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession):
|
||||
def update_user(
|
||||
user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession, background: BackgroundTasks
|
||||
):
|
||||
target = _get_user_or_404(db, user_id)
|
||||
return user_service.update_user(
|
||||
user = user_service.update_user(
|
||||
db, admin, target, role=body.role, is_active=body.is_active, password=body.password
|
||||
)
|
||||
if body.is_active is False or body.password is not None:
|
||||
background.add_task(hub.close_user, user_id)
|
||||
return user
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_user(user_id: int, admin: AdminUser, db: DbSession) -> None:
|
||||
def delete_user(user_id: int, admin: AdminUser, db: DbSession, background: BackgroundTasks) -> None:
|
||||
user_service.delete_user(db, admin, _get_user_or_404(db, user_id))
|
||||
background.add_task(hub.close_user, user_id)
|
||||
+23
-5
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, HTTPException, Request, Response, status
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, Response, status
|
||||
|
||||
from app.api.deps import (
|
||||
SESSION_COOKIE,
|
||||
@@ -20,6 +20,7 @@ from app.security import verify_password
|
||||
from app.services import sessions as session_service
|
||||
from app.services.auth import LoginBlocked, authenticate
|
||||
from app.services.users import set_password
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -49,9 +50,12 @@ def login(body: LoginRequest, request: Request, response: Response, db: DbSessio
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def logout(session: CurrentSession, response: Response, db: DbSession) -> None:
|
||||
def logout(
|
||||
session: CurrentSession, response: Response, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
session_service.revoke_session(db, session.user_id, session.id)
|
||||
clear_session_cookies(response)
|
||||
background.add_task(hub.close_session, session.id)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
@@ -60,10 +64,16 @@ def me(user: CurrentUser):
|
||||
|
||||
|
||||
@router.post("/password", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def change_password(body: PasswordChangeRequest, session: CurrentSession, db: DbSession) -> None:
|
||||
def change_password(
|
||||
body: PasswordChangeRequest,
|
||||
session: CurrentSession,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
if not verify_password(session.user.password_hash, body.current_password):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Das aktuelle Passwort ist falsch.")
|
||||
set_password(db, session.user, body.new_password, keep_session_id=session.id)
|
||||
background.add_task(hub.close_user, session.user_id, except_session_id=session.id)
|
||||
|
||||
|
||||
@router.get("/sessions", response_model=list[SessionOut])
|
||||
@@ -76,15 +86,23 @@ def list_sessions(session: CurrentSession, db: DbSession) -> list[SessionOut]:
|
||||
|
||||
@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def revoke_session(
|
||||
session_id: int, session: CurrentSession, response: Response, db: DbSession
|
||||
session_id: int,
|
||||
session: CurrentSession,
|
||||
response: Response,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
if not session_service.revoke_session(db, session.user_id, session_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Sitzung nicht gefunden.")
|
||||
if session_id == session.id:
|
||||
clear_session_cookies(response)
|
||||
background.add_task(hub.close_session, session_id)
|
||||
|
||||
|
||||
@router.delete("/sessions", response_model=RevokedResponse)
|
||||
def revoke_other_sessions(session: CurrentSession, db: DbSession) -> RevokedResponse:
|
||||
def revoke_other_sessions(
|
||||
session: CurrentSession, db: DbSession, background: BackgroundTasks
|
||||
) -> RevokedResponse:
|
||||
revoked = session_service.revoke_other_sessions(db, session.user_id, session.id)
|
||||
background.add_task(hub.close_user, session.user_id, except_session_id=session.id)
|
||||
return RevokedResponse(revoked=revoked)
|
||||
@@ -1,12 +1,13 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
from app.services import clips as clip_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
@@ -14,6 +15,15 @@ router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
_NULLABLE_FIELDS = {"title", "language"}
|
||||
|
||||
|
||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||
"""Tell all devices of the user about a change, after the response is sent."""
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
|
||||
|
||||
def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
@@ -34,8 +44,10 @@ def list_clips(
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession):
|
||||
return clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
_notify(background, user.id, "clip.created", _clip_data(clip))
|
||||
return clip
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
@@ -44,7 +56,13 @@ def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
||||
def update_clip(
|
||||
clip_id: int,
|
||||
body: ClipUpdate,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
clip = _get_own_clip(db, user, clip_id)
|
||||
changes = {
|
||||
field: getattr(body, field)
|
||||
@@ -52,18 +70,23 @@ def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession
|
||||
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||
}
|
||||
try:
|
||||
return clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
clip = clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
except clip_service.ClipConflict as exc:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
content={
|
||||
"detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.",
|
||||
"current": ClipOut.model_validate(exc.current).model_dump(mode="json"),
|
||||
"current": _clip_data(exc.current),
|
||||
},
|
||||
)
|
||||
_notify(background, user.id, "clip.updated", _clip_data(clip))
|
||||
return clip
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
||||
def delete_clip(
|
||||
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
_notify(background, user.id, "clip.deleted", {"id": clip_id})
|
||||
@@ -0,0 +1,85 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
from app.api.deps import SESSION_COOKIE
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.services.sessions import is_session_valid, resolve_session
|
||||
from app.ws.hub import CLOSE_UNAUTHORIZED, Connection, hub
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_CONNECTIONS_PER_USER = 20
|
||||
PING_INTERVAL_SECONDS = 30
|
||||
REVALIDATE_INTERVAL_SECONDS = 300
|
||||
CLOSE_TOO_MANY = 4429
|
||||
|
||||
|
||||
def _resolve(token: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
session = resolve_session(db, token)
|
||||
return (session.id, session.user_id) if session else None
|
||||
|
||||
|
||||
def _still_valid(session_id: int) -> bool:
|
||||
with _session_factory()() as db:
|
||||
return is_session_valid(db, session_id)
|
||||
|
||||
|
||||
async def _heartbeat(conn: Connection) -> None:
|
||||
"""Keep the connection alive through the proxy and end it when the session ends."""
|
||||
last_check = time.monotonic()
|
||||
while True:
|
||||
await asyncio.sleep(PING_INTERVAL_SECONDS)
|
||||
await conn.websocket.send_json({"type": "ping"})
|
||||
if time.monotonic() - last_check >= REVALIDATE_INTERVAL_SECONDS:
|
||||
last_check = time.monotonic()
|
||||
if not await run_in_threadpool(_still_valid, conn.session_id):
|
||||
await conn.websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
|
||||
|
||||
async def _drain(conn: Connection) -> None:
|
||||
"""Clients do not send commands; reading only detects disconnects."""
|
||||
while True:
|
||||
await conn.websocket.receive_text()
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def websocket_endpoint(websocket: WebSocket) -> None:
|
||||
# Origin check protects the cookie-authenticated socket against cross-site hijacking
|
||||
origin = (websocket.headers.get("origin") or "").rstrip("/")
|
||||
if origin not in get_settings().allowed_origin_list:
|
||||
await websocket.close(code=4403) # before accept: handshake is rejected
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
# Accept first so the client sees the close code and can redirect to login
|
||||
ids = await run_in_threadpool(_resolve, websocket.cookies.get(SESSION_COOKIE))
|
||||
if ids is None:
|
||||
await websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
session_id, user_id = ids
|
||||
if hub.count(user_id) >= MAX_CONNECTIONS_PER_USER:
|
||||
await websocket.close(code=CLOSE_TOO_MANY)
|
||||
return
|
||||
|
||||
conn = Connection(websocket=websocket, user_id=user_id, session_id=session_id)
|
||||
hub.add(conn)
|
||||
try:
|
||||
await websocket.send_json({"type": "hello"})
|
||||
tasks = [asyncio.create_task(_heartbeat(conn)), asyncio.create_task(_drain(conn))]
|
||||
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
for task in done:
|
||||
exc = task.exception()
|
||||
if exc is not None and not isinstance(exc, WebSocketDisconnect | RuntimeError):
|
||||
raise exc
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
hub.remove(conn)
|
||||
Reference in new issue
Block a user