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
@@ -0,0 +1,43 @@
|
||||
"""api tokens
|
||||
|
||||
Revision ID: 0007
|
||||
Revises: 0006
|
||||
Create Date: 2026-10-25 14:49:30.200128
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "0007"
|
||||
down_revision: str | None = "0006"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"api_tokens",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("token_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("prefix", sa.String(length=16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("last_used_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("last_ip", sa.String(length=45), nullable=True),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("token_hash"),
|
||||
)
|
||||
with op.batch_alter_table("api_tokens", schema=None) as batch_op:
|
||||
batch_op.create_index("ix_api_tokens_user", ["user_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("api_tokens", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_api_tokens_user")
|
||||
|
||||
op.drop_table("api_tokens")
|
||||
@@ -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"})
|
||||
|
||||
+2
-1
@@ -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, files, health, projects, users, ws
|
||||
from app.api import admin, auth, clips, files, health, projects, tokens, users, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -151,6 +151,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(projects.router, prefix="/api")
|
||||
app.include_router(files.router, prefix="/api")
|
||||
app.include_router(users.router, prefix="/api")
|
||||
app.include_router(tokens.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from app.models.api_token import ApiToken
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.file import StoredFile
|
||||
@@ -8,6 +9,7 @@ from app.models.session import UserSession
|
||||
from app.models.user import Role, User
|
||||
|
||||
__all__ = [
|
||||
"ApiToken",
|
||||
"Base",
|
||||
"Clip",
|
||||
"ClipKind",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class ApiToken(Base):
|
||||
"""Per-device token for the desktop agent and scripts; only its hash is stored."""
|
||||
|
||||
__tablename__ = "api_tokens"
|
||||
__table_args__ = (Index("ix_api_tokens_user", "user_id"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
# First characters of the token, so the user can tell tokens apart
|
||||
prefix: Mapped[str] = mapped_column(String(16))
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
|
||||
last_ip: Mapped[str | None] = mapped_column(String(45))
|
||||
|
||||
user: Mapped[User] = relationship(lazy="joined")
|
||||
@@ -0,0 +1,80 @@
|
||||
import secrets
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import ApiToken, utcnow
|
||||
from app.security import hash_token
|
||||
from app.services.sessions import TOUCH_INTERVAL
|
||||
from app.services.users import UserError
|
||||
|
||||
TOKEN_PREFIX = "lc_" # noqa: S105 - public marker, not a secret
|
||||
SHOWN_PREFIX_LENGTH = 10
|
||||
NAME_MAX_LENGTH = 100
|
||||
MAX_TOKENS_PER_USER = 50
|
||||
|
||||
|
||||
def create_token(db: Session, user_id: int, name: str) -> tuple[ApiToken, str]:
|
||||
"""Create a token; the plain value is returned once and never stored."""
|
||||
name = " ".join(name.split())
|
||||
if not name:
|
||||
raise UserError("Bitte einen Namen für das Gerät angeben.")
|
||||
if len(name) > NAME_MAX_LENGTH:
|
||||
raise UserError(f"Der Name ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
|
||||
if any(unicodedata.category(ch).startswith("C") for ch in name):
|
||||
raise UserError("Der Name enthält ungültige Zeichen.")
|
||||
count = db.scalar(select(func.count(ApiToken.id)).where(ApiToken.user_id == user_id))
|
||||
if (count or 0) >= MAX_TOKENS_PER_USER:
|
||||
raise UserError(f"Höchstens {MAX_TOKENS_PER_USER} Tokens möglich.")
|
||||
|
||||
plain = TOKEN_PREFIX + secrets.token_urlsafe(32)
|
||||
token = ApiToken(
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
token_hash=hash_token(plain),
|
||||
prefix=plain[:SHOWN_PREFIX_LENGTH],
|
||||
)
|
||||
db.add(token)
|
||||
db.commit()
|
||||
return token, plain
|
||||
|
||||
|
||||
def list_tokens(db: Session, user_id: int) -> list[ApiToken]:
|
||||
return list(
|
||||
db.scalars(
|
||||
select(ApiToken).where(ApiToken.user_id == user_id).order_by(ApiToken.created_at)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def revoke_token(db: Session, user_id: int, token_id: int) -> bool:
|
||||
result = db.execute(
|
||||
delete(ApiToken).where(ApiToken.id == token_id, ApiToken.user_id == user_id)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def resolve_token(db: Session, plain: str | None, ip: str | None = None) -> ApiToken | None:
|
||||
"""The token for a raw value if valid (owner active); records when it was last used."""
|
||||
if not plain or not plain.startswith(TOKEN_PREFIX):
|
||||
return None
|
||||
token = db.scalar(select(ApiToken).where(ApiToken.token_hash == hash_token(plain)))
|
||||
if token is None or not token.user.is_active:
|
||||
return None
|
||||
now = utcnow()
|
||||
if (
|
||||
token.last_used_at is None
|
||||
or now - token.last_used_at >= TOUCH_INTERVAL
|
||||
or (ip is not None and ip != token.last_ip)
|
||||
):
|
||||
token.last_used_at = now
|
||||
token.last_ip = ip
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
def is_token_valid(db: Session, token_id: int) -> bool:
|
||||
token = db.get(ApiToken, token_id)
|
||||
return token is not None and token.user.is_active
|
||||
@@ -23,7 +23,9 @@ CLOSE_UNAUTHORIZED = 4401
|
||||
class Connection:
|
||||
websocket: WebSocket
|
||||
user_id: int
|
||||
session_id: int
|
||||
# Exactly one of these: browser session or device token
|
||||
session_id: int | None = None
|
||||
token_id: int | None = None
|
||||
|
||||
|
||||
class Hub:
|
||||
@@ -57,6 +59,9 @@ class Hub:
|
||||
async def close_session(self, session_id: int) -> None:
|
||||
await self._close_where(lambda c: c.session_id == session_id)
|
||||
|
||||
async def close_token(self, token_id: int) -> None:
|
||||
await self._close_where(lambda c: c.token_id == token_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
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from app.api import ws as ws_module
|
||||
from app.models import ApiToken, Role, User
|
||||
from tests.conftest import login
|
||||
from tests.test_ws import connect
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anna(client, make_user):
|
||||
make_user("anna")
|
||||
login(client, "anna")
|
||||
return client
|
||||
|
||||
|
||||
def create_token(c, name="Laptop"):
|
||||
response = c.post("/api/tokens", json={"name": name})
|
||||
assert response.status_code == 201, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agent(anna):
|
||||
"""A client without cookies that authenticates with a device token only."""
|
||||
token = create_token(anna)["token"]
|
||||
with TestClient(anna.app, base_url="https://testserver") as c:
|
||||
c.headers["Authorization"] = f"Bearer {token}"
|
||||
yield c
|
||||
|
||||
|
||||
def ws_with_token(c, token, origin=None):
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
if origin:
|
||||
headers["Origin"] = origin
|
||||
return c.websocket_connect("/api/ws", headers=headers)
|
||||
|
||||
|
||||
# --- Managing tokens ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_create_token_shows_value_once(anna):
|
||||
created = create_token(anna, " Arbeits Laptop ")
|
||||
|
||||
assert created["name"] == "Arbeits Laptop"
|
||||
assert created["token"].startswith("lc_")
|
||||
assert len(created["token"]) > 40
|
||||
assert created["prefix"] == created["token"][:10]
|
||||
assert created["last_used_at"] is None
|
||||
listed = anna.get("/api/tokens").json()
|
||||
assert [t["name"] for t in listed] == ["Arbeits Laptop"]
|
||||
assert "token" not in listed[0]
|
||||
|
||||
|
||||
def test_only_the_hash_is_stored(anna, db):
|
||||
plain = create_token(anna)["token"]
|
||||
stored = db.query(ApiToken).one()
|
||||
assert plain not in (stored.token_hash, stored.prefix)
|
||||
assert len(stored.token_hash) == 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", " ", "x" * 101, "bad\x00name"])
|
||||
def test_token_name_validation(anna, name):
|
||||
assert anna.post("/api/tokens", json={"name": name}).status_code == 400
|
||||
|
||||
|
||||
def test_token_limit(anna, monkeypatch):
|
||||
monkeypatch.setattr("app.services.tokens.MAX_TOKENS_PER_USER", 1)
|
||||
create_token(anna)
|
||||
assert anna.post("/api/tokens", json={"name": "second"}).status_code == 400
|
||||
|
||||
|
||||
def test_tokens_of_other_users_are_invisible(anna, client, make_user):
|
||||
token = create_token(anna)
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||
login(bert, "bert")
|
||||
assert bert.get("/api/tokens").json() == []
|
||||
assert bert.delete(f"/api/tokens/{token['id']}").status_code == 404
|
||||
assert len(anna.get("/api/tokens").json()) == 1
|
||||
|
||||
|
||||
# --- Using tokens ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_token_works_without_cookie_or_csrf(agent):
|
||||
assert agent.cookies.get("lc_session") is None
|
||||
created = agent.post("/api/clips", json={"content": "from agent"})
|
||||
assert created.status_code == 201
|
||||
assert agent.get("/api/clips").json()["items"][0]["content"] == "from agent"
|
||||
assert (
|
||||
agent.patch(f"/api/clips/{created.json()['id']}", json={"pinned": True}).status_code == 200
|
||||
)
|
||||
assert agent.post("/api/files", params={"name": "a.txt"}, content=b"data").status_code == 201
|
||||
assert agent.get("/api/projects").status_code == 200
|
||||
assert agent.post("/api/projects", json={"name": "Zwischenablage"}).status_code == 201
|
||||
|
||||
|
||||
def test_token_records_last_use(anna, agent):
|
||||
agent.get("/api/clips")
|
||||
token = anna.get("/api/tokens").json()[0]
|
||||
assert token["last_used_at"] is not None
|
||||
assert token["last_ip"] == "testclient"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path", "body"),
|
||||
[
|
||||
("GET", "/api/auth/me", None),
|
||||
("GET", "/api/auth/sessions", None),
|
||||
("POST", "/api/auth/password", {"current_password": "x", "new_password": "y" * 12}),
|
||||
("GET", "/api/tokens", None),
|
||||
("POST", "/api/tokens", {"name": "more"}),
|
||||
("GET", "/api/admin/users", None),
|
||||
("PATCH", "/api/projects/1", {"name": "x"}),
|
||||
("DELETE", "/api/projects/1", None),
|
||||
("POST", "/api/projects/1/members", {"username": "x"}),
|
||||
],
|
||||
)
|
||||
def test_token_cannot_reach_account_admin_or_project_management(agent, method, path, body):
|
||||
assert agent.request(method, path, json=body).status_code == 401
|
||||
|
||||
|
||||
def test_admin_token_cannot_use_admin_api(client, make_user):
|
||||
make_user("root", role=Role.ADMIN)
|
||||
login(client, "root")
|
||||
token = create_token(client)["token"]
|
||||
with TestClient(client.app, base_url="https://testserver") as c:
|
||||
response = c.get("/api/admin/users", headers={"Authorization": f"Bearer {token}"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["lc_wrong", "not-a-token", "", "Bearer"])
|
||||
def test_invalid_tokens(client, value):
|
||||
response = client.get("/api/clips", headers={"Authorization": f"Bearer {value}"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_revoked_token_stops_working(anna, agent):
|
||||
token_id = anna.get("/api/tokens").json()[0]["id"]
|
||||
assert anna.delete(f"/api/tokens/{token_id}").status_code == 204
|
||||
assert agent.get("/api/clips").status_code == 401
|
||||
assert anna.delete(f"/api/tokens/{token_id}").status_code == 404
|
||||
|
||||
|
||||
def test_tokens_of_deactivated_or_deleted_users(anna, agent, db):
|
||||
user = db.query(User).filter_by(username="anna").one()
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
assert agent.get("/api/clips").status_code == 401
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
assert db.query(ApiToken).count() == 0
|
||||
|
||||
|
||||
def test_token_respects_data_separation(anna, client, make_user):
|
||||
secret = anna.post("/api/clips", json={"content": "anna only"}).json()
|
||||
make_user("bert")
|
||||
with TestClient(client.app, base_url="https://testserver") as bert:
|
||||
login(bert, "bert")
|
||||
token = create_token(bert)["token"]
|
||||
bert.cookies.clear()
|
||||
bert.headers["Authorization"] = f"Bearer {token}"
|
||||
assert bert.get("/api/clips").json()["items"] == []
|
||||
assert bert.get(f"/api/clips/{secret['id']}").status_code == 404
|
||||
assert bert.delete(f"/api/clips/{secret['id']}").status_code == 404
|
||||
|
||||
|
||||
# --- WebSocket ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_websocket_with_token_and_without_origin(anna):
|
||||
token = create_token(anna)["token"]
|
||||
with ws_with_token(anna, token) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
anna.post("/api/clips", json={"content": "to the agent"})
|
||||
event = ws.receive_json()
|
||||
assert (event["type"], event["data"]["content"]) == ("clip.created", "to the agent")
|
||||
|
||||
|
||||
def test_websocket_token_with_foreign_origin_is_rejected(anna):
|
||||
token = create_token(anna)["token"]
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as exc,
|
||||
ws_with_token(anna, token, "https://evil.example") as ws,
|
||||
):
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4403
|
||||
|
||||
|
||||
def test_websocket_invalid_token_is_4401(client):
|
||||
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(client, "lc_nope") as ws:
|
||||
ws.receive_json()
|
||||
ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
|
||||
def test_revoking_token_closes_its_socket_only(anna):
|
||||
laptop = create_token(anna, "Laptop")
|
||||
desktop = create_token(anna, "Desktop")
|
||||
|
||||
with ws_with_token(anna, desktop["token"]) as desktop_ws, connect(anna) as browser_ws:
|
||||
desktop_ws.receive_json()
|
||||
browser_ws.receive_json()
|
||||
with (
|
||||
pytest.raises(WebSocketDisconnect) as exc,
|
||||
ws_with_token(anna, laptop["token"]) as laptop_ws,
|
||||
):
|
||||
laptop_ws.receive_json()
|
||||
anna.delete(f"/api/tokens/{laptop['id']}")
|
||||
laptop_ws.receive_json()
|
||||
assert exc.value.code == 4401
|
||||
|
||||
anna.post("/api/clips", json={"content": "still live"})
|
||||
assert desktop_ws.receive_json()["type"] == "clip.created"
|
||||
assert browser_ws.receive_json()["type"] == "clip.created"
|
||||
|
||||
|
||||
def test_token_socket_is_revalidated(anna, db, monkeypatch):
|
||||
monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05)
|
||||
monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0)
|
||||
token = create_token(anna)["token"]
|
||||
|
||||
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(anna, token) as ws:
|
||||
assert ws.receive_json() == {"type": "hello"}
|
||||
db.query(User).filter_by(username="anna").one().is_active = False
|
||||
db.commit()
|
||||
while True:
|
||||
assert ws.receive_json() == {"type": "ping"}
|
||||
assert exc.value.code == 4401
|
||||
Reference in new issue
Block a user