Spaces:
Runtime error

ai-tester-platform / src /utils /uploads.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
6.41 kB
"""Upload validation helpers.
Centralised guard for any FastAPI endpoint that accepts user-uploaded files.
Enforces three checks:
1. **Size** — bounded by ``MAX_UPLOAD_SIZE`` (env var, bytes; default 25 MiB).
Reads ``Content-Length`` first to short-circuit oversized requests, then
verifies the actual byte count after reading (defends against clients that
lie in the header).
2. **MIME / extension** — caller passes a whitelist of allowed content-types
and (optionally) extensions. Both are matched case-insensitively.
3. **Filename** — sanitised against path-traversal and shell-unfriendly
characters. The returned name is what should be persisted.
Raises ``HTTPException`` with 4xx codes that are safe to surface to clients.
"""
from __future__ import annotations
import re
from pathlib import PurePosixPath
from typing import Iterable, Optional, Set
from fastapi import HTTPException, UploadFile, status
from src.utils.env import env_int
# 25 MiB default. Override via env to relax for large knowledge sources.
DEFAULT_MAX_UPLOAD_SIZE = 25 * 1024 * 1024
# Whitelist for knowledge / scenario document uploads.
DOCUMENT_CONTENT_TYPES: Set[str] = {
"text/plain",
"text/csv",
"application/csv",
"application/json",
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/octet-stream", # fallback for browsers that don't sniff
}
DOCUMENT_EXTENSIONS: Set[str] = {
".txt",
".csv",
".tsv",
".json",
".pdf",
".doc",
".docx",
".xls",
".xlsx",
".md",
".html",
".htm",
}
# Whitelist for screenshot / image uploads from the desktop runner.
IMAGE_CONTENT_TYPES: Set[str] = {
"image/png",
"image/jpeg",
"image/jpg",
"image/webp",
"image/gif",
}
IMAGE_EXTENSIONS: Set[str] = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
_FILENAME_SAFE_RE = re.compile(r"[^A-Za-z0-9._\- ]+")
def max_upload_size() -> int:
"""Return the configured upload cap in bytes (read at call time)."""
return env_int("MAX_UPLOAD_SIZE", DEFAULT_MAX_UPLOAD_SIZE)
def sanitize_filename(filename: Optional[str], default: str = "uploaded-file") -> str:
"""Strip path components and dangerous characters from a filename.
- Drops any directory prefix (path traversal, ``..\\..\\etc\\passwd``).
- Replaces non-``[A-Za-z0-9._\\- ]`` characters with ``_``.
- Caps length at 200 chars to keep ext4/Postgres happy.
- Falls back to ``default`` if the name becomes empty after cleaning.
"""
if not filename:
return default
base = PurePosixPath(filename.replace("\\", "/")).name.strip()
if not base or base in {".", ".."}:
return default
cleaned = _FILENAME_SAFE_RE.sub("_", base)[:200].strip("._ ")
return cleaned or default
def _enforce_size_header(content_length: Optional[int], cap: int) -> None:
if content_length is None:
return
if content_length > cap:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=f"Upload exceeds maximum size of {cap} bytes",
)
def _enforce_content_type(content_type: Optional[str], whitelist: Optional[Set[str]]) -> None:
if not whitelist:
return
ct = (content_type or "").split(";", 1)[0].strip().lower()
if not ct or ct not in whitelist:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail=f"Unsupported content type: {ct or 'unknown'}",
)
def _enforce_extension(filename: str, whitelist: Optional[Set[str]]) -> None:
if not whitelist:
return
ext = PurePosixPath(filename).suffix.lower()
if ext and ext not in whitelist:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail=f"Unsupported file extension: {ext}",
)
async def read_upload_safely(
upload: UploadFile,
*,
allowed_content_types: Optional[Set[str]] = None,
allowed_extensions: Optional[Set[str]] = None,
max_size: Optional[int] = None,
) -> tuple[bytes, str]:
"""Read an ``UploadFile`` enforcing all three guards.
Returns ``(content_bytes, sanitized_filename)``.
Raises:
HTTPException 413 if the upload exceeds the size cap.
HTTPException 415 if the content-type or extension is rejected.
HTTPException 400 if the upload is empty.
"""
cap = max_size if max_size is not None else max_upload_size()
safe_name = sanitize_filename(upload.filename)
_enforce_extension(safe_name, allowed_extensions)
_enforce_content_type(upload.content_type, allowed_content_types)
# Read in chunks so we can abort early if the body exceeds the cap, even
# when Content-Length is missing or lies.
chunks: list[bytes] = []
total = 0
while True:
chunk = await upload.read(64 * 1024)
if not chunk:
break
total += len(chunk)
if total > cap:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=f"Upload exceeds maximum size of {cap} bytes",
)
chunks.append(chunk)
if total == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Empty upload",
)
return b"".join(chunks), safe_name
def assert_request_within_cap(content_length_header: Optional[str]) -> None:
"""Cheap pre-check on the raw header before reading the body.
Useful to short-circuit oversized multipart requests with multiple files.
Pass ``request.headers.get('content-length')``.
"""
cap = max_upload_size()
try:
cl = int(content_length_header) if content_length_header is not None else None
except (TypeError, ValueError):
cl = None
_enforce_size_header(cl, cap)
__all__ = [
"DOCUMENT_CONTENT_TYPES",
"DOCUMENT_EXTENSIONS",
"IMAGE_CONTENT_TYPES",
"IMAGE_EXTENSIONS",
"DEFAULT_MAX_UPLOAD_SIZE",
"assert_request_within_cap",
"max_upload_size",
"read_upload_safely",
"sanitize_filename",
]
# Suppress unused-import lint when the module is imported for side-effects only.
_ = Iterable