forked from mtusi2026/mtusi2026lab4
Исправить валидацию изображений и filename
This commit is contained in:
+8
-1
@@ -2,6 +2,7 @@
|
|||||||
import io
|
import io
|
||||||
|
|
||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
|
from PIL.Image import DecompressionBombError
|
||||||
|
|
||||||
CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
CONTENT_TYPE_TO_PIL_FORMAT = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||||
|
|
||||||
@@ -10,6 +11,10 @@ class InvalidImage(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ImageTooLarge(InvalidImage):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def validate(data: bytes, declared_content_type: str, max_pixels: int) -> None:
|
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."""
|
"""Raise InvalidImage if the bytes are not a genuine, within-budget PNG/JPEG."""
|
||||||
expected_format = CONTENT_TYPE_TO_PIL_FORMAT.get(declared_content_type)
|
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")
|
raise InvalidImage("declared content type does not match actual image format")
|
||||||
width, height = img.size
|
width, height = img.size
|
||||||
if width * height > max_pixels:
|
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
|
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:
|
except (UnidentifiedImageError, OSError, ValueError) as exc:
|
||||||
raise InvalidImage(str(exc)) from exc
|
raise InvalidImage(str(exc)) from exc
|
||||||
|
|||||||
+17
-3
@@ -10,6 +10,7 @@ from datetime import datetime, timezone
|
|||||||
|
|
||||||
import asyncpg
|
import asyncpg
|
||||||
from fastapi import FastAPI, Header, Request
|
from fastapi import FastAPI, Header, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
from fastapi.responses import JSONResponse, Response
|
from fastapi.responses import JSONResponse, Response
|
||||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
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}$")
|
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
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_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or f"{socket.gethostname()}-{os.getpid()}"
|
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))
|
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:
|
def iso(value: datetime) -> str:
|
||||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
@@ -138,7 +147,10 @@ def decode_cursor(value: str) -> dict:
|
|||||||
try:
|
try:
|
||||||
padded = value + "=" * (-len(value) % 4)
|
padded = value + "=" * (-len(value) % 4)
|
||||||
raw = base64.urlsafe_b64decode(padded.encode())
|
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):
|
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||||
raise bad_request("malformed cursor")
|
raise bad_request("malformed cursor")
|
||||||
|
|
||||||
@@ -238,7 +250,7 @@ async def health_ready():
|
|||||||
@app.post("/api/v1/users", status_code=201)
|
@app.post("/api/v1/users", status_code=201)
|
||||||
async def register_user(request: Request):
|
async def register_user(request: Request):
|
||||||
body = await parse_body(request, CreateUser)
|
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}$")
|
raise bad_request("username must match ^[a-z0-9_]{3,32}$")
|
||||||
if not body.display_name.strip():
|
if not body.display_name.strip():
|
||||||
raise bad_request("display_name must not be blank")
|
raise bad_request("display_name must not be blank")
|
||||||
@@ -572,6 +584,8 @@ async def upload_attachment(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
images.validate(data, content_type, MAX_IMAGE_PIXELS)
|
images.validate(data, content_type, MAX_IMAGE_PIXELS)
|
||||||
|
except images.ImageTooLarge as exc:
|
||||||
|
raise payload_too_large(str(exc))
|
||||||
except images.InvalidImage as exc:
|
except images.InvalidImage as exc:
|
||||||
raise unsupported_media_type(str(exc))
|
raise unsupported_media_type(str(exc))
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user