security: harden data auth and deployment
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import warnings
|
||||
from io import BytesIO
|
||||
from typing import Any, Dict
|
||||
|
||||
@@ -15,6 +16,10 @@ _BUNDLED_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "as
|
||||
_BUNDLED_LOGO_PATH = os.path.join(_BUNDLED_DIR, "logo.png")
|
||||
_BUNDLED_FAVICON_PATH = os.path.join(_BUNDLED_DIR, "favicon.ico")
|
||||
_BRANDING_SOURCE = os.getenv("BRANDING_SOURCE", "bundled").lower()
|
||||
_MAX_UPLOAD_BYTES = 5 * 1024 * 1024
|
||||
_MAX_IMAGE_PIXELS = 25_000_000
|
||||
_ALLOWED_IMAGE_TYPES = {"image/png", "image/jpeg", "image/webp"}
|
||||
_ALLOWED_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
|
||||
def _ensure_branding_dir() -> None:
|
||||
@@ -110,14 +115,27 @@ async def branding_favicon() -> FileResponse:
|
||||
|
||||
|
||||
async def save_branding_image(file: UploadFile) -> Dict[str, Any]:
|
||||
if not file.content_type or not file.content_type.startswith("image/"):
|
||||
raise HTTPException(status_code=400, detail="Please upload an image file.")
|
||||
content = await file.read()
|
||||
content_type = str(file.content_type or "").lower()
|
||||
extension = os.path.splitext(str(file.filename or ""))[1].lower()
|
||||
if content_type not in _ALLOWED_IMAGE_TYPES or extension not in _ALLOWED_IMAGE_EXTENSIONS:
|
||||
raise HTTPException(status_code=400, detail="Upload a PNG, JPEG, or WebP image.")
|
||||
content = await file.read(_MAX_UPLOAD_BYTES + 1)
|
||||
if not content:
|
||||
raise HTTPException(status_code=400, detail="Uploaded file is empty.")
|
||||
if len(content) > _MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="Image is too large (maximum 5 MB).")
|
||||
try:
|
||||
image = Image.open(BytesIO(content))
|
||||
except OSError as exc:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
candidate = Image.open(BytesIO(content))
|
||||
if candidate.format not in {"PNG", "JPEG", "WEBP"}:
|
||||
raise ValueError("Unsupported image format")
|
||||
if candidate.width * candidate.height > _MAX_IMAGE_PIXELS:
|
||||
raise Image.DecompressionBombError("Image pixel limit exceeded")
|
||||
candidate.verify()
|
||||
image = Image.open(BytesIO(content))
|
||||
image.load()
|
||||
except (OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
raise HTTPException(status_code=400, detail="Image file could not be read.") from exc
|
||||
|
||||
_ensure_branding_dir()
|
||||
|
||||
Reference in New Issue
Block a user