""" Secure document upload service: - Magic-byte inspection (JPEG, PNG, GIF, WebP, PDF) - Per-category size limits (2 MB photo, 5 MB KYC document) - Decompression-bomb guard (MAX_IMAGE_PIXELS) - Palette PNG & animated GIF safe handling + fast metadata stripping - Quarantine -> Clean scan lifecycle + session ownership """ import io import os import uuid from datetime import datetime, timedelta, timezone from PIL import Image, ImageOps, UnidentifiedImageError PHOTO_MAX_BYTES = 2 * 1024 * 1024 # 2 MB KYC_MAX_BYTES = 5 * 1024 * 1024 # 5 MB MAX_IMAGE_DIM = 5000 Image.MAX_IMAGE_PIXELS = 25_000_000 PHOTO_ALLOWED_MIMES = {"image/jpeg", "image/png", "image/gif", "image/webp"} KYC_ALLOWED_MIMES = {"image/jpeg", "image/png", "image/gif", "application/pdf"} class UploadValidationError(Exception): def __init__(self, message: str, status_code: int = 422): super().__init__(message) self.message = message self.status_code = status_code def detect_mime_from_magic_bytes(data: bytes) -> str | None: """Inspect file header magic bytes instead of trusting filename extensions.""" if len(data) < 4: return None if data[:3] == b"\xff\xd8\xff": return "image/jpeg" if data[:8] == b"\x89PNG\r\n\x1a\n": return "image/png" if data[:6] in (b"GIF87a", b"GIF89a"): return "image/gif" if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": return "image/webp" if data[:5] == b"%PDF-": return "application/pdf" return None def strip_image_metadata_and_validate(data: bytes, mime_type: str) -> bytes: """ Decode image via Pillow to validate dimensions and strip EXIF/metadata in C-speed without materializing pixel tuples in Python RAM. """ if mime_type == "application/pdf": return data try: with Image.open(io.BytesIO(data)) as img: img.verify() with Image.open(io.BytesIO(data)) as img: w, h = img.size if w <= 0 or h <= 0 or w > MAX_IMAGE_DIM or h > MAX_IMAGE_DIM: raise UploadValidationError("Invalid image dimensions (max 5000x5000).", 422) fmt = (img.format or "JPEG").upper() out = io.BytesIO() if fmt == "GIF": is_animated = getattr(img, "is_animated", False) and getattr(img, "n_frames", 1) > 1 if is_animated: img.save(out, format="GIF", save_all=True) else: img.save(out, format="GIF") return out.getvalue() # Normalize orientation from EXIF, then drop all EXIF/text chunks img = ImageOps.exif_transpose(img) if fmt == "JPEG" and img.mode not in ("RGB", "L"): img = img.convert("RGB") elif fmt == "PNG" and img.mode == "P": # Convert palette PNGs safely so transparency/colors are preserved img = img.convert("RGBA" if "transparency" in img.info else "RGB") img.save(out, format=fmt) return out.getvalue() except UploadValidationError: raise except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError) as exc: raise UploadValidationError(f"Corrupted or invalid image content: {exc}", 422) from exc def scan_quarantined_bytes(data: bytes) -> str: """Hook for malware scanner; flags EICAR test signature as REJECTED.""" if b"X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" in data: return "REJECTED" return "CLEAN" def process_staged_upload( *, raw_bytes: bytes, category: str, upload_root: str, session_id: str, doc_type_id: int | None = None, ) -> dict: """Validate, strip metadata, quarantine, scan, and store a staged upload.""" cat = (category or "").upper() if cat not in ("PHOTO", "KYC"): raise UploadValidationError("Invalid upload category. Must be PHOTO or KYC.", 422) max_bytes = PHOTO_MAX_BYTES if cat == "PHOTO" else KYC_MAX_BYTES if len(raw_bytes) == 0: raise UploadValidationError("Uploaded file is empty.", 422) if len(raw_bytes) > max_bytes: limit_mb = max_bytes // (1024 * 1024) raise UploadValidationError(f"File exceeds maximum allowed size of {limit_mb} MB.", 413) mime = detect_mime_from_magic_bytes(raw_bytes) allowed = PHOTO_ALLOWED_MIMES if cat == "PHOTO" else KYC_ALLOWED_MIMES if mime not in allowed: raise UploadValidationError("Invalid file type (magic-byte check failed).", 422) clean_bytes = strip_image_metadata_and_validate(raw_bytes, mime) upload_id = str(uuid.uuid4()) ext_map = { "image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", "image/webp": ".webp", "application/pdf": ".pdf", } ext = ext_map[mime] quarantine_dir = os.path.join(upload_root, "quarantine") clean_dir = os.path.join(upload_root, "clean") os.makedirs(quarantine_dir, exist_ok=True) os.makedirs(clean_dir, exist_ok=True) q_path = os.path.join(quarantine_dir, f"{upload_id}{ext}") with open(q_path, "wb") as f: f.write(clean_bytes) scan_status = scan_quarantined_bytes(clean_bytes) if scan_status != "CLEAN": os.remove(q_path) raise UploadValidationError("File failed security/malware scan.", 422) storage_key = f"clean/{upload_id}{ext}" os.replace(q_path, os.path.join(upload_root, storage_key)) return { "id": upload_id, "session_id": session_id, "doc_category": cat, "doc_type_id": doc_type_id, "storage_key": storage_key, "mime_type": mime, "size_bytes": len(clean_bytes), "scan_status": "CLEAN", "expires_at": datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=2), }