diff --git a/backend/app/api/clips.py b/backend/app/api/clips.py new file mode 100644 index 0000000..1fe66d8 --- /dev/null +++ b/backend/app/api/clips.py @@ -0,0 +1,69 @@ +from typing import Annotated + +from fastapi import APIRouter, 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 + +router = APIRouter(prefix="/clips", tags=["clips"]) + +# Fields that may be null on purpose (clearing them); all others are ignored when null +_NULLABLE_FIELDS = {"title", "language"} + + +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) + if clip is None: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.") + return clip + + +@router.get("", response_model=ClipList) +def list_clips( + user: CurrentUser, + db: DbSession, + limit: Annotated[int, Query(ge=1, le=100)] = 50, + offset: Annotated[int, Query(ge=0)] = 0, +) -> ClipList: + items, total = clip_service.list_clips(db, user.id, limit, offset) + return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total) + + +@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()) + + +@router.get("/{clip_id}", response_model=ClipOut) +def get_clip(clip_id: int, user: CurrentUser, db: DbSession): + return _get_own_clip(db, user, clip_id) + + +@router.patch("/{clip_id}", response_model=ClipOut) +def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession): + clip = _get_own_clip(db, user, clip_id) + changes = { + field: getattr(body, field) + for field in body.model_fields_set - {"version"} + 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) + 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"), + }, + ) + + +@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None: + if not clip_service.delete_clip(db, user.id, clip_id): + raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.") diff --git a/backend/app/config.py b/backend/app/config.py index 662d627..531ba1a 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -26,6 +26,8 @@ class Settings(BaseSettings): # Only meaningful once the real client IP is known (FORWARDED_ALLOW_IPS set to the proxy) login_ip_lockout: bool = False + clip_max_chars: int = 200_000 + initial_admin_username: str | None = None initial_admin_password: str | None = None diff --git a/backend/app/main.py b/backend/app/main.py index b2a7e02..a0c6a77 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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, health +from app.api import admin, auth, clips, health from app.config import get_settings from app.db import _session_factory from app.middleware import ( @@ -110,6 +110,7 @@ def create_app() -> FastAPI: 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.exception_handler(UserError) def user_error_handler(_request: Request, exc: UserError) -> JSONResponse: diff --git a/backend/app/schemas/clips.py b/backend/app/schemas/clips.py new file mode 100644 index 0000000..271f081 --- /dev/null +++ b/backend/app/schemas/clips.py @@ -0,0 +1,46 @@ +from datetime import datetime + +from pydantic import BaseModel, ConfigDict, Field + +from app.models import ClipKind + +# Hard upper bound for request parsing; the configurable limit is enforced in the service +_CONTENT_MAX = 1_000_000 + + +class ClipCreate(BaseModel): + kind: ClipKind = ClipKind.TEXT + title: str | None = Field(default=None, max_length=1000) + content: str = Field(max_length=_CONTENT_MAX) + language: str | None = Field(default=None, max_length=32) + pinned: bool = False + + +class ClipUpdate(BaseModel): + """Partial update; only fields present in the request are changed.""" + + kind: ClipKind | None = None + title: str | None = Field(default=None, max_length=1000) + content: str | None = Field(default=None, max_length=_CONTENT_MAX) + language: str | None = Field(default=None, max_length=32) + pinned: bool | None = None + version: int | None = Field(default=None, description="Expected version for conflict check") + + +class ClipOut(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + kind: ClipKind + title: str | None + content: str + language: str | None + pinned: bool + version: int + created_at: datetime + updated_at: datetime + + +class ClipList(BaseModel): + items: list[ClipOut] + total: int diff --git a/backend/app/services/clips.py b/backend/app/services/clips.py new file mode 100644 index 0000000..9e5426d --- /dev/null +++ b/backend/app/services/clips.py @@ -0,0 +1,125 @@ +from typing import Any + +from sqlalchemy import delete, func, select, update +from sqlalchemy.orm import Session + +from app.config import get_settings +from app.languages import LANGUAGES +from app.models import Clip, ClipKind, utcnow +from app.services.users import UserError + +# Changing only these fields does not count as an edit (no new updated_at) +_META_FIELDS = frozenset({"pinned"}) + + +class ClipConflict(Exception): + """The clip was changed elsewhere since the client loaded it.""" + + def __init__(self, current: Clip) -> None: + super().__init__("clip version conflict") + self.current = current + + +def _normalize(kind: ClipKind, title: str | None, content: str, language: str | None): + max_chars = get_settings().clip_max_chars + if not content.strip(): + raise UserError("Der Inhalt darf nicht leer sein.") + if len(content) > max_chars: + raise UserError( + f"Der Inhalt ist zu lang (höchstens {max_chars:,} Zeichen).".replace(",", ".") + ) + title = (title or "").strip() or None + if title is not None and len(title) > 200: + raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).") + if kind == ClipKind.TEXT: + language = None + else: + language = language or "plaintext" + if language not in LANGUAGES: + raise UserError("Unbekannte Sprache.") + return title, language + + +def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]: + items = db.scalars( + select(Clip) + .where(Clip.user_id == user_id) + .order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc()) + .limit(limit) + .offset(offset) + ) + total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id)) + return list(items), total or 0 + + +def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None: + return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id)) + + +def create_clip( + db: Session, + user_id: int, + *, + content: str, + kind: ClipKind = ClipKind.TEXT, + title: str | None = None, + language: str | None = None, + pinned: bool = False, +) -> Clip: + title, language = _normalize(kind, title, content, language) + clip = Clip( + user_id=user_id, + kind=kind, + title=title, + content=content, + language=language, + pinned=pinned, + ) + db.add(clip) + db.commit() + return clip + + +def update_clip( + db: Session, + user_id: int, + clip: Clip, + changes: dict[str, Any], + expected_version: int | None = None, +) -> Clip: + """Apply a partial update. With expected_version, a concurrent change raises ClipConflict.""" + kind = changes.get("kind", clip.kind) + title = changes.get("title", clip.title) + content = changes.get("content", clip.content) + language = changes.get("language", clip.language) + title, language = _normalize(kind, title, content, language) + + values: dict[str, Any] = { + "kind": kind, + "title": title, + "content": content, + "language": language, + "pinned": changes.get("pinned", clip.pinned), + "version": Clip.version + 1, + } + if set(changes) - _META_FIELDS: + values["updated_at"] = utcnow() + + # Conditional UPDATE keeps the version check atomic across concurrent requests + stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id) + if expected_version is not None: + stmt = stmt.where(Clip.version == expected_version) + result = db.execute(stmt.values(**values).execution_options(synchronize_session=False)) + if result.rowcount == 0: + db.rollback() + db.refresh(clip) + raise ClipConflict(clip) + db.commit() + db.refresh(clip) + return clip + + +def delete_clip(db: Session, user_id: int, clip_id: int) -> bool: + result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id)) + db.commit() + return result.rowcount > 0 diff --git a/backend/tests/test_clips.py b/backend/tests/test_clips.py new file mode 100644 index 0000000..e186258 --- /dev/null +++ b/backend/tests/test_clips.py @@ -0,0 +1,234 @@ +from datetime import timedelta + +import pytest +from fastapi.testclient import TestClient + +from app.config import get_settings +from app.models import Clip, Role, utcnow +from tests.conftest import login + + +@pytest.fixture +def anna(client, make_user): + make_user("anna") + login(client, "anna") + return client + + +@pytest.fixture +def bert(client, make_user): + """Second logged-in user with own client, for data separation tests.""" + make_user("bert") + with TestClient(client.app, base_url="https://testserver") as other: + login(other, "bert") + yield other + + +def create(c, **fields): + response = c.post("/api/clips", json={"content": "hello", **fields}) + assert response.status_code == 201, response.text + return response.json() + + +# --- CRUD ----------------------------------------------------------------------- + + +def test_create_text_clip(anna): + clip = create(anna, content="Some text", title=" Note ") + + assert clip["kind"] == "text" + assert clip["title"] == "Note" + assert clip["language"] is None + assert clip["pinned"] is False + assert clip["version"] == 1 + + +def test_create_code_clip_defaults_to_plaintext(anna): + assert create(anna, kind="code")["language"] == "plaintext" + assert create(anna, kind="code", language="python")["language"] == "python" + + +def test_text_clip_drops_language(anna): + assert create(anna, kind="text", language="python")["language"] is None + + +@pytest.mark.parametrize( + "fields", + [ + {"content": " "}, + {"content": "x", "kind": "code", "language": "brainfuck"}, + {"content": "x", "title": "t" * 201}, + {"content": "x", "kind": "image"}, + ], +) +def test_create_validation(anna, fields): + assert anna.post("/api/clips", json=fields).status_code in (400, 422) + + +def test_content_limit_is_configurable(anna, monkeypatch): + monkeypatch.setenv("CLIP_MAX_CHARS", "10") + get_settings.cache_clear() + + assert anna.post("/api/clips", json={"content": "x" * 10}).status_code == 201 + response = anna.post("/api/clips", json={"content": "x" * 11}) + assert response.status_code == 400 + assert "zu lang" in response.json()["detail"] + + +def test_list_orders_pinned_first_then_recent(anna, db): + old = create(anna, content="old") + pinned = create(anna, content="pinned", pinned=True) + new = create(anna, content="new") + db.query(Clip).filter_by(id=old["id"]).update({Clip.updated_at: utcnow() - timedelta(days=1)}) + db.commit() + + data = anna.get("/api/clips").json() + + assert [c["id"] for c in data["items"]] == [pinned["id"], new["id"], old["id"]] + assert data["total"] == 3 + + +def test_list_pagination(anna): + for i in range(5): + create(anna, content=f"clip {i}") + + page = anna.get("/api/clips", params={"limit": 2, "offset": 2}).json() + + assert len(page["items"]) == 2 + assert page["total"] == 5 + assert anna.get("/api/clips", params={"limit": 101}).status_code == 422 + + +def test_get_update_delete(anna): + clip = create(anna) + + assert anna.get(f"/api/clips/{clip['id']}").json()["content"] == "hello" + + updated = anna.patch( + f"/api/clips/{clip['id']}", + json={"content": "print(1)", "kind": "code", "language": "python"}, + ).json() + assert updated["content"] == "print(1)" + assert updated["language"] == "python" + assert updated["version"] == 2 + + assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204 + assert anna.get(f"/api/clips/{clip['id']}").status_code == 404 + + +def test_patch_only_changes_given_fields(anna): + clip = create(anna, title="Keep", kind="code", language="go") + + updated = anna.patch(f"/api/clips/{clip['id']}", json={"content": "new"}).json() + + assert updated["title"] == "Keep" + assert updated["language"] == "go" + + +def test_patch_can_clear_title(anna): + clip = create(anna, title="Remove me") + + assert anna.patch(f"/api/clips/{clip['id']}", json={"title": None}).json()["title"] is None + + +def test_pinning_does_not_count_as_edit(anna): + clip = create(anna) + + pinned = anna.patch(f"/api/clips/{clip['id']}", json={"pinned": True}).json() + + assert pinned["pinned"] is True + assert pinned["updated_at"] == clip["updated_at"] + assert pinned["version"] == 2 + + +def test_version_conflict(anna): + clip = create(anna) + anna.patch(f"/api/clips/{clip['id']}", json={"content": "from phone", "version": 1}) + + response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "from laptop", "version": 1}) + + assert response.status_code == 409 + assert response.json()["current"]["content"] == "from phone" + assert response.json()["current"]["version"] == 2 + assert anna.get(f"/api/clips/{clip['id']}").json()["content"] == "from phone" + + +def test_update_without_version_overwrites(anna): + clip = create(anna) + anna.patch(f"/api/clips/{clip['id']}", json={"content": "first"}) + + response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "second"}) + + assert response.status_code == 200 + assert response.json()["version"] == 3 + + +def test_clips_require_login(client): + assert client.get("/api/clips").status_code == 401 + assert client.post("/api/clips", json={"content": "x"}).status_code == 401 + + +def test_clip_changes_require_csrf(anna): + clip = create(anna) + del anna.headers["X-CSRF-Token"] + + assert anna.post("/api/clips", json={"content": "x"}).status_code == 403 + assert anna.patch(f"/api/clips/{clip['id']}", json={"pinned": True}).status_code == 403 + assert anna.delete(f"/api/clips/{clip['id']}").status_code == 403 + + +# --- Data separation ------------------------------------------------------------ + + +def test_list_only_shows_own_clips(anna, bert): + create(anna, content="anna's secret") + create(bert, content="bert's clip") + + anna_items = anna.get("/api/clips").json() + bert_items = bert.get("/api/clips").json() + + assert [c["content"] for c in anna_items["items"]] == ["anna's secret"] + assert [c["content"] for c in bert_items["items"]] == ["bert's clip"] + assert anna_items["total"] == bert_items["total"] == 1 + + +def test_foreign_clip_is_indistinguishable_from_missing(anna, bert): + clip_id = create(anna, content="anna's secret")["id"] + + for response in ( + bert.get(f"/api/clips/{clip_id}"), + bert.patch(f"/api/clips/{clip_id}", json={"content": "hacked"}), + bert.delete(f"/api/clips/{clip_id}"), + ): + assert response.status_code == 404 + assert response.json() == bert.get("/api/clips/999999").json() + + assert anna.get(f"/api/clips/{clip_id}").json()["content"] == "anna's secret" + + +def test_admin_cannot_read_other_users_clips(client, make_user): + make_user("boss", Role.ADMIN) + make_user("anna") + login(client, "anna") + clip_id = create(client, content="private")["id"] + client.post("/api/auth/logout") + + login(client, "boss") + + assert client.get(f"/api/clips/{clip_id}").status_code == 404 + assert client.get("/api/clips").json()["total"] == 0 + + +def test_deleting_user_deletes_their_clips(client, make_user, db): + make_user("boss", Role.ADMIN) + anna = make_user("anna") + anna_id = anna.id + with TestClient(client.app, base_url="https://testserver") as anna_client: + login(anna_client, "anna") + create(anna_client, content="bye") + + login(client, "boss") + client.delete(f"/api/admin/users/{anna_id}") + + db.expire_all() + assert db.query(Clip).filter_by(user_id=anna_id).count() == 0