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
+474
-29
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)
|
||||
+3
-2
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, clips, health
|
||||
from app.api import admin, auth, clips, health, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -106,11 +106,12 @@ def create_app() -> FastAPI:
|
||||
# Last added runs first: security headers wrap every response, including rejections
|
||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes)
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
app.include_router(clips.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
|
||||
@@ -26,21 +26,26 @@ class OriginCheckMiddleware:
|
||||
await self.app(scope, receive, send)
|
||||
|
||||
|
||||
CONTENT_SECURITY_POLICY = "; ".join(
|
||||
def build_csp(allowed_origins: list[str]) -> str:
|
||||
# Older Safari does not match ws/wss against 'self', so list the socket origins explicitly
|
||||
ws_origins = [
|
||||
o.replace("https://", "wss://", 1) for o in allowed_origins if o.startswith("https://")
|
||||
]
|
||||
return "; ".join(
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
" ".join(["connect-src 'self'", *ws_origins]),
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
SECURITY_HEADERS = [
|
||||
(b"content-security-policy", CONTENT_SECURITY_POLICY.encode()),
|
||||
(b"x-content-type-options", b"nosniff"),
|
||||
(b"referrer-policy", b"same-origin"),
|
||||
(b"x-frame-options", b"DENY"),
|
||||
@@ -54,15 +59,16 @@ HSTS_HEADER = (b"strict-transport-security", b"max-age=31536000")
|
||||
class SecurityHeadersMiddleware:
|
||||
"""Add security headers to every HTTP response; HSTS only for HTTPS requests."""
|
||||
|
||||
def __init__(self, app: ASGIApp) -> None:
|
||||
def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None:
|
||||
self.app = app
|
||||
self.csp_header = (b"content-security-policy", build_csp(allowed_origins).encode())
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
extra = list(SECURITY_HEADERS)
|
||||
extra = [self.csp_header, *SECURITY_HEADERS]
|
||||
if scope.get("scheme") == "https":
|
||||
extra.append(HSTS_HEADER)
|
||||
|
||||
|
||||
@@ -32,11 +32,8 @@ def create_session(
|
||||
return session, token
|
||||
|
||||
|
||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
"""Return the valid session for a raw token; expired sessions are deleted."""
|
||||
if not token:
|
||||
return None
|
||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
||||
def _validate(db: Session, session: UserSession | None, touch: bool) -> UserSession | None:
|
||||
"""Return the session if still valid; expired ones are deleted."""
|
||||
if session is None:
|
||||
return None
|
||||
|
||||
@@ -47,12 +44,25 @@ def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
if now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||
if touch and now - session.last_seen_at >= TOUCH_INTERVAL:
|
||||
session.last_seen_at = now
|
||||
db.commit()
|
||||
return session
|
||||
|
||||
|
||||
def resolve_session(db: Session, token: str | None) -> UserSession | None:
|
||||
"""Return the valid session for a raw token and record activity."""
|
||||
if not token:
|
||||
return None
|
||||
session = db.scalar(select(UserSession).where(UserSession.token_hash == hash_token(token)))
|
||||
return _validate(db, session, touch=True)
|
||||
|
||||
|
||||
def is_session_valid(db: Session, session_id: int) -> bool:
|
||||
"""Re-check a known session (e.g. for long-lived WebSockets) without recording activity."""
|
||||
return _validate(db, db.get(UserSession, session_id), touch=False) is not None
|
||||
|
||||
|
||||
def list_sessions(db: Session, user_id: int) -> list[UserSession]:
|
||||
return list(
|
||||
db.scalars(
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,79 @@
|
||||
"""In-process registry of WebSocket connections, keyed by user.
|
||||
|
||||
All methods run on the event loop; sync request handlers reach them via BackgroundTasks.
|
||||
This only works with a single worker process (see CLAUDE.md).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from fastapi import WebSocket
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEND_TIMEOUT_SECONDS = 5
|
||||
CLOSE_UNAUTHORIZED = 4401
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class Connection:
|
||||
websocket: WebSocket
|
||||
user_id: int
|
||||
session_id: int
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self) -> None:
|
||||
self._by_user: dict[int, set[Connection]] = defaultdict(set)
|
||||
|
||||
def count(self, user_id: int) -> int:
|
||||
return len(self._by_user.get(user_id, ()))
|
||||
|
||||
def add(self, conn: Connection) -> None:
|
||||
self._by_user[conn.user_id].add(conn)
|
||||
|
||||
def remove(self, conn: Connection) -> None:
|
||||
conns = self._by_user.get(conn.user_id)
|
||||
if conns is not None:
|
||||
conns.discard(conn)
|
||||
if not conns:
|
||||
del self._by_user[conn.user_id]
|
||||
|
||||
async def broadcast(self, user_id: int, message: dict[str, Any]) -> None:
|
||||
"""Send a message to every connection of one user; dead connections are dropped."""
|
||||
text = json.dumps(message)
|
||||
for conn in list(self._by_user.get(user_id, ())):
|
||||
try:
|
||||
await asyncio.wait_for(conn.websocket.send_text(text), SEND_TIMEOUT_SECONDS)
|
||||
except Exception:
|
||||
logger.info("Dropping unresponsive WebSocket of user %s", user_id)
|
||||
self.remove(conn)
|
||||
await self._close(conn, 1011)
|
||||
|
||||
async def close_session(self, session_id: int) -> None:
|
||||
await self._close_where(lambda c: c.session_id == session_id)
|
||||
|
||||
async def close_user(self, user_id: int, except_session_id: int | None = None) -> None:
|
||||
await self._close_where(
|
||||
lambda c: c.user_id == user_id and c.session_id != except_session_id
|
||||
)
|
||||
|
||||
async def _close_where(self, predicate) -> None:
|
||||
targets = [c for conns in self._by_user.values() for c in conns if predicate(c)]
|
||||
for conn in targets:
|
||||
self.remove(conn)
|
||||
await self._close(conn, CLOSE_UNAUTHORIZED)
|
||||
|
||||
@staticmethod
|
||||
async def _close(conn: Connection, code: int) -> None:
|
||||
try:
|
||||
await conn.websocket.close(code=code)
|
||||
except Exception: # already closed or broken
|
||||
logger.debug("WebSocket already closed", exc_info=True)
|
||||
|
||||
|
||||
hub = Hub()
|
||||
@@ -82,3 +82,8 @@ def test_oversized_chunked_request_is_rejected(client):
|
||||
def test_normal_requests_pass_size_limit(client):
|
||||
response = client.post("/api/auth/login", json={"username": "x", "password": "y"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_csp_allows_websocket_to_own_origin(client):
|
||||
csp = client.get("/api/health").headers["content-security-policy"]
|
||||
assert "connect-src 'self' wss://testserver" in csp
|
||||
@@ -0,0 +1,210 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app.api import ws as ws_module
|
||||
from app.models import Role
|
||||
from tests.conftest import PASSWORD, login
|
||||
|
||||
ORIGIN = {"Origin": "https://testserver"}
|
||||
|
||||
|
||||
def connect(c: TestClient, headers=ORIGIN):
|
||||
# TestClient always uses ws:// and therefore drops Secure cookies; browsers use wss://
|
||||
cookie = "; ".join(f"{name}={value}" for name, value in c.cookies.items())
|
||||
return c.websocket_connect("/api/ws", headers={**headers, "Cookie": cookie})
|
||||
|
||||
|
||||
def expect_close(c: TestClient, code: int, headers=ORIGIN) -> None:
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(c, headers) as ws:
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
assert exc.value.code == code
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def second_client(client):
|
||||
def _make(username: str, password: str = PASSWORD) -> TestClient:
|
||||
other = TestClient(client.app, base_url="https://testserver")
|
||||
login(other, username, password)
|
||||
return other
|
||||
|
||||
return _make
|
||||
|
||||
|
||||
# --- Handshake ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_connect_with_session(anna):
|
||||
with connect(anna) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
|
||||
|
||||
def test_connect_without_session_is_closed_4401(client):
|
||||
expect_close(client, 4401)
|
||||
|
||||
|
||||
def test_foreign_origin_is_rejected(anna):
|
||||
expect_close(anna, 4403, {"Origin": "https://evil.example"})
|
||||
|
||||
|
||||
def test_missing_origin_is_rejected(anna):
|
||||
expect_close(anna, 4403, {})
|
||||
|
||||
|
||||
def test_connection_limit(anna, monkeypatch):
|
||||
monkeypatch.setattr(ws_module, "MAX_CONNECTIONS_PER_USER", 2)
|
||||
with connect(anna) as ws1, connect(anna) as ws2:
|
||||
ws1.receive_json()
|
||||
ws2.receive_json()
|
||||
expect_close(anna, 4429)
|
||||
|
||||
|
||||
# --- Clip events ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_clip_events_reach_all_devices_of_user(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with connect(anna) as laptop_ws, connect(phone) as phone_ws:
|
||||
laptop_ws.receive_json()
|
||||
phone_ws.receive_json()
|
||||
|
||||
clip = phone.post("/api/clips", json={"content": "from phone"}).json()
|
||||
for ws in (laptop_ws, phone_ws):
|
||||
event = ws.receive_json()
|
||||
assert event["type"] == "clip.created"
|
||||
assert event["data"]["id"] == clip["id"]
|
||||
assert event["data"]["content"] == "from phone"
|
||||
|
||||
phone.patch(f"/api/clips/{clip['id']}", json={"content": "edited"})
|
||||
event = laptop_ws.receive_json()
|
||||
assert event["type"] == "clip.updated"
|
||||
assert event["data"]["content"] == "edited"
|
||||
assert event["data"]["version"] == 2
|
||||
phone_ws.receive_json()
|
||||
|
||||
phone.delete(f"/api/clips/{clip['id']}")
|
||||
assert laptop_ws.receive_json() == {"type": "clip.deleted", "data": {"id": clip["id"]}}
|
||||
|
||||
|
||||
def test_no_event_on_conflict(anna):
|
||||
clip = anna.post("/api/clips", json={"content": "x"}).json()
|
||||
with connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
assert (
|
||||
anna.patch(f"/api/clips/{clip['id']}", json={"content": "y", "version": 99}).status_code
|
||||
== 409
|
||||
)
|
||||
anna.post("/api/clips", json={"content": "marker"})
|
||||
# The next event is the marker, so the conflict produced none
|
||||
assert ws.receive_json()["data"]["content"] == "marker"
|
||||
|
||||
|
||||
def test_events_are_not_sent_to_other_users(anna, make_user, second_client):
|
||||
make_user("bert")
|
||||
bert = second_client("bert")
|
||||
with connect(bert) as bert_ws:
|
||||
bert_ws.receive_json()
|
||||
|
||||
anna.post("/api/clips", json={"content": "anna's secret"})
|
||||
bert.post("/api/clips", json={"content": "marker"})
|
||||
|
||||
event = bert_ws.receive_json()
|
||||
assert event["data"]["content"] == "marker"
|
||||
|
||||
|
||||
# --- Session end closes sockets -------------------------------------------------
|
||||
|
||||
|
||||
def test_logout_closes_socket(anna):
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
anna.post("/api/auth/logout")
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_revoking_session_closes_its_socket_only(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
sessions = anna.get("/api/auth/sessions").json()
|
||||
phone_session = next(s for s in sessions if not s["current"])
|
||||
|
||||
with connect(anna) as laptop_ws:
|
||||
laptop_ws.receive_json()
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.delete(f"/api/auth/sessions/{phone_session['id']}")
|
||||
phone_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert laptop_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_revoke_other_sessions_closes_their_sockets(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with connect(anna) as laptop_ws:
|
||||
laptop_ws.receive_json()
|
||||
with pytest.raises(WebSocketDisconnect), connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.delete("/api/auth/sessions")
|
||||
phone_ws.receive_json()
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert laptop_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_password_change_closes_other_sockets(anna, second_client):
|
||||
phone = second_client("anna")
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(phone) as phone_ws:
|
||||
phone_ws.receive_json()
|
||||
anna.post(
|
||||
"/api/auth/password",
|
||||
json={"current_password": PASSWORD, "new_password": "brand new password"},
|
||||
)
|
||||
phone_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "body"),
|
||||
[("patch", {"is_active": False}), ("patch", {"password": "reset by admin!"}), ("delete", None)],
|
||||
)
|
||||
def test_admin_actions_close_user_sockets(client, make_user, second_client, method, body):
|
||||
make_user("boss", Role.ADMIN)
|
||||
anna_id = make_user("anna").id
|
||||
login(client, "boss")
|
||||
anna = second_client("anna")
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
ws.receive_json()
|
||||
if method == "patch":
|
||||
client.patch(f"/api/admin/users/{anna_id}", json=body)
|
||||
else:
|
||||
client.delete(f"/api/admin/users/{anna_id}")
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_heartbeat_and_revalidation(anna, db, monkeypatch):
|
||||
from app.models import UserSession
|
||||
|
||||
monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05)
|
||||
monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0)
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, connect(anna) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
# Session disappears behind the socket's back (e.g. CLI password reset)
|
||||
db.query(UserSession).delete()
|
||||
db.commit()
|
||||
while True:
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
assert exc.value.code == 4401
|
||||
@@ -18,6 +18,7 @@ exec uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port 8000 \
|
||||
--workers 1 \
|
||||
--ws-max-size 65536 \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}" \
|
||||
--log-level "${LOG_LEVEL:-info}"
|
||||
Reference in new issue
Block a user