fix: bound full image validation and cover progressive JPEG and APNG
This commit is contained in:
@@ -70,8 +70,8 @@ Readiness проверяет обязательные таблицы и стол
|
||||
|
||||
1. Проверяются сессия, чат, filename, MIME.
|
||||
2. Тело читается частями в spool: первые 256 KiB в RAM, далее временный файл в ограниченном tmpfs. Максимум 10 MiB, таймаут чтения 15 секунд.
|
||||
3. По одному upload slot на API, лишняя работа получает 429/Retry-After. Размеры изображения проверяются до decode: максимум 40 млн пикселей.
|
||||
4. Pillow verify и повторный полный load проверяют PNG/JPEG. Для JPEG djpeg -strict дополнительно отклоняет недодекодируемые изображения, которые Pillow может принять с предупреждением; timeout5s, maxmemory192m.
|
||||
3. По одному upload slot на API, лишняя работа получает 429/Retry-After. Сжатое содержимое передаётся короткоживущему процессу ограниченной копией до10MiB; второй10MiB-файл в tmpfs не создаётся. API не сохраняет декодированные пиксели между запросами.
|
||||
4. Child проверяет MIME и размеры до decode. Для PNG/APNG Pillow проверяет CRC и декодирует каждый кадр по очереди; общий бюджет всех canvas, включая default image, не более40млн пикселей. Raw acTL/fcTL сверяются, чтобы нулевое/поддельное число кадров не скрывало повреждение. Для JPEG после проверки метаданных строгий djpeg полностью декодирует пиксели построчно в/dev/null, с nativebudget384MiB и timeout4s. Второй полный Pillow.load JPEG не выполняется: он избыточен и у progressiveCMYK мог одновременно держать коэффициенты320MB и canvas160MB. Child Linux address-space limit512MiB, CPU4s; parent walltimeout5s завершает всю process group, включая native grandchildren. Ошибка/падение/таймаут декодера даёт415, превышение bytes/pixel budget413; недоступность запуска процесса503.
|
||||
5. После полной валидации фиксируется durable upload_intent. Под его row lock выполняются S3 PUT и транзакция ready metadata + удаление intent.
|
||||
6. Только успешное завершение COMMIT даёт 201 ready с variants=[] и error_code=null. SHA-256/size/MIME относятся к исходным bytes.
|
||||
|
||||
@@ -98,7 +98,7 @@ docker compose run --rm --no-deps research
|
||||
|
||||
Стоимость обхода измеряется на10/100/1000 добавленных intact attachments, по3 dry-run, page_size100. Перед измерением все добавленные объекты выдерживаются за границу grace, чтобы fresh-skip не менял профиль работы. Точные размеры с учётом сохранённых fault fixtures находятся в JSON. Измеряются время и количество просмотренных объектов/метаданных; это SQL+S3 обход, не HTTP throughput.
|
||||
|
||||
После сохранённых измерений внесена отдельная правка `domain.boundary`: строгая RFC3339Z-дата с календарной проверкой и целочисленная версия cursor вместо расширений Python ISO parser. Этот путь не используется исследованием сверки или image upload. Исходные hashes в raw JSON оставлены как снимок измеренного runtime, не переписаны под новый файл. Финальные HTTP/unit регрессии проверяют эту правку отдельно.
|
||||
После сохранённых измерений отдельно исправлены строгий RFC3339Z cursor, UTF-8 JSON guard и validation edge cases progressive JPEG/APNG. Сам reconciler, S3 adapter и схема этого эксперимента не изменились. Исходные hashes в raw JSON оставлены как снимок измеренного runtime, не переписаны под новые файлы. Финальные HTTP/unit регрессии и отдельные image-validation receipts проверяют последние изменения; они не выдаются за повторный замер исследования сверки.
|
||||
|
||||
### Результат исследовательского прогона
|
||||
|
||||
@@ -148,7 +148,7 @@ Before/after peaks не выросли: начальная загрузка пр
|
||||
- Нет распределённого COMMIT через PostgreSQL и S3: остатки допустимы до grace/apply. Уникальные immutable server keys и intent делают выбранную очистку безопасной для штатного API; конкурентное ручное изменение администратором после HEAD находится вне этой гарантии.
|
||||
- Очереди обработки изображений нет: ЛР4 синхронная, thumbnail/crop/optimized относятся к ЛР5.
|
||||
- HTTP допустим для локального изолированного стенда с синтетическими данными. Удалённая передача секретов требует TLS.
|
||||
- Native decoder/libjpeg ограничен memory/time/cgroup; полная корректность каждого экзотического изображения зависит от библиотечного декодера. Специально проверены конкретные повреждения из замечаний преподавателя.
|
||||
- Native decoder/libjpeg и Pillow ограничены memory/time/cgroup; корректность декодирования зависит от закреплённых библиотек. Проверены конкретные повреждения из замечаний,36M RGB progressive,40M CMYK progressive и последовательность APNG40M→CMYK40M→RGB36M→обычныйPNG при512MiB API безOOM. Кадры APNG валидируются все, а thumbnail следующей ЛР5 строится по первому кадру; такая политика не изменяет original bytes.
|
||||
- Client-side deadline ограничивает ожидание одного обращения к PostgreSQL, а не весь HTTP-путь; при неопределённом результате записи ключ идемпотентности защищает повтор сообщения. Upload не имеет такого ключа и не должен автоматически повторяться как будто это тот же объект.
|
||||
|
||||
## Источники
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ Durable intent до S3 PUT, row lock на время PUT/финализации
|
||||
## Протокол upload
|
||||
|
||||
1. Поток HTTP складывается в ограниченный spool: 256 KiB в RAM, затем временный файл на ограниченном tmpfs; максимум 10 MiB.
|
||||
2. После полного приёма выполняется полная проверка PNG/JPEG. Пиксельный предел применяется до decode. Для JPEG строгий djpeg отвергает предупреждения о повреждении, которые Pillow иногда допускает.
|
||||
2. После полного приёма короткоживущий ограниченный child проверяет PNG/JPEG. Пиксельный предел применяется до decode: для APNG это сумма canvas всех кадров≤40M. JPEG полностью декодирует строгий djpeg384MiB построчно, PNG/APNG декодирует Pillow; decoded buffers не остаются в API. Последние edge исправлены после исходного измерения сверки, его raw snapshot не переписывался.
|
||||
3. Создаётся и фиксируется upload_intent с уникальным server key.
|
||||
4. Новая транзакция блокирует intent, выполняет S3 PUT и создаёт ready attachment, удаляет intent, COMMIT.
|
||||
5. Только после успешной фиксации возвращается 201. При неопределённом исходе COMMIT объект немедленно не удаляется.
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Full-range JPEG and bounded multi-frame PNG regressions."""
|
||||
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from client import Client
|
||||
from PIL import Image
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def scenario():
|
||||
c = Client(os.getenv("BASE_URL", "http://127.0.0.1:8084"))
|
||||
return c, *c.bootstrap()
|
||||
|
||||
|
||||
def upload(scenario, data, mime, expected):
|
||||
c, alice, _, _, chat = scenario
|
||||
return c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=edge.png",
|
||||
expected,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if expected == 201 else None,
|
||||
)
|
||||
|
||||
|
||||
def progressive_jpeg():
|
||||
output = BytesIO()
|
||||
image = Image.new("RGB", (6000, 6000), "blue")
|
||||
try:
|
||||
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
|
||||
finally:
|
||||
image.close()
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def apng(size=(16, 16), default_image=False):
|
||||
output = BytesIO()
|
||||
first, second = Image.new("RGB", size, "red"), Image.new("RGB", size, "blue")
|
||||
try:
|
||||
first.save(
|
||||
output,
|
||||
"PNG",
|
||||
save_all=True,
|
||||
append_images=[second],
|
||||
duration=100,
|
||||
loop=0,
|
||||
default_image=default_image,
|
||||
)
|
||||
finally:
|
||||
first.close()
|
||||
second.close()
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def broken_later_frame(data):
|
||||
result, position = bytearray(data[:8]), 8
|
||||
while position < len(data):
|
||||
length = struct.unpack(">I", data[position : position + 4])[0]
|
||||
kind = data[position + 4 : position + 8]
|
||||
payload = data[position + 8 : position + 8 + length]
|
||||
if kind == b"fdAT":
|
||||
payload = payload[:4] + b"not-a-valid-deflate-stream"
|
||||
result += (
|
||||
struct.pack(">I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack(">I", zlib.crc32(kind + payload))
|
||||
)
|
||||
position += length + 12
|
||||
return bytes(result)
|
||||
|
||||
|
||||
def test_36m_progressive_jpeg_is_valid_and_unchanged(scenario):
|
||||
data = progressive_jpeg()
|
||||
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
|
||||
c, _, bob, _, _ = scenario
|
||||
assert (
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
|
||||
)
|
||||
|
||||
|
||||
def test_apng_corrupt_later_frame_is_rejected(scenario):
|
||||
upload(scenario, broken_later_frame(apng()), "image/png", 415)
|
||||
|
||||
|
||||
def test_valid_small_apng_is_accepted_and_unchanged(scenario):
|
||||
data = apng()
|
||||
attachment = upload(scenario, data, "image/png", 201)["json"]
|
||||
c, _, bob, _, _ = scenario
|
||||
assert (
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
|
||||
)
|
||||
|
||||
|
||||
def test_apng_cumulative_canvas_limit(scenario):
|
||||
# Two 25M-pixel canvases exceed the total 40M decode budget.
|
||||
upload(scenario, apng((5000, 5000)), "image/png", 413)
|
||||
|
||||
|
||||
def test_apng_forged_frame_count_cannot_hide_bad_frame(scenario):
|
||||
data = bytearray(broken_later_frame(apng()))
|
||||
position = 8
|
||||
while position < len(data):
|
||||
length = struct.unpack(">I", data[position : position + 4])[0]
|
||||
kind = bytes(data[position + 4 : position + 8])
|
||||
if kind == b"acTL":
|
||||
data[position + 8 : position + 12] = struct.pack(">I", 1)
|
||||
payload = bytes(data[position + 8 : position + 8 + length])
|
||||
data[position + 8 + length : position + 12 + length] = struct.pack(
|
||||
">I", zlib.crc32(kind + payload)
|
||||
)
|
||||
break
|
||||
position += length + 12
|
||||
upload(scenario, bytes(data), "image/png", 415)
|
||||
|
||||
|
||||
def test_apng_exact_cumulative_limit_is_accepted(scenario):
|
||||
upload(scenario, apng((4000, 5000)), "image/png", 201)
|
||||
|
||||
|
||||
def test_40m_cmyk_progressive_jpeg_is_accepted(scenario):
|
||||
output = BytesIO()
|
||||
image = Image.new("CMYK", (8000, 5000), (0, 128, 128, 0))
|
||||
try:
|
||||
image.save(output, "JPEG", quality=90, progressive=True, subsampling=0)
|
||||
finally:
|
||||
image.close()
|
||||
data = output.getvalue()
|
||||
attachment = upload(scenario, data, "image/jpeg", 201)["json"]
|
||||
c, _, bob, _, _ = scenario
|
||||
assert (
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
|
||||
)
|
||||
|
||||
|
||||
def test_repeated_large_image_sequence_stays_available(scenario):
|
||||
# Formerly retained APNG canvases could overlap the next CMYK decoder.
|
||||
c, _, bob, _, _ = scenario
|
||||
data = apng((4000, 5000))
|
||||
attachment = upload(scenario, data, "image/png", 201)["json"]
|
||||
assert (
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"] == data
|
||||
)
|
||||
del data
|
||||
test_40m_cmyk_progressive_jpeg_is_accepted(scenario)
|
||||
test_36m_progressive_jpeg_is_valid_and_unchanged(scenario)
|
||||
data = BytesIO()
|
||||
image = Image.new("RGB", (16, 16), "green")
|
||||
image.save(data, "PNG")
|
||||
image.close()
|
||||
attachment = upload(scenario, data.getvalue(), "image/png", 201)["json"]
|
||||
assert (
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)["bytes"]
|
||||
== data.getvalue()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("progressive", [False, True])
|
||||
def test_small_cmyk_jpeg(progressive, scenario):
|
||||
output = BytesIO()
|
||||
image = Image.new("CMYK", (24, 18), (0, 128, 128, 0))
|
||||
image.save(output, "JPEG", progressive=progressive)
|
||||
image.close()
|
||||
upload(scenario, output.getvalue(), "image/jpeg", 201)
|
||||
|
||||
|
||||
def test_invalid_zero_frame_count_is_rejected(scenario):
|
||||
data = apng()
|
||||
result, position, controls = bytearray(data[:8]), 8, 0
|
||||
while position < len(data):
|
||||
length = struct.unpack(">I", data[position : position + 4])[0]
|
||||
kind = data[position + 4 : position + 8]
|
||||
payload = data[position + 8 : position + 8 + length]
|
||||
position += length + 12
|
||||
if kind == b"fcTL":
|
||||
controls += 1
|
||||
if controls > 1:
|
||||
continue
|
||||
if kind == b"fdAT":
|
||||
continue
|
||||
if kind == b"acTL":
|
||||
payload = bytes(4) + payload[4:]
|
||||
result += (
|
||||
struct.pack(">I", len(payload))
|
||||
+ kind
|
||||
+ payload
|
||||
+ struct.pack(">I", zlib.crc32(kind + payload))
|
||||
)
|
||||
upload(scenario, bytes(result), "image/png", 415)
|
||||
|
||||
|
||||
def test_valid_apng_default_image(scenario):
|
||||
upload(scenario, apng(default_image=True), "image/png", 201)
|
||||
@@ -0,0 +1,140 @@
|
||||
import base64
|
||||
import codecs
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from client import Client
|
||||
|
||||
ENCODINGS = [
|
||||
"utf-16",
|
||||
"utf-16-le",
|
||||
"utf-16-be",
|
||||
"utf-16-be-bom",
|
||||
"utf-32",
|
||||
"utf-32-le",
|
||||
"utf-32-be",
|
||||
"utf-32-be-bom",
|
||||
]
|
||||
|
||||
|
||||
def encoded(body, encoding):
|
||||
text = json.dumps(body, ensure_ascii=False)
|
||||
if encoding == "utf-16-be-bom":
|
||||
return codecs.BOM_UTF16_BE + text.encode("utf-16-be")
|
||||
if encoding == "utf-32-be-bom":
|
||||
return codecs.BOM_UTF32_BE + text.encode("utf-32-be")
|
||||
return text.encode(encoding)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def encoding_scenario():
|
||||
c = Client(os.environ["BASE_URL"])
|
||||
return c, *c.bootstrap()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoding", ENCODINGS)
|
||||
def test_non_utf8_registration_has_no_write(encoding_scenario, encoding):
|
||||
c, *_ = encoding_scenario
|
||||
body = {
|
||||
"username": "enc_" + uuid.uuid4().hex[:14],
|
||||
"display_name": "Никита\u0000имя",
|
||||
"password": "Пароль:тестовый-12345",
|
||||
}
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=encoded(body, encoding),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
# UNIQUE username proves the rejected request did not insert a user.
|
||||
created = c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
assert created["display_name"] == body["display_name"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoding", ENCODINGS)
|
||||
def test_non_utf8_chat_has_no_write(encoding_scenario, encoding):
|
||||
c, alice, *_ = encoding_scenario
|
||||
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
|
||||
body = {"title": "Чат\u0000" + uuid.uuid4().hex, "member_ids": [alice["id"]]}
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
400,
|
||||
actor=alice,
|
||||
raw=encoded(body, encoding),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
|
||||
assert before == after
|
||||
assert (
|
||||
c.call("POST", "/api/v1/chats", 201, actor=alice, body=body, schema="Chat")["json"]["title"]
|
||||
== body["title"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoding", ENCODINGS)
|
||||
def test_non_utf8_message_has_no_write(encoding_scenario, encoding):
|
||||
c, alice, _, _, chat = encoding_scenario
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
key = uuid.uuid4().hex
|
||||
body = {"text": "Сообщение\u0000" + key}
|
||||
c.call(
|
||||
"POST",
|
||||
path,
|
||||
400,
|
||||
actor=alice,
|
||||
raw=encoded(body, encoding),
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
)
|
||||
history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"]
|
||||
assert all(item["text"] != body["text"] for item in history)
|
||||
good = c.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)["json"]
|
||||
repeat = c.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body=body,
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)["json"]
|
||||
assert good == repeat and good["text"] == body["text"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
|
||||
def test_valid_utf8_registration_and_login(encoding_scenario, encoding):
|
||||
c, *_ = encoding_scenario
|
||||
body = {
|
||||
"username": "utf8_" + uuid.uuid4().hex[:14],
|
||||
"display_name": "Юникод\u0000😀",
|
||||
"password": "Пароль:тестовый-12345",
|
||||
}
|
||||
user = c.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
201,
|
||||
raw=encoded(body, encoding),
|
||||
headers={"Content-Type": "application/json"},
|
||||
schema="User",
|
||||
)["json"]
|
||||
assert user["display_name"] == body["display_name"]
|
||||
credential = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
|
||||
session = c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credential},
|
||||
schema="Session",
|
||||
)["json"]
|
||||
assert session["user"] == user
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Process boundary failures must stay bounded and map to contract errors."""
|
||||
|
||||
import signal
|
||||
import subprocess
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
|
||||
from messenger.attachments import validate_image
|
||||
from messenger.domain import Failure
|
||||
|
||||
|
||||
class FakeProcess:
|
||||
pid = 999999999
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, output=b'{"ok":["image/png",1,1]}', crash=False, timeout=False):
|
||||
self.output, self.timeout, self.calls = output, timeout, 0
|
||||
self.returncode = -11 if crash else 0
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
def communicate(self, input=None, timeout=None):
|
||||
self.calls += 1
|
||||
if self.timeout and self.calls == 1:
|
||||
raise subprocess.TimeoutExpired("validator", 5)
|
||||
return self.output, b""
|
||||
|
||||
|
||||
def test_timeout_kills_group_and_returns_415(monkeypatch):
|
||||
process = FakeProcess(timeout=True)
|
||||
killed = []
|
||||
monkeypatch.setattr("messenger.attachments.subprocess.Popen", lambda *a, **k: process)
|
||||
monkeypatch.setattr(
|
||||
"messenger.attachments.os.killpg", lambda pid, sig: killed.append((pid, sig))
|
||||
)
|
||||
with pytest.raises(Failure) as failure:
|
||||
validate_image(BytesIO(b"synthetic"), "image/png")
|
||||
assert failure.value.status == 415
|
||||
assert killed == [(process.pid, signal.SIGKILL)]
|
||||
assert process.calls == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"output,crash", [(b"", True), (b"not-json", False), (b"null", False), (b"[]", False)]
|
||||
)
|
||||
def test_crash_or_malformed_child_result_returns_415(monkeypatch, output, crash):
|
||||
monkeypatch.setattr(
|
||||
"messenger.attachments.subprocess.Popen", lambda *a, **k: FakeProcess(output, crash=crash)
|
||||
)
|
||||
with pytest.raises(Failure) as failure:
|
||||
validate_image(BytesIO(b"synthetic"), "image/png")
|
||||
assert failure.value.status == 415
|
||||
Reference in New Issue
Block a user