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>
278 lines
9.6 KiB
Python
278 lines
9.6 KiB
Python
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
|