diff --git a/app/images.py b/app/images.py index 5d6eb89..ed5482d 100644 --- a/app/images.py +++ b/app/images.py @@ -2,6 +2,7 @@ import io from PIL import Image, UnidentifiedImageError +from PIL.Image import DecompressionBombError CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"} @@ -10,6 +11,10 @@ class InvalidImage(Exception): pass +class ImageTooLarge(InvalidImage): + pass + + def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None: """Raise InvalidImage if the bytes are not a genuine, within-budget PNG/JPEG.""" expected_format = CONTENT_TYPE_TO_PIL_FORMAT.get(declared_content_type) @@ -23,7 +28,9 @@ def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None: raise InvalidImage("declared content type does not match actual image format") width, height = img.size if width * height > max_pixels: - raise InvalidImage("image exceeds the decoded pixel budget") + raise ImageTooLarge("image exceeds the decoded pixel budget") img.load() # forces full decode; raises on truncated/corrupted data + except DecompressionBombError as exc: + raise ImageTooLarge("image exceeds the decoded pixel budget") from exc except (UnidentifiedImageError, OSError, ValueError) as exc: raise InvalidImage(str(exc)) from exc diff --git a/app/main.py b/app/main.py index 21a4843..d4b920d 100644 --- a/app/main.py +++ b/app/main.py @@ -10,6 +10,7 @@ from datetime import datetime, timezone import asyncpg from fastapi import FastAPI, Header, Request +from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse, Response from pydantic import BaseModel, ConfigDict, Field, ValidationError @@ -26,7 +27,7 @@ from .security import hash_password, verify_password USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") -FILENAME_FORBIDDEN_RE = re.compile(r"[/\\\x00-\x1f]") +FILENAME_FORBIDDEN_RE = re.compile(r"[/\\\x00-\x1f\x7f]") MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760")) MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000")) INSTANCE_ID = os.environ.get("INSTANCE_ID") or f"{socket.gethostname()}-{os.getpid()}" @@ -75,6 +76,14 @@ async def api_error_handler(request: Request, exc: ApiError): return _error_response(exc, getattr(request.state, "request_id", uuid.uuid4().hex)) +@app.exception_handler(RequestValidationError) +async def request_validation_error_handler(request: Request, exc: RequestValidationError): + return _error_response( + bad_request("invalid request parameters"), + getattr(request.state, "request_id", uuid.uuid4().hex), + ) + + def iso(value: datetime) -> str: return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") @@ -138,7 +147,10 @@ def decode_cursor(value: str) -> dict: try: padded = value + "=" * (-len(value) % 4) raw = base64.urlsafe_b64decode(padded.encode()) - return json.loads(raw) + payload = json.loads(raw) + if not isinstance(payload, dict): + raise bad_request("malformed cursor") + return payload except (binascii.Error, ValueError, UnicodeDecodeError): raise bad_request("malformed cursor") @@ -238,7 +250,7 @@ async def health_ready(): @app.post("/api/v1/users", status_code=201) async def register_user(request: Request): body = await parse_body(request, CreateUser) - if not USERNAME_RE.match(body.username): + if not USERNAME_RE.fullmatch(body.username): raise bad_request("username must match ^[a-z0-9_]{3,32}$") if not body.display_name.strip(): raise bad_request("display_name must not be blank") @@ -572,6 +584,8 @@ async def upload_attachment( try: images.validate(data, content_type, MAX_IMAGE_PIXELS) + except images.ImageTooLarge as exc: + raise payload_too_large(str(exc)) except images.InvalidImage as exc: raise unsupported_media_type(str(exc))