feat: dateiaustausch im backend

Dateien als Clip-Art "file": gestreamter Upload mit Größengrenze, Kontingent
pro Benutzer und Mindestreserve an freiem Speicher. Download immer als
Anhang mit sandbox-CSP, Vorschau nur für geprüfte JPEG/PNG/GIF/WebP.
Ablauf nach 1/7/30 Tagen oder nie; der Aufräumjob löscht abgelaufene und
verwaiste Dateien.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 14:01:10 +01:00
1 parent ae334d2248
commit 52a8fd019f
12 files changed
+1027 -11

No files matched your search

@@ -0,0 +1,52 @@
"""files
Revision ID: 0005
Revises: 0004
Create Date: 2026-10-25 13:57:03.762901
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0005"
down_revision: str | None = "0004"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
op.create_table(
"files",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("clip_id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("storage_name", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("content_type", sa.String(length=127), nullable=False),
sa.Column("size", sa.BigInteger(), nullable=False),
sa.Column("sha256", sa.String(length=64), nullable=False),
sa.Column("previewable", sa.Boolean(), nullable=False),
sa.Column("expires_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["clip_id"], ["clips.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("clip_id"),
sa.UniqueConstraint("storage_name"),
)
with op.batch_alter_table("files", schema=None) as batch_op:
batch_op.create_index("ix_files_expires_at", ["expires_at"], unique=False)
batch_op.create_index("ix_files_user", ["user_id"], unique=False)
def downgrade() -> None:
# File clips cannot exist without their table; the files on disk stay as orphans
op.execute("DELETE FROM clips WHERE kind = 'file'")
with op.batch_alter_table("files", schema=None) as batch_op:
batch_op.drop_index("ix_files_user")
batch_op.drop_index("ix_files_expires_at")
op.drop_table("files")
+109
View File
@@ -0,0 +1,109 @@
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, status
from fastapi.responses import FileResponse
from pydantic import BaseModel
from app.api.deps import CurrentUser, DbSession
from app.config import get_settings
from app.schemas.clips import ClipOut
from app.services import clips as clip_service
from app.services import files as file_service
from app.ws.hub import hub
router = APIRouter(prefix="/files", tags=["files"])
UPLOAD_PATH = "/api/files"
# A downloaded file must never run as a page of this origin
_DOWNLOAD_CSP = "default-src 'none'; sandbox"
class Usage(BaseModel):
used_bytes: int
quota_bytes: int
max_file_bytes: int
class ExpiryUpdate(BaseModel):
expires_days: int
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
async def upload(
request: Request,
user: CurrentUser,
db: DbSession,
background: BackgroundTasks,
name: Annotated[str, Query(max_length=1000)],
expires_days: int = 7,
project_id: int | None = None,
title: Annotated[str | None, Query(max_length=1000)] = None,
):
"""Raw file body (not multipart), streamed to disk; metadata in the query string."""
length = request.headers.get("content-length", "")
if not length.isdigit():
raise HTTPException(status.HTTP_411_LENGTH_REQUIRED, "Content-Length fehlt.")
clip = await file_service.store_upload(
db,
user.id,
request.stream(),
name=name,
size=int(length),
content_type=request.headers.get("content-type"),
expires_days=expires_days,
project_id=project_id,
title=title,
)
out = ClipOut.model_validate(clip)
_notify(background, user.id, "clip.created", out.model_dump(mode="json"))
return out
@router.get("/usage", response_model=Usage)
def usage(user: CurrentUser, db: DbSession) -> Usage:
settings = get_settings()
return Usage(
used_bytes=file_service.used_bytes(db, user.id),
quota_bytes=settings.file_quota_bytes,
max_file_bytes=settings.file_max_bytes,
)
@router.get("/{clip_id}")
def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = False):
stored = file_service.get_file(db, user.id, clip_id)
path = None if stored is None else file_service.file_path(user.id, stored.storage_name)
if stored is None or path is None or not path.is_file():
raise HTTPException(status.HTTP_404_NOT_FOUND, "Datei nicht gefunden.")
# Only verified images may be shown in the browser; everything else is a download
show_inline = inline and stored.previewable
return FileResponse(
path,
media_type=stored.content_type,
headers={
"Content-Disposition": file_service.content_disposition(stored.name, show_inline),
"Content-Security-Policy": _DOWNLOAD_CSP,
"Cache-Control": "private, no-cache",
},
)
@router.patch("/{clip_id}", response_model=ClipOut)
def update_expiry(
clip_id: int,
body: ExpiryUpdate,
user: CurrentUser,
db: DbSession,
background: BackgroundTasks,
):
clip = clip_service.get_clip(db, user.id, clip_id)
if clip is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
clip = file_service.set_expiry(db, user.id, clip, body.expires_days)
out = ClipOut.model_validate(clip)
_notify(background, user.id, "clip.updated", out.model_dump(mode="json"))
return out
+9
View File
@@ -30,6 +30,11 @@ class Settings(BaseSettings):
clip_max_chars: int = 200_000 clip_max_chars: int = 200_000
file_max_bytes: int = 100 * 1024 * 1024
file_quota_bytes: int = 1024 * 1024 * 1024
# Uploads are refused when the disk would drop below this; the server is shared
file_min_free_bytes: int = 2 * 1024 * 1024 * 1024
initial_admin_username: str | None = None initial_admin_username: str | None = None
initial_admin_password: str | None = None initial_admin_password: str | None = None
@@ -37,6 +42,10 @@ class Settings(BaseSettings):
def database_url(self) -> str: def database_url(self) -> str:
return f"sqlite:///{self.data_dir / 'app.db'}" return f"sqlite:///{self.data_dir / 'app.db'}"
@property
def files_dir(self) -> Path:
return self.data_dir / "files"
@property @property
def allowed_origin_list(self) -> list[str]: def allowed_origin_list(self) -> list[str]:
return [o.strip().rstrip("/") for o in self.allowed_origins.split(",") if o.strip()] return [o.strip().rstrip("/") for o in self.allowed_origins.split(",") if o.strip()]
+28 -6
View File
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
from fastapi.responses import FileResponse, JSONResponse from fastapi.responses import FileResponse, JSONResponse
from app import __version__ from app import __version__
from app.api import admin, auth, clips, health, projects, ws from app.api import admin, auth, clips, files, health, projects, ws
from app.config import get_settings from app.config import get_settings
from app.db import _session_factory from app.db import _session_factory
from app.middleware import ( from app.middleware import (
@@ -17,28 +17,41 @@ from app.middleware import (
OriginCheckMiddleware, OriginCheckMiddleware,
SecurityHeadersMiddleware, SecurityHeadersMiddleware,
) )
from app.services import files as file_service
from app.services.auth import delete_old_login_attempts from app.services.auth import delete_old_login_attempts
from app.services.projects import ProjectNotFound from app.services.projects import ProjectNotFound
from app.services.sessions import delete_expired_sessions from app.services.sessions import delete_expired_sessions
from app.services.users import UserError, bootstrap_initial_admin from app.services.users import UserError, bootstrap_initial_admin
from app.ws.hub import hub
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
CLEANUP_INTERVAL_SECONDS = 3600 CLEANUP_INTERVAL_SECONDS = 3600
def _cleanup() -> None: def _cleanup() -> list[tuple[int, int]]:
"""Hourly housekeeping; returns (user_id, clip_id) of expired file clips."""
with _session_factory()() as db: with _session_factory()() as db:
sessions = delete_expired_sessions(db) sessions = delete_expired_sessions(db)
attempts = delete_old_login_attempts(db) attempts = delete_old_login_attempts(db)
if sessions or attempts: expired = file_service.delete_expired(db)
logger.info("Cleanup: %d sessions, %d login attempts removed", sessions, attempts) orphans = file_service.remove_orphans(db)
if sessions or attempts or expired or orphans:
logger.info(
"Cleanup: %d sessions, %d login attempts, %d expired files, %d orphans removed",
sessions,
attempts,
len(expired),
orphans,
)
return expired
async def _cleanup_loop() -> None: async def _cleanup_loop() -> None:
while True: while True:
try: try:
await run_in_threadpool(_cleanup) for user_id, clip_id in await run_in_threadpool(_cleanup):
await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}})
except Exception: except Exception:
logger.exception("Cleanup failed") logger.exception("Cleanup failed")
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS) await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
@@ -124,19 +137,28 @@ def create_app() -> FastAPI:
) )
# Last added runs first: security headers wrap every response, including rejections # Last added runs first: security headers wrap every response, including rejections
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list) app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
app.add_middleware(BodySizeLimitMiddleware, max_bytes=settings.max_request_bytes) app.add_middleware(
BodySizeLimitMiddleware,
max_bytes=settings.max_request_bytes,
exempt=frozenset({("POST", files.UPLOAD_PATH)}),
)
app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list) app.add_middleware(SecurityHeadersMiddleware, allowed_origins=settings.allowed_origin_list)
app.include_router(health.router, prefix="/api") app.include_router(health.router, prefix="/api")
app.include_router(auth.router, prefix="/api") app.include_router(auth.router, prefix="/api")
app.include_router(admin.router, prefix="/api") app.include_router(admin.router, prefix="/api")
app.include_router(clips.router, prefix="/api") app.include_router(clips.router, prefix="/api")
app.include_router(projects.router, prefix="/api") app.include_router(projects.router, prefix="/api")
app.include_router(files.router, prefix="/api")
app.include_router(ws.router, prefix="/api") app.include_router(ws.router, prefix="/api")
@app.exception_handler(UserError) @app.exception_handler(UserError)
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse: def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST) return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
@app.exception_handler(file_service.FileRejected)
def file_rejected_handler(_request: Request, exc: file_service.FileRejected) -> JSONResponse:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
@app.exception_handler(ProjectNotFound) @app.exception_handler(ProjectNotFound)
def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse: def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse:
# Same answer for foreign and missing projects, so ids of other users are not revealed # Same answer for foreign and missing projects, so ids of other users are not revealed
+14 -2
View File
@@ -90,13 +90,25 @@ class BodySizeLimitMiddleware:
When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect. When a stream exceeds the limit, the 413 is sent here and the app sees a disconnect.
""" """
def __init__(self, app: ASGIApp, max_bytes: int, path_prefix: str = "/api/") -> None: def __init__(
self,
app: ASGIApp,
max_bytes: int,
path_prefix: str = "/api/",
exempt: frozenset[tuple[str, str]] = frozenset(),
) -> None:
self.app = app self.app = app
self.max_bytes = max_bytes self.max_bytes = max_bytes
self.path_prefix = path_prefix self.path_prefix = path_prefix
# (method, path) pairs that enforce their own, larger limit (file uploads)
self.exempt = exempt
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or not scope["path"].startswith(self.path_prefix): if (
scope["type"] != "http"
or not scope["path"].startswith(self.path_prefix)
or (scope["method"], scope["path"]) in self.exempt
):
await self.app(scope, receive, send) await self.app(scope, receive, send)
return return
+2
View File
@@ -1,5 +1,6 @@
from app.models.base import Base, UTCDateTime, utcnow from app.models.base import Base, UTCDateTime, utcnow
from app.models.clip import Clip, ClipKind from app.models.clip import Clip, ClipKind
from app.models.file import StoredFile
from app.models.login_attempt import LoginAttempt from app.models.login_attempt import LoginAttempt
from app.models.project import PROJECT_COLORS, Project from app.models.project import PROJECT_COLORS, Project
from app.models.session import UserSession from app.models.session import UserSession
@@ -13,6 +14,7 @@ __all__ = [
"PROJECT_COLORS", "PROJECT_COLORS",
"Project", "Project",
"Role", "Role",
"StoredFile",
"UTCDateTime", "UTCDateTime",
"User", "User",
"UserSession", "UserSession",
+11 -1
View File
@@ -2,16 +2,22 @@ from __future__ import annotations
import enum import enum
from datetime import datetime from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import Enum, ForeignKey, Index, String, Text from sqlalchemy import Enum, ForeignKey, Index, String, Text
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, UTCDateTime, utcnow from app.models.base import Base, UTCDateTime, utcnow
if TYPE_CHECKING:
from app.models.file import StoredFile
class ClipKind(enum.StrEnum): class ClipKind(enum.StrEnum):
TEXT = "text" TEXT = "text"
CODE = "code" CODE = "code"
# Uploaded file; content holds the file name so search finds it
FILE = "file"
class Clip(Base): class Clip(Base):
@@ -37,3 +43,7 @@ class Clip(Base):
version: Mapped[int] = mapped_column(default=1) version: Mapped[int] = mapped_column(default=1)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
file: Mapped[StoredFile | None] = relationship(
back_populates="clip", lazy="selectin", passive_deletes=True
)
+38
View File
@@ -0,0 +1,38 @@
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, 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.clip import Clip
class StoredFile(Base):
"""An uploaded file; belongs to exactly one clip of kind "file"."""
__tablename__ = "files"
__table_args__ = (
Index("ix_files_user", "user_id"),
Index("ix_files_expires_at", "expires_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
clip_id: Mapped[int] = mapped_column(ForeignKey("clips.id", ondelete="CASCADE"), unique=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
# Random name on disk; the original name never touches the file system
storage_name: Mapped[str] = mapped_column(String(64), unique=True)
name: Mapped[str] = mapped_column(String(255))
content_type: Mapped[str] = mapped_column(String(127))
size: Mapped[int] = mapped_column(BigInteger)
sha256: Mapped[str] = mapped_column(String(64))
# Only set when the content really is a JPEG/PNG/GIF/WebP image (checked on upload)
previewable: Mapped[bool] = mapped_column(default=False)
expires_at: Mapped[datetime | None] = mapped_column(UTCDateTime)
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
clip: Mapped[Clip] = relationship(back_populates="file")
+11
View File
@@ -29,6 +29,16 @@ class ClipUpdate(BaseModel):
version: int | None = Field(default=None, description="Expected version for conflict check") version: int | None = Field(default=None, description="Expected version for conflict check")
class FileOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
content_type: str
size: int
previewable: bool
expires_at: datetime | None
class ClipOut(BaseModel): class ClipOut(BaseModel):
model_config = ConfigDict(from_attributes=True) model_config = ConfigDict(from_attributes=True)
@@ -39,6 +49,7 @@ class ClipOut(BaseModel):
language: str | None language: str | None
pinned: bool pinned: bool
project_id: int | None project_id: int | None
file: FileOut | None = None
version: int version: int
created_at: datetime created_at: datetime
updated_at: datetime updated_at: datetime
+19 -2
View File
@@ -5,13 +5,17 @@ from sqlalchemy.orm import Session
from app.config import get_settings from app.config import get_settings
from app.languages import LANGUAGES from app.languages import LANGUAGES
from app.models import Clip, ClipKind, utcnow from app.models import Clip, ClipKind, StoredFile, utcnow
from app.services.files import remove_from_disk
from app.services.projects import require_project from app.services.projects import require_project
from app.services.users import UserError from app.services.users import UserError
# Changing only these fields does not count as an edit (no new updated_at) # Changing only these fields does not count as an edit (no new updated_at)
_META_FIELDS = frozenset({"pinned", "project_id"}) _META_FIELDS = frozenset({"pinned", "project_id"})
# Fixed for file clips: content is the file name
_CONTENT_FIELDS = frozenset({"kind", "content", "language"})
# Filter value for clips without a project # Filter value for clips without a project
NO_PROJECT = "none" NO_PROJECT = "none"
SEARCH_MAX_LENGTH = 200 SEARCH_MAX_LENGTH = 200
@@ -36,7 +40,7 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
title = (title or "").strip() or None title = (title or "").strip() or None
if title is not None and len(title) > 200: if title is not None and len(title) > 200:
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).") raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
if kind == ClipKind.TEXT: if kind != ClipKind.CODE:
language = None language = None
else: else:
language = language or "plaintext" language = language or "plaintext"
@@ -100,6 +104,8 @@ def create_clip(
pinned: bool = False, pinned: bool = False,
project_id: int | None = None, project_id: int | None = None,
) -> Clip: ) -> Clip:
if kind == ClipKind.FILE:
raise UserError("Dateien werden über den Upload angelegt.")
title, language = _normalize(kind, title, content, language) title, language = _normalize(kind, title, content, language)
if project_id is not None: if project_id is not None:
require_project(db, user_id, project_id) require_project(db, user_id, project_id)
@@ -128,6 +134,10 @@ def update_clip(
# Early check so a stale client gets the conflict, not a follow-up validation error # Early check so a stale client gets the conflict, not a follow-up validation error
if expected_version is not None and clip.version != expected_version: if expected_version is not None and clip.version != expected_version:
raise ClipConflict(clip) raise ClipConflict(clip)
if clip.kind == ClipKind.FILE and set(changes) & _CONTENT_FIELDS:
raise UserError("Bei Dateien lassen sich nur Titel, Projekt und Anheften ändern.")
if changes.get("kind") == ClipKind.FILE and clip.kind != ClipKind.FILE:
raise UserError("Ein Clip lässt sich nicht in eine Datei umwandeln.")
kind = changes.get("kind", clip.kind) kind = changes.get("kind", clip.kind)
title = changes.get("title", clip.title) title = changes.get("title", clip.title)
content = changes.get("content", clip.content) content = changes.get("content", clip.content)
@@ -164,6 +174,13 @@ def update_clip(
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool: def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
storage_name = db.scalar(
select(StoredFile.storage_name).where(
StoredFile.clip_id == clip_id, StoredFile.user_id == user_id
)
)
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id)) result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
db.commit() db.commit()
if storage_name is not None:
remove_from_disk(user_id, storage_name)
return result.rowcount > 0 return result.rowcount > 0
+277
View File
@@ -0,0 +1,277 @@
import hashlib
import logging
import os
import re
import shutil
import time
import unicodedata
import uuid
from collections.abc import AsyncIterator
from datetime import timedelta
from pathlib import Path
from urllib.parse import quote
from sqlalchemy import delete, func, select, update
from sqlalchemy.orm import Session
from app.config import get_settings
from app.models import Clip, ClipKind, StoredFile, utcnow
from app.services.projects import require_project
from app.services.users import UserError
logger = logging.getLogger(__name__)
# Allowed lifetimes in days; 0 means the file is kept until deleted
EXPIRY_CHOICES = frozenset({0, 1, 7, 30})
NAME_MAX_LENGTH = 255
FALLBACK_NAME = "datei"
TMP_DIR_NAME = "tmp"
# Files on disk without database row are only removed after this age, so an upload
# that is just being committed is never touched
ORPHAN_MIN_AGE_SECONDS = 3600
STALE_UPLOAD_SECONDS = 6 * 3600
_CONTENT_TYPE = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$")
# Magic bytes of the image formats every browser displays safely (no SVG: it can run script)
_IMAGE_SIGNATURES = (
(b"\xff\xd8\xff", "image/jpeg"),
(b"\x89PNG\r\n\x1a\n", "image/png"),
(b"GIF87a", "image/gif"),
(b"GIF89a", "image/gif"),
)
class FileRejected(Exception):
"""Upload refused; status code and message go to the client unchanged."""
def __init__(self, status_code: int, detail: str) -> None:
super().__init__(detail)
self.status_code = status_code
self.detail = detail
def format_bytes(size: int) -> str:
for unit, factor in (("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
if size >= factor:
return f"{size / factor:.1f}".rstrip("0").rstrip(".").replace(".", ",") + f" {unit}"
return f"{size} B"
def sanitize_name(name: str) -> str:
"""Keep only the base name, without control characters, at most 255 characters."""
name = unicodedata.normalize("NFC", name)
name = re.split(r"[/\\]", name)[-1]
name = "".join(ch for ch in name if not unicodedata.category(ch).startswith("C"))
name = name.strip()
if name in ("", ".", ".."):
return FALLBACK_NAME
if len(name) > NAME_MAX_LENGTH:
stem, dot, ext = name.rpartition(".")
if dot and stem and len(ext) <= 20:
name = stem[: NAME_MAX_LENGTH - len(ext) - 1] + "." + ext
else:
name = name[:NAME_MAX_LENGTH]
return name
def sanitize_content_type(value: str | None) -> str:
value = (value or "").split(";")[0].strip().lower()
return value if _CONTENT_TYPE.fullmatch(value) else "application/octet-stream"
def sniff_image(head: bytes) -> str | None:
"""Image type from the first bytes, or None if it is not a previewable image."""
for signature, content_type in _IMAGE_SIGNATURES:
if head.startswith(signature):
return content_type
if len(head) >= 12 and head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "image/webp"
return None
def content_disposition(name: str, inline: bool = False) -> str:
"""RFC 6266 header with ASCII fallback; quotes and line breaks cannot break out."""
fallback = "".join(ch if 32 <= ord(ch) < 127 and ch not in '"\\' else "_" for ch in name)
kind = "inline" if inline else "attachment"
return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"
def file_path(user_id: int, storage_name: str) -> Path:
return get_settings().files_dir / str(user_id) / storage_name
def remove_from_disk(user_id: int, storage_name: str) -> None:
try:
file_path(user_id, storage_name).unlink(missing_ok=True)
except OSError:
logger.exception("Could not remove file %s of user %d", storage_name, user_id)
def used_bytes(db: Session, user_id: int) -> int:
total = db.scalar(select(func.sum(StoredFile.size)).where(StoredFile.user_id == user_id))
return int(total or 0)
def _expires_at(days: int):
if days not in EXPIRY_CHOICES:
raise UserError("Ungültige Ablaufzeit.")
return utcnow() + timedelta(days=days) if days else None
def _check_limits(db: Session, user_id: int, size: int) -> None:
settings = get_settings()
if size <= 0:
raise FileRejected(400, "Die Datei ist leer.")
if size > settings.file_max_bytes:
raise FileRejected(
413, f"Die Datei ist zu groß (höchstens {format_bytes(settings.file_max_bytes)})."
)
used = used_bytes(db, user_id)
if used + size > settings.file_quota_bytes:
free = max(settings.file_quota_bytes - used, 0)
raise FileRejected(
413,
f"Nicht genug Speicherplatz: noch {format_bytes(free)} von "
f"{format_bytes(settings.file_quota_bytes)} frei.",
)
settings.files_dir.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(settings.files_dir).free - size < settings.file_min_free_bytes:
raise FileRejected(507, "Auf dem Server ist gerade nicht genug Speicherplatz frei.")
async def store_upload(
db: Session,
user_id: int,
chunks: AsyncIterator[bytes],
*,
name: str,
size: int,
content_type: str | None = None,
expires_days: int = 7,
project_id: int | None = None,
title: str | None = None,
) -> Clip:
"""Stream an upload to disk and create its clip. size is the announced Content-Length."""
name = sanitize_name(name)
expires_at = _expires_at(expires_days)
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 project_id is not None:
require_project(db, user_id, project_id)
_check_limits(db, user_id, size)
settings = get_settings()
tmp_dir = settings.files_dir / TMP_DIR_NAME
tmp_dir.mkdir(parents=True, exist_ok=True)
storage_name = uuid.uuid4().hex
tmp_path = tmp_dir / f"{storage_name}.part"
final_path = file_path(user_id, storage_name)
digest = hashlib.sha256()
received = 0
head = b""
try:
with tmp_path.open("xb") as out:
async for chunk in chunks:
received += len(chunk)
if received > size:
raise FileRejected(400, "Die Datei ist größer als angekündigt.")
if len(head) < 16:
head = (head + chunk)[:16]
digest.update(chunk)
out.write(chunk)
if received != size:
raise FileRejected(400, "Die Übertragung wurde unterbrochen.")
image_type = sniff_image(head)
final_path.parent.mkdir(parents=True, exist_ok=True)
os.replace(tmp_path, final_path)
clip = Clip(
user_id=user_id,
project_id=project_id,
kind=ClipKind.FILE,
title=title,
content=name,
)
clip.file = StoredFile(
user_id=user_id,
storage_name=storage_name,
name=name,
content_type=image_type or sanitize_content_type(content_type),
size=size,
sha256=digest.hexdigest(),
previewable=image_type is not None,
expires_at=expires_at,
)
db.add(clip)
db.commit()
return clip
except BaseException:
db.rollback()
tmp_path.unlink(missing_ok=True)
final_path.unlink(missing_ok=True)
raise
def get_file(db: Session, user_id: int, clip_id: int) -> StoredFile | None:
"""The file of a clip of this user, unless it has expired."""
stored = db.scalar(
select(StoredFile).where(StoredFile.clip_id == clip_id, StoredFile.user_id == user_id)
)
if stored is None or (stored.expires_at is not None and stored.expires_at <= utcnow()):
return None
return stored
def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip:
"""Change how long a file is kept; counts as a change of the clip, not as an edit."""
if clip.file is None:
raise UserError("Dieser Clip ist keine Datei.")
clip.file.expires_at = _expires_at(expires_days)
db.execute(
update(Clip)
.where(Clip.id == clip.id, Clip.user_id == user_id)
.values(version=Clip.version + 1)
.execution_options(synchronize_session=False)
)
db.commit()
db.refresh(clip)
return clip
def delete_expired(db: Session) -> list[tuple[int, int]]:
"""Delete clips whose file has expired; returns (user_id, clip_id) for notifications."""
rows = db.execute(
select(StoredFile.user_id, StoredFile.clip_id, StoredFile.storage_name).where(
StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow()
)
).all()
if not rows:
return []
db.execute(delete(Clip).where(Clip.id.in_([row.clip_id for row in rows])))
db.commit()
for row in rows:
remove_from_disk(row.user_id, row.storage_name)
return [(row.user_id, row.clip_id) for row in rows]
def remove_orphans(db: Session) -> int:
"""Remove files without database row (e.g. of deleted users) and stale partial uploads."""
files_dir = get_settings().files_dir
if not files_dir.is_dir():
return 0
known = set(db.scalars(select(StoredFile.storage_name)))
now = time.time()
removed = 0
for path in files_dir.glob("*/*"):
if not path.is_file():
continue
if path.parent.name == TMP_DIR_NAME:
stale = now - path.stat().st_mtime > STALE_UPLOAD_SECONDS
else:
stale = path.name not in known and now - path.stat().st_mtime > ORPHAN_MIN_AGE_SECONDS
if stale:
path.unlink(missing_ok=True)
removed += 1
return removed
+457
View File
@@ -0,0 +1,457 @@
import asyncio
import os
import time
from datetime import timedelta
from types import SimpleNamespace
import pytest
from fastapi.testclient import TestClient
from app.config import get_settings
from app.models import Clip, StoredFile, utcnow
from app.services import files as file_service
from tests.conftest import login
from tests.test_ws import connect
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 64
WEBP = b"RIFF\x00\x00\x00\x00WEBPVP8 " + b"\x00" * 32
@pytest.fixture
def anna(client, make_user):
make_user("anna")
login(client, "anna")
return client
@pytest.fixture
def bert(client, make_user):
make_user("bert")
with TestClient(client.app, base_url="https://testserver") as other:
login(other, "bert")
yield other
@pytest.fixture
def limits(monkeypatch):
"""Set file limits via environment, like in production."""
def _set(**values):
for key, value in values.items():
monkeypatch.setenv(key.upper(), str(value))
get_settings.cache_clear()
return _set
def upload(c, data=b"hello file", name="note.txt", status=201, headers=None, **params):
response = c.post(
"/api/files",
params={"name": name, **params},
content=data,
headers={"Content-Type": "text/plain", **(headers or {})},
)
assert response.status_code == status, response.text
return response.json()
def stored_files():
root = get_settings().files_dir
return sorted(p for p in root.glob("*/*") if p.is_file()) if root.exists() else []
# --- Upload and download --------------------------------------------------------
def test_upload_creates_file_clip(anna):
clip = upload(anna, b"hello file", "Notiz.txt", title=" Wichtig ")
assert clip["kind"] == "file"
assert clip["content"] == "Notiz.txt"
assert clip["title"] == "Wichtig"
assert clip["language"] is None
assert clip["file"]["name"] == "Notiz.txt"
assert clip["file"]["size"] == 10
assert clip["file"]["content_type"] == "text/plain"
assert clip["file"]["previewable"] is False
assert len(stored_files()) == 1
# The original name never reaches the file system
assert stored_files()[0].name != "Notiz.txt"
def test_download_is_an_attachment(anna):
clip = upload(
anna, b"<html><script>alert(1)</script>", "page.html", headers={"Content-Type": "text/html"}
)
response = anna.get(f"/api/files/{clip['id']}")
assert response.status_code == 200
assert response.content == b"<html><script>alert(1)</script>"
assert response.headers["content-disposition"].startswith("attachment;")
assert response.headers["content-security-policy"] == "default-src 'none'; sandbox"
assert response.headers["x-content-type-options"] == "nosniff"
assert response.headers["cache-control"] == "private, no-cache"
def test_inline_request_is_ignored_for_non_images(anna):
clip = upload(anna, b"<svg onload='x'/>", "x.svg", headers={"Content-Type": "image/svg+xml"})
assert clip["file"]["previewable"] is False
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
assert response.headers["content-disposition"].startswith("attachment;")
@pytest.mark.parametrize(
("data", "content_type"),
[
(PNG, "image/png"),
(JPEG, "image/jpeg"),
(WEBP, "image/webp"),
(b"GIF89a" + PNG, "image/gif"),
],
)
def test_real_images_are_previewable(anna, data, content_type):
# Type comes from the content, not from what the client claims
clip = upload(anna, data, "bild", headers={"Content-Type": "application/octet-stream"})
assert clip["file"]["previewable"] is True
assert clip["file"]["content_type"] == content_type
response = anna.get(f"/api/files/{clip['id']}", params={"inline": 1})
assert response.headers["content-disposition"].startswith("inline;")
assert response.headers["content-type"] == content_type
def test_fake_image_is_not_previewable(anna):
clip = upload(anna, b"<html>", "fake.png", headers={"Content-Type": "image/png"})
assert clip["file"]["previewable"] is False
@pytest.mark.parametrize(
("raw", "expected"),
[
("../../etc/passwd", "passwd"),
("C:\\Users\\x\\bericht.pdf", "bericht.pdf"),
("a\r\nX-Evil: 1.txt", "aX-Evil: 1.txt"),
(" .. ", "datei"),
("Größe.txt", "Größe.txt"),
],
)
def test_file_names_are_sanitized(anna, raw, expected):
assert upload(anna, name=raw)["file"]["name"] == expected
def test_long_names_keep_their_extension():
name = file_service.sanitize_name("x" * 400 + ".tar.gz")
assert len(name) == 255
assert name.endswith(".gz")
def test_content_disposition_cannot_break_out():
header = file_service.content_disposition('a"b\\c ä.txt')
assert header == "attachment; filename=\"a_b_c _.txt\"; filename*=UTF-8''a%22b%5Cc%20%C3%A4.txt"
def test_download_header_with_umlauts(anna):
clip = upload(anna, name="Bericht März.pdf")
disposition = anna.get(f"/api/files/{clip['id']}").headers["content-disposition"]
assert "filename*=UTF-8''Bericht%20M%C3%A4rz.pdf" in disposition
def test_content_type_is_sanitized(anna):
clip = upload(anna, headers={"Content-Type": "Text/Plain; charset=utf-8"})
assert clip["file"]["content_type"] == "text/plain"
clip = upload(anna, headers={"Content-Type": "bad type\r\nX: y"})
assert clip["file"]["content_type"] == "application/octet-stream"
def test_upload_larger_than_request_limit(anna):
data = os.urandom(1024 * 1024 + 4096) # above the general 1 MiB request limit
clip = upload(anna, data, "random.bin")
assert anna.get(f"/api/files/{clip['id']}").content == data
# The general limit still applies everywhere else
assert anna.post("/api/clips", content=b"x" * len(data)).status_code == 413
def test_search_finds_file_names(anna):
clip = upload(anna, name="steuer-2026.pdf")
upload(anna, name="urlaub.jpg")
items = anna.get("/api/clips", params={"q": "STEUER"}).json()["items"]
assert [c["id"] for c in items] == [clip["id"]]
def test_upload_into_project(anna):
project = anna.post("/api/projects", json={"name": "Docs"}).json()
clip = upload(anna, project_id=project["id"])
assert clip["project_id"] == project["id"]
assert anna.get("/api/projects").json()[0]["clip_count"] == 1
# --- Limits ---------------------------------------------------------------------
def test_empty_file_is_rejected(anna):
assert upload(anna, b"", status=400)["detail"] == "Die Datei ist leer."
def test_file_size_limit(anna, limits):
limits(file_max_bytes=10)
upload(anna, b"x" * 10)
detail = upload(anna, b"x" * 11, status=413)["detail"]
assert detail == "Die Datei ist zu groß (höchstens 10 B)."
assert len(stored_files()) == 1
def test_quota_per_user(anna, bert, limits):
limits(file_quota_bytes=2048)
upload(anna, b"x" * 1500)
detail = upload(anna, b"x" * 1000, status=413)["detail"]
assert detail == "Nicht genug Speicherplatz: noch 548 B von 2 KB frei."
# Quota is per user
upload(bert, b"x" * 1500)
def test_minimum_free_disk_space(anna, limits, monkeypatch):
limits(file_min_free_bytes=1000)
monkeypatch.setattr(file_service.shutil, "disk_usage", lambda _path: SimpleNamespace(free=1500))
upload(anna, b"x" * 500)
response = anna.post("/api/files", params={"name": "a"}, content=b"x" * 501)
assert response.status_code == 507
def test_content_length_is_required(anna):
def body():
yield b"chunk"
response = anna.post("/api/files", params={"name": "a"}, content=body())
assert response.status_code == 411
@pytest.mark.parametrize("days", [-1, 2, 365])
def test_invalid_expiry(anna, days):
upload(anna, expires_days=days, status=400)
def test_foreign_or_unknown_project(anna, bert):
project = anna.post("/api/projects", json={"name": "Docs"}).json()
upload(bert, project_id=project["id"], status=404)
upload(anna, project_id=999, status=404)
assert stored_files() == []
def test_upload_requires_login_and_csrf(anna, client):
del anna.headers["X-CSRF-Token"]
upload(anna, status=403)
anna.cookies.clear()
upload(anna, status=401)
assert stored_files() == []
def _chunks(*parts, fail=False):
async def gen():
for part in parts:
yield part
if fail:
raise ConnectionError("client gone")
return gen()
def test_aborted_upload_leaves_nothing_behind(db, make_user):
user = make_user("anna")
with pytest.raises(ConnectionError):
asyncio.run(
file_service.store_upload(db, user.id, _chunks(b"half", fail=True), name="a", size=8)
)
with pytest.raises(file_service.FileRejected, match="unterbrochen"):
asyncio.run(file_service.store_upload(db, user.id, _chunks(b"half"), name="a", size=8))
with pytest.raises(file_service.FileRejected, match="größer als angekündigt"):
asyncio.run(
file_service.store_upload(db, user.id, _chunks(b"too", b"long"), name="a", size=4)
)
assert stored_files() == []
assert db.query(StoredFile).count() == 0
assert db.query(Clip).count() == 0
# --- File clips -----------------------------------------------------------------
def test_file_clip_metadata_can_change(anna):
clip = upload(anna)
project = anna.post("/api/projects", json={"name": "Docs"}).json()
response = anna.patch(
f"/api/clips/{clip['id']}",
json={"title": "Neu", "pinned": True, "project_id": project["id"]},
)
assert response.status_code == 200
assert response.json()["file"]["name"] == "note.txt"
@pytest.mark.parametrize(
"changes", [{"content": "other.txt"}, {"kind": "text"}, {"language": "python"}]
)
def test_file_clip_content_is_fixed(anna, changes):
clip = upload(anna)
response = anna.patch(f"/api/clips/{clip['id']}", json=changes)
assert response.status_code == 400
def test_files_cannot_be_created_or_faked_as_clips(anna):
assert anna.post("/api/clips", json={"content": "x", "kind": "file"}).status_code == 400
text = anna.post("/api/clips", json={"content": "x"}).json()
assert anna.patch(f"/api/clips/{text['id']}", json={"kind": "file"}).status_code == 400
def test_deleting_clip_removes_file(anna):
clip = upload(anna)
assert len(stored_files()) == 1
assert anna.delete(f"/api/clips/{clip['id']}").status_code == 204
assert stored_files() == []
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
def test_missing_file_on_disk_is_404(anna):
clip = upload(anna)
stored_files()[0].unlink()
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
def test_usage(anna, bert, limits):
limits(file_quota_bytes=5000, file_max_bytes=1000)
upload(anna, b"x" * 300)
upload(anna, b"x" * 200)
upload(bert, b"x" * 999)
assert anna.get("/api/files/usage").json() == {
"used_bytes": 500,
"quota_bytes": 5000,
"max_file_bytes": 1000,
}
# --- Expiry ---------------------------------------------------------------------
def test_default_expiry_is_seven_days(anna):
expires = upload(anna)["file"]["expires_at"]
assert expires[:10] == (utcnow() + timedelta(days=7)).date().isoformat()
assert upload(anna, expires_days=0)["file"]["expires_at"] is None
def test_change_expiry(anna):
clip = upload(anna, expires_days=1)
response = anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 0})
assert response.status_code == 200
assert response.json()["file"]["expires_at"] is None
assert response.json()["version"] == clip["version"] + 1
assert response.json()["updated_at"] == clip["updated_at"]
text = anna.post("/api/clips", json={"content": "x"}).json()
assert anna.patch(f"/api/files/{text['id']}", json={"expires_days": 0}).status_code == 400
def _expire(db, clip_id):
stored = db.query(StoredFile).filter_by(clip_id=clip_id).one()
stored.expires_at = utcnow() - timedelta(minutes=1)
db.commit()
def test_expired_file_cannot_be_downloaded(anna, db):
clip = upload(anna)
_expire(db, clip["id"])
assert anna.get(f"/api/files/{clip['id']}").status_code == 404
def test_cleanup_deletes_expired_files(anna, db):
old = upload(anna, b"old", "old.txt")
keep = upload(anna, b"keep", "keep.txt", expires_days=0)
_expire(db, old["id"])
user_id = db.query(Clip).filter_by(id=old["id"]).one().user_id
assert file_service.delete_expired(db) == [(user_id, old["id"])]
ids = [c["id"] for c in anna.get("/api/clips").json()["items"]]
assert ids == [keep["id"]]
assert len(stored_files()) == 1
assert file_service.delete_expired(db) == []
def test_cleanup_removes_orphans_and_stale_uploads(anna, db):
upload(anna)
files_dir = get_settings().files_dir
known = stored_files()[0]
old = time.time() - 7 * 3600
orphan_old = files_dir / "99" / "deadbeef"
orphan_new = files_dir / "99" / "cafebabe"
stale_part = files_dir / "tmp" / "x.part"
fresh_part = files_dir / "tmp" / "y.part"
for path in (orphan_old, orphan_new, stale_part, fresh_part):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b"x")
for path in (orphan_old, stale_part, known):
os.utime(path, (old, old))
assert file_service.remove_orphans(db) == 2
assert {p.name for p in stored_files()} == {known.name, "cafebabe", "y.part"}
def test_deleted_user_leaves_only_orphans(client, anna, db, make_user):
from app.models import Role, User
upload(anna)
make_user("root", role=Role.ADMIN)
with TestClient(client.app, base_url="https://testserver") as admin:
login(admin, "root")
anna_id = db.query(User).filter_by(username="anna").one().id
admin.delete(f"/api/admin/users/{anna_id}")
db.expire_all()
assert db.query(StoredFile).count() == 0
path = stored_files()[0]
os.utime(path, (time.time() - 7200, time.time() - 7200))
assert file_service.remove_orphans(db) == 1
# --- Data separation ------------------------------------------------------------
def test_files_of_other_users_are_invisible(anna, bert):
clip = upload(anna, b"secret")
url = f"/api/files/{clip['id']}"
assert bert.get(url).status_code == 404
assert bert.get(url, params={"inline": 1}).status_code == 404
assert bert.patch(url, json={"expires_days": 0}).status_code == 404
assert bert.delete(f"/api/clips/{clip['id']}").status_code == 404
assert bert.get("/api/files/usage").json()["used_bytes"] == 0
assert anna.get(url).content == b"secret"
assert len(stored_files()) == 1
# --- Live sync ------------------------------------------------------------------
def test_upload_is_broadcast(anna):
with connect(anna) as ws:
ws.receive_json()
clip = upload(anna, name="live.txt")
event = ws.receive_json()
assert event["type"] == "clip.created"
assert event["data"]["id"] == clip["id"]
assert event["data"]["file"]["name"] == "live.txt"
anna.patch(f"/api/files/{clip['id']}", json={"expires_days": 30})
event = ws.receive_json()
assert event["type"] == "clip.updated"
assert event["data"]["file"]["expires_at"] is not None