feat: api-tokens pro gerät (backend)
Tokens werden einmal angezeigt und nur gehasht gespeichert. Anmeldung per Authorization: Bearer für Clips, Dateien, Projektliste/-anlage und den Live-Sync (WebSocket ohne Origin). Konto, Admin, Sessions, Tokens und Projektverwaltung bleiben der Browser-Session vorbehalten. Widerruf schließt die Verbindungen des Tokens sofort. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4ae459cf53
commit
d8377c8a04
14 files changed
+520
-32
No files matched your search
@@ -3,7 +3,7 @@ from typing import Annotated
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
@@ -23,7 +23,7 @@ def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
def _get_visible_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
def _get_visible_clip(db: DbSession, user: ApiUser, clip_id: int) -> Clip:
|
||||
# Invisible and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
@@ -33,7 +33,7 @@ def _get_visible_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
|
||||
@router.get("", response_model=ClipList)
|
||||
def list_clips(
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
@@ -48,7 +48,7 @@ def list_clips(
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||
def create_clip(body: ClipCreate, user: ApiUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
notify(
|
||||
background,
|
||||
@@ -60,7 +60,7 @@ def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background:
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
def get_clip(clip_id: int, user: ApiUser, db: DbSession):
|
||||
return _get_visible_clip(db, user, clip_id)
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
def update_clip(
|
||||
clip_id: int,
|
||||
body: ClipUpdate,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
@@ -97,9 +97,7 @@ def update_clip(
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(
|
||||
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
def delete_clip(clip_id: int, user: ApiUser, db: DbSession, background: BackgroundTasks) -> None:
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
clip_service.delete_clip(db, user.id, clip)
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.db import get_db
|
||||
from app.middleware import SAFE_METHODS
|
||||
from app.models import User, UserSession
|
||||
from app.services.sessions import resolve_session
|
||||
from app.services.tokens import resolve_token
|
||||
|
||||
SESSION_COOKIE = "lc_session"
|
||||
CSRF_COOKIE = "lc_csrf"
|
||||
@@ -37,6 +38,28 @@ def get_current_user(session: CurrentSession) -> User:
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
|
||||
|
||||
def bearer_token(authorization: str | None) -> str | None:
|
||||
if authorization and authorization[:7].lower() == "bearer ":
|
||||
return authorization[7:].strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_api_user(request: Request, db: DbSession) -> User:
|
||||
"""Session or device token (Authorization: Bearer). Only for the endpoints the desktop
|
||||
agent needs; admin, password, sessions and token management stay session-only."""
|
||||
plain = bearer_token(request.headers.get("authorization"))
|
||||
if plain is None:
|
||||
return get_current_session(request, db).user
|
||||
token = resolve_token(db, plain, client_ip(request))
|
||||
if token is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token ungültig oder widerrufen.")
|
||||
# No CSRF check: browsers never attach this header on their own
|
||||
return token.user
|
||||
|
||||
|
||||
ApiUser = Annotated[User, Depends(get_api_user)]
|
||||
|
||||
|
||||
def require_admin(user: CurrentUser) -> User:
|
||||
if not user.is_admin:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Nur für Administratoren.")
|
||||
|
||||
@@ -4,7 +4,7 @@ from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, s
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.config import get_settings
|
||||
from app.schemas.clips import ClipOut
|
||||
@@ -32,7 +32,7 @@ class ExpiryUpdate(BaseModel):
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
async def upload(
|
||||
request: Request,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
name: Annotated[str, Query(max_length=1000)],
|
||||
@@ -62,7 +62,7 @@ async def upload(
|
||||
|
||||
|
||||
@router.get("/usage", response_model=Usage)
|
||||
def usage(user: CurrentUser, db: DbSession) -> Usage:
|
||||
def usage(user: ApiUser, db: DbSession) -> Usage:
|
||||
settings = get_settings()
|
||||
return Usage(
|
||||
used_bytes=file_service.used_bytes(db, user.id),
|
||||
@@ -72,7 +72,7 @@ def usage(user: CurrentUser, db: DbSession) -> Usage:
|
||||
|
||||
|
||||
@router.get("/{clip_id}")
|
||||
def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = False):
|
||||
def download(clip_id: int, user: ApiUser, db: DbSession, inline: bool = False):
|
||||
stored = file_service.get_file(db, user.id, clip_id)
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
path = None if stored is None else file_service.file_path(stored.user_id, stored.storage_name)
|
||||
@@ -95,7 +95,7 @@ def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = Fals
|
||||
def update_expiry(
|
||||
clip_id: int,
|
||||
body: ExpiryUpdate,
|
||||
user: CurrentUser,
|
||||
user: ApiUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
|
||||
@@ -2,7 +2,7 @@ from collections.abc import Iterable
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Project
|
||||
from app.schemas.projects import (
|
||||
@@ -17,6 +17,8 @@ from app.services import projects as project_service
|
||||
from app.services.access import project_audience
|
||||
from app.services.projects import ProjectView
|
||||
|
||||
# Device tokens may list and create projects (the agent sets up its own); managing
|
||||
# projects and members needs a browser session
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
@@ -65,13 +67,13 @@ def _notify_project(
|
||||
|
||||
|
||||
@router.get("", response_model=list[ProjectOut])
|
||||
def list_projects(user: CurrentUser, db: DbSession) -> list[ProjectOut]:
|
||||
def list_projects(user: ApiUser, db: DbSession) -> list[ProjectOut]:
|
||||
return [_out(view) for view in project_service.list_projects(db, user.id)]
|
||||
|
||||
|
||||
@router.post("", response_model=ProjectOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_project(
|
||||
body: ProjectCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
body: ProjectCreate, user: ApiUser, db: DbSession, background: BackgroundTasks
|
||||
) -> ProjectOut:
|
||||
project = project_service.create_project(db, user.id, **body.model_dump())
|
||||
out = _out(_view(db, user, project.id))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.services import tokens as token_service
|
||||
from app.ws.hub import hub
|
||||
|
||||
# Session only: a device token must not be able to create or list tokens
|
||||
router = APIRouter(prefix="/tokens", tags=["tokens"])
|
||||
|
||||
|
||||
class TokenCreate(BaseModel):
|
||||
name: str = Field(max_length=1000)
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
prefix: str
|
||||
created_at: datetime
|
||||
last_used_at: datetime | None
|
||||
last_ip: str | None
|
||||
|
||||
|
||||
class TokenCreated(TokenOut):
|
||||
token: str = Field(description="Shown only once")
|
||||
|
||||
|
||||
@router.get("", response_model=list[TokenOut])
|
||||
def list_tokens(user: CurrentUser, db: DbSession):
|
||||
return token_service.list_tokens(db, user.id)
|
||||
|
||||
|
||||
@router.post("", response_model=TokenCreated, status_code=status.HTTP_201_CREATED)
|
||||
def create_token(body: TokenCreate, user: CurrentUser, db: DbSession) -> TokenCreated:
|
||||
token, plain = token_service.create_token(db, user.id, body.name)
|
||||
return TokenCreated(**TokenOut.model_validate(token).model_dump(), token=plain)
|
||||
|
||||
|
||||
@router.delete("/{token_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def revoke_token(
|
||||
token_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not token_service.revoke_token(db, user.id, token_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Token nicht gefunden.")
|
||||
background.add_task(hub.close_token, token_id)
|
||||
@@ -2,7 +2,7 @@ from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.deps import ApiUser, DbSession
|
||||
from app.models import User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
@@ -14,7 +14,7 @@ class UserName(BaseModel):
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserName])
|
||||
def list_user_names(user: CurrentUser, db: DbSession) -> list[UserName]:
|
||||
def list_user_names(user: ApiUser, db: DbSession) -> list[UserName]:
|
||||
"""Names of the other active users, for sharing projects; nothing else is revealed."""
|
||||
rows = db.execute(
|
||||
select(User.id, User.username)
|
||||
|
||||
+32
-11
@@ -4,10 +4,11 @@ import time
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
|
||||
from app.api.deps import SESSION_COOKIE
|
||||
from app.api.deps import SESSION_COOKIE, bearer_token
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.services.sessions import is_session_valid, resolve_session
|
||||
from app.services.tokens import is_token_valid, resolve_token
|
||||
from app.ws.hub import CLOSE_UNAUTHORIZED, Connection, hub
|
||||
|
||||
router = APIRouter()
|
||||
@@ -18,15 +19,23 @@ REVALIDATE_INTERVAL_SECONDS = 300
|
||||
CLOSE_TOO_MANY = 4429
|
||||
|
||||
|
||||
def _resolve(token: str | None) -> tuple[int, int] | None:
|
||||
def _resolve_session(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:
|
||||
def _resolve_token(plain: str, ip: str | None) -> tuple[int, int] | None:
|
||||
with _session_factory()() as db:
|
||||
return is_session_valid(db, session_id)
|
||||
token = resolve_token(db, plain, ip)
|
||||
return (token.id, token.user_id) if token else None
|
||||
|
||||
|
||||
def _still_valid(conn: Connection) -> bool:
|
||||
with _session_factory()() as db:
|
||||
if conn.token_id is not None:
|
||||
return is_token_valid(db, conn.token_id)
|
||||
return conn.session_id is not None and is_session_valid(db, conn.session_id)
|
||||
|
||||
|
||||
async def _heartbeat(conn: Connection) -> None:
|
||||
@@ -37,7 +46,7 @@ async def _heartbeat(conn: Connection) -> None:
|
||||
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):
|
||||
if not await run_in_threadpool(_still_valid, conn):
|
||||
await conn.websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
|
||||
@@ -50,24 +59,36 @@ async def _drain(conn: Connection) -> None:
|
||||
|
||||
@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:
|
||||
plain = bearer_token(websocket.headers.get("authorization"))
|
||||
origin = websocket.headers.get("origin")
|
||||
# Origin check protects the cookie-authenticated socket against cross-site hijacking.
|
||||
# The desktop agent sends a token and no Origin; browsers always send Origin and
|
||||
# cannot set an Authorization header on WebSockets.
|
||||
origin_ok = (origin or "").rstrip("/") in get_settings().allowed_origin_list
|
||||
if not origin_ok and not (plain is not None and origin is None):
|
||||
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))
|
||||
ip = websocket.client.host if websocket.client else None
|
||||
if plain is not None:
|
||||
ids = await run_in_threadpool(_resolve_token, plain, ip)
|
||||
else:
|
||||
ids = await run_in_threadpool(_resolve_session, websocket.cookies.get(SESSION_COOKIE))
|
||||
if ids is None:
|
||||
await websocket.close(code=CLOSE_UNAUTHORIZED)
|
||||
return
|
||||
session_id, user_id = ids
|
||||
credential_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)
|
||||
conn = (
|
||||
Connection(websocket=websocket, user_id=user_id, token_id=credential_id)
|
||||
if plain is not None
|
||||
else Connection(websocket=websocket, user_id=user_id, session_id=credential_id)
|
||||
)
|
||||
hub.add(conn)
|
||||
try:
|
||||
await websocket.send_json({"type": "hello"})
|
||||
|
||||
Reference in new issue
Block a user