forked from mtusi2026/mtusi2026lab4
fix: bound full image validation and cover progressive JPEG and APNG
This commit is contained in:
@@ -67,6 +67,23 @@ def error(request, status, message, headers=None):
|
||||
)
|
||||
|
||||
|
||||
async def invalid_json_encoding(request: Request):
|
||||
path = request.url.path
|
||||
if request.method != "POST" or not (
|
||||
path in {"/api/v1/users", "/api/v1/chats"}
|
||||
or re.fullmatch(r"/api/v1/chats/[^/]+/messages", path)
|
||||
):
|
||||
return False
|
||||
raw = await request.body()
|
||||
try:
|
||||
raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return True
|
||||
# Literal NUL is invalid JSON; it also prevents json.loads(bytes) from
|
||||
# autodetecting BOM-less UTF-16/32. Escaped JSON \u0000 remains valid.
|
||||
return b"\x00" in raw
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_log(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
@@ -78,6 +95,8 @@ async def request_log(request: Request, call_next):
|
||||
and await request.body()
|
||||
):
|
||||
response = error(request, 400, "Вход не принимает тело запроса")
|
||||
elif await invalid_json_encoding(request):
|
||||
response = error(request, 400, "JSON должен быть закодирован в UTF-8")
|
||||
else:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
"""Synchronous attachment intake: bounded spool, full image validation, durable intent."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import sys
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .domain import Failure, timestamp
|
||||
from .image_validation import MAX_BYTES
|
||||
from .postgres import public
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
# Check dimensions before decoding. Pillow's own hard bomb threshold remains active.
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
PUBLIC_FIELDS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
@@ -42,61 +40,57 @@ def filename_valid(name):
|
||||
def validate_image(fileobj, declared_type):
|
||||
if declared_type not in {"image/png", "image/jpeg"}:
|
||||
raise Failure(415, "Ожидается PNG или JPEG")
|
||||
fileobj.seek(0)
|
||||
encoded = fileobj.read(MAX_BYTES + 1)
|
||||
if len(encoded) > MAX_BYTES:
|
||||
raise Failure(413, "Файл больше 10 MiB")
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
width, height = image.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(image.format)
|
||||
if actual != declared_type:
|
||||
raise Failure(415, "Формат изображения не соответствует MIME")
|
||||
image.verify()
|
||||
# verify() alone does not decode IDAT/JPEG scan data.
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
image.load()
|
||||
if actual == "image/jpeg":
|
||||
# libjpeg emits a warning but Pillow accepts e.g. a half scan with a
|
||||
# forged EOI. djpeg's nonzero warning exit rejects that corruption.
|
||||
fileobj.seek(0)
|
||||
fallback = None
|
||||
with subprocess.Popen(
|
||||
[sys.executable, "-m", "messenger.image_validation", declared_type],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
start_new_session=True,
|
||||
env={
|
||||
"PATH": os.environ.get("PATH", os.defpath),
|
||||
"PYTHONPATH": str(Path(__file__).resolve().parents[1]),
|
||||
"PYTHONDONTWRITEBYTECODE": "1",
|
||||
"LANG": "C.UTF-8",
|
||||
},
|
||||
) as process:
|
||||
try:
|
||||
decoder_input = fileobj
|
||||
try:
|
||||
fileobj.fileno()
|
||||
except (AttributeError, OSError):
|
||||
# Internal callers may supply BytesIO; bound the fallback too.
|
||||
fallback = tempfile.TemporaryFile()
|
||||
copied = 0
|
||||
while chunk := fileobj.read(64 * 1024):
|
||||
copied += len(chunk)
|
||||
if copied > MAX_BYTES:
|
||||
raise Failure(413, "Файл больше 10 MiB") from None
|
||||
fallback.write(chunk)
|
||||
fallback.seek(0)
|
||||
decoder_input = fallback
|
||||
decoded = subprocess.run(
|
||||
["djpeg", "-strict", "-maxmemory", "192m", "-outfile", "/dev/null"],
|
||||
stdin=decoder_input,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
output, _ = process.communicate(input=encoded, timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
# The validator can itself run djpeg: kill its whole process group
|
||||
# before releasing the upload slot, not only the Python parent.
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass # The child may have exited at the timeout boundary.
|
||||
process.communicate()
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
|
||||
finally:
|
||||
if fallback is not None:
|
||||
fallback.close()
|
||||
if decoded.returncode:
|
||||
raise Failure(415, "Повреждённое изображение")
|
||||
fileobj.seek(0)
|
||||
return actual, width, height
|
||||
except Image.DecompressionBombError:
|
||||
raise Failure(413, "Слишком много пикселей") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
if process.returncode:
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку")
|
||||
except OSError:
|
||||
raise Failure(503, "Проверка изображения временно недоступна") from None
|
||||
finally:
|
||||
del encoded
|
||||
try:
|
||||
outcome = json.loads(output)
|
||||
except (ValueError, UnicodeError):
|
||||
raise Failure(415, "Повреждённое изображение") from None
|
||||
if not isinstance(outcome, dict):
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку")
|
||||
if "error" in outcome:
|
||||
status = outcome["error"]
|
||||
if type(status) is not int or status not in {413, 415}:
|
||||
status = 415
|
||||
raise Failure(status, "Изображение не прошло ограниченную проверку")
|
||||
values = outcome.get("ok")
|
||||
if not isinstance(values, list) or len(values) != 3:
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку")
|
||||
fileobj.seek(0)
|
||||
return tuple(values)
|
||||
|
||||
|
||||
def metadata_public(row):
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Short-lived bounded pixel validation; no DB, credentials or application imports."""
|
||||
|
||||
import json
|
||||
import resource
|
||||
import subprocess
|
||||
import sys
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from .domain import Failure
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
|
||||
|
||||
def inspect_image(fileobj, declared_type):
|
||||
if declared_type not in {"image/png", "image/jpeg"}:
|
||||
raise Failure(415, "Ожидается PNG или JPEG")
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as header:
|
||||
width, height = header.size
|
||||
if width * height > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(header.format)
|
||||
if actual != declared_type:
|
||||
raise Failure(415, "Формат изображения не соответствует MIME")
|
||||
frames = getattr(header, "n_frames", 1)
|
||||
default_image = bool(getattr(header, "default_image", False))
|
||||
if width * height * frames > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей во всех кадрах")
|
||||
header.verify()
|
||||
# Drop parsed metadata before the separate strict decoder process starts.
|
||||
del header
|
||||
if actual == "image/png":
|
||||
# verify() checks CRC, but does not compare acTL's frame count with
|
||||
# every fcTL. Do not let a forged count hide a corrupt later frame.
|
||||
fileobj.seek(8)
|
||||
controls = frame_controls = 0
|
||||
declared_frames = None
|
||||
animation_data = False
|
||||
while True:
|
||||
chunk_header = fileobj.read(8)
|
||||
if len(chunk_header) != 8:
|
||||
raise ValueError("Truncated PNG chunk")
|
||||
length = int.from_bytes(chunk_header[:4], "big")
|
||||
kind = chunk_header[4:]
|
||||
controls += kind == b"acTL"
|
||||
frame_controls += kind == b"fcTL"
|
||||
animation_data |= kind == b"fdAT"
|
||||
if kind == b"acTL":
|
||||
if length != 8:
|
||||
raise ValueError("Invalid acTL length")
|
||||
declared_frames = int.from_bytes(fileobj.read(4), "big")
|
||||
fileobj.seek(length, 1) # remaining payload plus CRC
|
||||
else:
|
||||
fileobj.seek(length + 4, 1)
|
||||
if kind == b"IEND":
|
||||
break
|
||||
if controls:
|
||||
if (
|
||||
controls != 1
|
||||
or not declared_frames
|
||||
or frame_controls != declared_frames
|
||||
or declared_frames + int(default_image) != frames
|
||||
):
|
||||
raise ValueError("Invalid APNG frame count")
|
||||
elif frame_controls or animation_data:
|
||||
raise ValueError("Animation chunks without acTL")
|
||||
if actual == "image/jpeg":
|
||||
# Validate scan warnings before allocating Pillow's decoded canvas.
|
||||
# 384 MiB covers coefficient arrays for <=40M pixels and <=4 channels;
|
||||
# keeping both full decoded buffers alive could exceed the API cgroup.
|
||||
fileobj.seek(0)
|
||||
# A bounded compressed copy avoids sharing buffered file-descriptor
|
||||
# offsets with the child, and supports BytesIO callers as well.
|
||||
encoded = fileobj.read(MAX_BYTES + 1)
|
||||
if len(encoded) > MAX_BYTES:
|
||||
raise Failure(413, "Файл больше 10 MiB")
|
||||
try:
|
||||
decoded = subprocess.run(
|
||||
["djpeg", "-strict", "-maxmemory", "384m", "-outfile", "/dev/null"],
|
||||
input=encoded,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=4,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
|
||||
finally:
|
||||
del encoded
|
||||
if decoded.returncode:
|
||||
raise Failure(415, "Повреждённое изображение")
|
||||
# djpeg has already decoded every JPEG pixel, streaming output rows.
|
||||
# A second Pillow load would overlap full progressive coefficient
|
||||
# arrays with a 160 MiB CMYK canvas and violate the API's 512 MiB cap.
|
||||
fileobj.seek(0)
|
||||
return actual, width, height
|
||||
# Decode one frame at a time. Pillow may retain a previous APNG canvas
|
||||
# for compositing, but no list/copies of every decoded frame is collected.
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as image:
|
||||
decoded_pixels = 0
|
||||
for frame in range(frames):
|
||||
if decoded_pixels + width * height > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей во всех кадрах")
|
||||
image.seek(frame)
|
||||
decoded_pixels += image.size[0] * image.size[1]
|
||||
if decoded_pixels > MAX_PIXELS:
|
||||
raise Failure(413, "Слишком много пикселей во всех кадрах")
|
||||
image.load()
|
||||
# Image's context manager closes its input handle, not the decoded core.
|
||||
# Releasing the object frees native canvases before hashing/S3 publication.
|
||||
del image
|
||||
fileobj.seek(0)
|
||||
return actual, width, height
|
||||
except Image.DecompressionBombError:
|
||||
raise Failure(413, "Слишком много пикселей") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError):
|
||||
raise Failure(415, "Повреждённое изображение") from None
|
||||
|
||||
|
||||
def main():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (4, 5))
|
||||
if sys.platform == "linux":
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
|
||||
try:
|
||||
data = sys.stdin.buffer.read(MAX_BYTES + 1)
|
||||
if len(data) > MAX_BYTES:
|
||||
raise Failure(413, "Файл больше 10 MiB")
|
||||
result = inspect_image(BytesIO(data), sys.argv[1])
|
||||
print(json.dumps({"ok": result}))
|
||||
except Failure as exc:
|
||||
print(json.dumps({"error": exc.status}))
|
||||
except MemoryError:
|
||||
print(json.dumps({"error": 415}))
|
||||
except Exception:
|
||||
print(json.dumps({"error": 415}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user