fix: validate required schema and support bounded JPEG file objects
This commit is contained in:
@@ -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 не принимает.
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user