Spaces:
Runtime error
Runtime error
File size: 6,409 Bytes
ed86a97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | """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
|