forked from mtusi2026/mtusi2026lab4
fix: validate required schema and support bounded JPEG file objects
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -59,10 +60,25 @@ def validate_image(fileobj, declared_type):
|
||||
# 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
|
||||
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=fileobj,
|
||||
stdin=decoder_input,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=5,
|
||||
@@ -70,6 +86,9 @@ def validate_image(fileobj, declared_type):
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
|
||||
finally:
|
||||
if fallback is not None:
|
||||
fallback.close()
|
||||
if decoded.returncode:
|
||||
raise Failure(415, "Повреждённое изображение")
|
||||
fileobj.seek(0)
|
||||
|
||||
Reference in New Issue
Block a user