From 14c659fda4c9c4b923134aaf1f9d56173aa9a0b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BB=D1=8C=D0=B5=D0=B2=20=D0=9D?= =?UTF-8?q?=D0=B8=D0=BA=D0=B8=D1=82=D0=B0?= Date: Fri, 6 Nov 2026 18:09:32 +0300 Subject: [PATCH] fix: validate required schema and support bounded JPEG file objects --- REPORT.md | 2 ++ scripts/verify_storage.py | 16 ++++++++++++++++ src/messenger/attachments.py | 21 ++++++++++++++++++++- src/messenger/postgres.py | 8 ++++++-- student-tests/test_attachments.py | 14 ++++++++++++++ 5 files changed, 58 insertions(+), 3 deletions(-) diff --git a/REPORT.md b/REPORT.md index 86e16c90..bb25e15d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -60,6 +60,8 @@ docker compose up -d --wait --no-recreate Seaweed backend подключён только к отдельной `storage_backend` internal network. API к ней не подключается: filer/master/volume интерфейсы недоступны из общей API-сети. S3 gateway подключён к обеим сетям и предоставляет только S3-интерфейс на общей сети; публичных host ports у него нет. Admin identity присутствует только у gateway и bootstrap/research, API получает bucket-scoped Read/Write/List identity. +Readiness проверяет обязательные таблицы и столбцы PostgreSQL запросом WHERE false, затем доступность S3 bucket. Простого SELECT 1 недостаточно для обнаружения отсутствующей схемы. + Ни случайный UUID, ни приватный bucket не заменяют ACL: метаданные и content выдаются только после проверки PostgreSQL-сессии и членства в чате. Сессии не кэшируются. Валидный токен не открывает чужой чат. Оригинал скачивается через авторизованный API без redirect. Сообщения сохраняют порядок attachment_ids в message_attachments.position. Идемпотентность из ЛР3 атомарно сохраняет сообщение, связи и точный ответ; перестановка вложений при том же ключе считается другим body. Пропущенный attachment_ids и [] эквивалентны. UTF-8 поля сообщений/имён хранятся lossless в bytea, включая NUL, который PostgreSQL text не принимает. diff --git a/scripts/verify_storage.py b/scripts/verify_storage.py index 2921400b..b225a39d 100644 --- a/scripts/verify_storage.py +++ b/scripts/verify_storage.py @@ -133,6 +133,22 @@ print(json.dumps({"anonymous_status":anon,"unrelated_bucket_denied":denied,"back else: raise AssertionError("PostgreSQL recovery timed out") check("old_session_recovers_after_unpause", me["json"]["id"] == alice["id"]) + inside( + "from messenger.postgres import PostgresStore; s=PostgresStore(); " + "c=s.pool.getconn(); c.execute('ALTER TABLE message_requests RENAME TO message_requests_readiness_test'); " + "s.pool.putconn(c); s.close(); print('{}')" + ) + try: + absent_table = request("/health/ready") + check("missing_required_table_ready_503", absent_table["status"] == 503) + report["faults"].append({"service": "missing_message_requests", "ready": absent_table}) + finally: + inside( + "from messenger.postgres import PostgresStore; s=PostgresStore(); " + "c=s.pool.getconn(); c.execute('ALTER TABLE message_requests_readiness_test RENAME TO message_requests'); " + "s.pool.putconn(c); s.close(); print('{}')" + ) + check("schema_restore_ready_200", request("/health/ready")["status"] == 200) Path(ROOT / "evidence/storage-checks.json").write_text( json.dumps(report, ensure_ascii=False, indent=2) + "\n" ) diff --git a/src/messenger/attachments.py b/src/messenger/attachments.py index 1b037944..ecae250c 100644 --- a/src/messenger/attachments.py +++ b/src/messenger/attachments.py @@ -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) diff --git a/src/messenger/postgres.py b/src/messenger/postgres.py index 6c734001..3fa8791a 100644 --- a/src/messenger/postgres.py +++ b/src/messenger/postgres.py @@ -101,9 +101,13 @@ class PostgresStore: def ready(self): try: with self.connection() as conn: - conn.execute("SELECT 1") + conn.execute( + "SELECT u.id,c.id,m.chat_id,msg.id,s.token_digest,r.key,a.id,i.id,ma.message_id " + "FROM users u,chats c,members m,messages msg,sessions s,message_requests r," + "attachments a,upload_intents i,message_attachments ma WHERE false" + ) return True - except Failure: + except (Failure, psycopg.Error): return False def _cached_user(self, uid): diff --git a/student-tests/test_attachments.py b/student-tests/test_attachments.py index fbdf7a90..1c105076 100644 --- a/student-tests/test_attachments.py +++ b/student-tests/test_attachments.py @@ -199,3 +199,17 @@ def test_truncated_jpeg_with_forged_eoi(scenario): mime="image/jpeg", status=415, ) + + +def test_internal_jpeg_bytesio_fallback(): + import shutil + + from messenger.attachments import validate_image + + if shutil.which("djpeg") is None: + pytest.skip( + "Internal BytesIO helper requires host djpeg; HTTP JPEG validation runs in Docker regardless" + ) + stream = BytesIO(image_bytes("JPEG")) + assert validate_image(stream, "image/jpeg") == ("image/jpeg", 32, 20) + assert stream.tell() == 0