Reject ambiguous PNG headers before pixel validation

This commit is contained in:
Artyom
2026-11-06 21:33:09 +03:00
parent bcbd4ebc02
commit 7c8a1a6489
21 changed files with 498 additions and 34 deletions
+51
View File
@@ -0,0 +1,51 @@
# Исправление major: повторный IHDR в PNG
Исходный snapshot: `7342d5d97a5e50659a6c44c56d5a87e62aa87c1f`.
Среда: существующая `.venv`, Python 3.14.5, Pillow 13.0.0, macOS. Окружения не устанавливались.
SHA реализации и Git blob-хеши изменённых файлов фиксируются в `manifest.json` при архивации; архивный коммит меняет только документы и evidence.
## Причина и результат
Инспектор проверял лимит по размерам, возвращённым Pillow, а поток пикселей — по первому IHDR по фиксированному смещению. Pillow использует последний IHDR перед IDAT. Точный PNG из ревью: сигнатура, IHDR 1×1 RGB8, IHDR 2×2 RGB8, IDAT с `zlib.compress(bytes(4))`, IEND, корректные CRC; 94 байта, SHA-256 `ca1c6483affee11cde4a5f91fdc6f09558951fb2108f044acd4c1eb5b85423fc`.
До исправления независимый `Image.load()` выдавал `OSError: image file is truncated`, инспектор принимал файл, ASGI-маршрут возвращал `201 ready` (`before-confirmed.txt`). После исправления маршрут отвечает `415 unsupported_media_type` с `X-Request-Id` и `X-Instance-Id`; нет транзакций, COMMIT, вызовов репозитория/S3 и событий.
Новый проход по границам чанков требует первый IHDR длины 13 байт и запрещает любой повтор до IEND. Единственный разобранный заголовок используется для метаданных/лимита пикселей и расчёта строк. Проход не копирует payload: O(число чанков) времени и O(1) дополнительной памяти. CRC по-прежнему проверяет Pillow; распаковка идёт блоками по 64 KiB после лимита 40 MP. Новых зависимостей нет.
Изменение остаётся в инфраструктуре attachments. SQLAlchemy/Alembic, хранилища, слоты, контейнеры и JPEG не менялись. Документация проверена через Context7 `/python-pillow/pillow/13.0.0`: [Image.open](https://github.com/python-pillow/pillow/blob/13.0.0/docs/reference/Image.rst) выполняет ленивое чтение; `verify` не заменяет проверку пикселей.
## Выполненные проверки
| Команда | Результат | Вывод |
| --- | --- | --- |
| `.venv/bin/pytest -q --tb=short student-tests/unit/test_image_inspection.py::test_duplicate_ihdr_cannot_disagree_with_pixel_validation student-tests/unit/test_png_upload.py` на исходном приложении | 2 failed, 1 passed: инспектор не выдаёт исключения, upload возвращает 201 вместо 415 | `before-confirmed.txt` |
| `.venv/bin/pytest -q --tb=short student-tests/unit/test_image_inspection.py student-tests/unit/test_png_upload.py` | 227 passed | `targeted.txt` |
| `make student-test PYTEST_ARGS='-q --tb=short student-tests/unit'` | 407 passed | `unit.txt` |
| `make student-test PYTEST_ARGS='--collect-only -q student-tests/api/test_attachments.py'` | 40 тестов собраны, fixtures не исполнялись | `api-collection.txt` |
| `make student-test PYTEST_ARGS='--collect-only -q -m stack student-tests/stack/test_attachment_faults.py'` | 7 тестов собраны, fixtures не исполнялись | `stack-collection.txt` |
| `make check` | PASS: структура, локальные refs, синтаксис | `check.txt` |
| `make validate` | PASS: OpenAPI 3.1 и JSON Schema | `validate.txt` |
| `make lint` | PASS: ruff check/format (166 файлов), ty | `lint.txt` |
| `openspec validate --all --strict --no-interactive` до архивации | 19 passed, 0 failed | `openspec.txt` |
| Прямые вызовы функций `test_*` через `runpy.run_path('student-tests/api/test_bounded_contexts.py')` | 19 статических проверок границ PASS; pytest-fixture БД не вызывалась | `boundaries.txt` |
Новые проверки покрывают одинаковый IHDR, изменение размеров/глубины/цвета/interlace, повтор до, между и после IDAT, заголовок не первым чанком и неверную длину. Существующая матрица PNG/Adam7, фильтров, лимита 40 MP и ограниченных Python-аллокаций проходит. Это не замер RSS/cgroup и не проверка реальных PostgreSQL/RustFS/LB.
В API-матрице также исправлено число `ids`: предыдущий фикс добавил случай битого zlib без соответствующего имени. Новая collection проверяет согласованность всей матрицы. Публичные `tests/`, `contracts/`, `README.md` и `COURSE.md` не менялись.
Промежуточные неуспешные попытки сохранены: `before.txt` — первый ASGI replay остановился на неполной подмене transaction; после настройки mock контекста и валидных id/дат получен настоящий `201` в `before-confirmed.txt`. `lint-initial.txt` — превышение длины строки параметризации; исправлено штатным ruff format перед успешным lint.
## Обязательные проверки финального этапа
Docker, нагрузка и бенчмарки на этом этапе не запускались. Инвентаризация Docker не выполнялась, фон неизвестен, чужие прогоны не используются. Этот фикс дополняет незавершённую динамическую проверку из `evidence/png-validation-fix/NOTES.md`; оба исправления проверяются одним финальным прогоном на итоговом коде:
1. `make student-test PYTEST_ARGS='-q student-tests/api/test_attachments.py student-tests/api/test_message_attachments.py student-tests/api/test_upload_consistency.py'`. Здесь требуется настоящий PostgreSQL; collection выше исполнение тестов не заменяет.
2. `make test` и `make upload-faults` через LB. В собственную негативную матрицу включены оба PNG из ревью. Зафиксировать 415, отсутствие 500 и новых строк/объектов; корректные PNG/JPEG должны сохраняться и скачиваться побайтно.
3. Затронутая матрица памяти: 3 слота × 1/10 MiB × 10/20/40 одновременных загрузок, три серии (`make upload-memory ARGS='--slots 3 --out evidence/png-header-final/upload-memory/run1'`, затем отдельные run2/run3). Дополнительно ≥10 одновременных сильно сжатых PNG на 40 MP с высокой глубиной цвета. Записать фон, cgroup, успешные ответы/ошибки, OOM и пик относительно лимита. Это общий долг обоих PNG-фиксов; повторять одни и те же серии для каждого фикса не нужно. Если финальный отчёт заявляет сравнение 64/3, контрольную серию нужно подтвердить новым кодом либо явно оставить исторической.
4. Повторить затронутую часть upload во время `make reconcile-demo` с проверкой сохранности готовых вложений. Reconciler, его SQL и обход объектов не изменены; 27 пригодных измерений стоимости 1k/10k/30k/100k сохраняются с исходными SHA, повторять их из-за этого фикса не требуется.
Прежние доказательства скачивания, persistence/failover, bootstrap, прав S3 и текстового пути сохраняются с исходными SHA; финальный агент проверяет применимость. Новые числа производительности или расхода памяти из unit-тестов не выводятся. Для подготовки финального стенда нельзя удалять пользовательские данные или постоянные volumes.
## Ограничения для отчётного агента
Известный minor `src/messenger/messaging/entrypoints/schemas.py:35` с непарными Unicode-суррогатами сохранён: HTTP 500 зафиксирован в `evidence/forward-final-2026-11-06/known-minor-http.txt`. Этот код не менялся; minor не входит в назначенное исправление. Итоговый `REPORT.md`, release и публикация принадлежат следующим этапам runner.
@@ -0,0 +1,43 @@
.venv/bin/pytest --collect-only -q student-tests/api/test_attachments.py
student-tests/api/test_attachments.py::test_member_uploads_and_another_member_downloads
student-tests/api/test_attachments.py::test_object_key_is_assigned_by_server
student-tests/api/test_attachments.py::test_jpeg_is_accepted_by_content
student-tests/api/test_attachments.py::test_access_is_checked_before_content
student-tests/api/test_attachments.py::test_token_is_checked_before_the_declared_size
student-tests/api/test_attachments.py::test_exact_limit_is_accepted
student-tests/api/test_attachments.py::test_one_byte_over_with_content_length
student-tests/api/test_attachments.py::test_one_byte_over_chunked
student-tests/api/test_attachments.py::test_pixel_limit_is_read_from_header[8000-5000-201]
student-tests/api/test_attachments.py::test_pixel_limit_is_read_from_header[8001-5000-413]
student-tests/api/test_attachments.py::test_pixel_limit_is_read_from_header[100000-100000-413]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[invalid-zlib]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[duplicate-ihdr]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[jpeg-as-png]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[gif-as-png]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[webp-as-png]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[text-as-png]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[png-as-jpeg]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[truncated-png]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[truncated-jpeg]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[empty]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[octet-stream]
student-tests/api/test_attachments.py::test_type_is_checked_by_content[gif-type]
student-tests/api/test_attachments.py::test_missing_content_type_is_unsupported
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[../a.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[a/b.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[a\\b.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[a\x00.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[a\x01.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[a\x7f.png]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[ ]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx]
student-tests/api/test_attachments.py::test_dangerous_filename_is_rejected[None]
student-tests/api/test_attachments.py::test_display_name_is_kept[\u0444\u043e\u0442\u043e 1.png]
student-tests/api/test_attachments.py::test_display_name_is_kept[\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f\u044f]
student-tests/api/test_attachments.py::test_display_name_is_kept[%41.png]
student-tests/api/test_attachments.py::test_only_original_variant_exists
student-tests/api/test_attachments.py::test_storage_failure_leaves_nothing_visible
student-tests/api/test_attachments.py::test_lost_object_is_not_found
40 tests collected in 0.10s
@@ -0,0 +1,17 @@
F.F [100%]
=================================== FAILURES ===================================
__________ test_duplicate_ihdr_cannot_disagree_with_pixel_validation ___________
student-tests/unit/test_image_inspection.py:77: in test_duplicate_ihdr_cannot_disagree_with_pixel_validation
with pytest.raises(UnsupportedImage):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE UnsupportedImage
_____ test_broken_png_returns_415_before_any_storage_write[duplicate-ihdr] _____
student-tests/unit/test_png_upload.py:71: in test_broken_png_returns_415_before_any_storage_write
assert response.status_code == 415, response.text
E AssertionError: {"id":"9024b438-7120-4966-9d7f-97a7e8cbafc3","chat_id":"3b19b246-45e4-4523-a9b8-9fea60ba8067","owner_id":"24afabb2-ec20-4630-8bc0-519ef7916568","filename":"broken.png","content_type":"image/png","size_bytes":94,"sha256":"ca1c6483affee11cde4a5f91fdc6f09558951fb2108f044acd4c1eb5b85423fc","status":"ready","variants":[],"error_code":null,"created_at":"2026-11-06T00:00:00Z","updated_at":"2026-11-06T00:00:00Z"}
E assert 201 == 415
E + where 201 = <Response [201 Created]>.status_code
=========================== short test summary info ============================
FAILED student-tests/unit/test_image_inspection.py::test_duplicate_ihdr_cannot_disagree_with_pixel_validation
FAILED student-tests/unit/test_png_upload.py::test_broken_png_returns_415_before_any_storage_write[duplicate-ihdr]
2 failed, 1 passed in 0.15s
+165
View File
@@ -0,0 +1,165 @@
F.F [100%]
=================================== FAILURES ===================================
__________ test_duplicate_ihdr_cannot_disagree_with_pixel_validation ___________
async def test_duplicate_ihdr_cannot_disagree_with_pixel_validation() -> None:
assert len(DUPLICATE_IHDR_PNG) == 94
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image:
assert image.size == (2, 2)
image.verify()
with Image.open(BytesIO(DUPLICATE_IHDR_PNG)) as image, pytest.raises(OSError):
image.load()
> with pytest.raises(UnsupportedImage):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E Failed: DID NOT RAISE UnsupportedImage
student-tests/unit/test_image_inspection.py:77: Failed
_____ test_broken_png_returns_415_before_any_storage_write[duplicate-ihdr] _____
data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\rIHDR\...\x00\x00\x00\xfd\xd4\x9as\x00\x00\x00\x0cIDATx\x9cc```\x00\x00\x00\x04\x00\x01\xf6\x178U\x00\x00\x00\x00IEND\xaeB`\x82'
@pytest.mark.parametrize("data", [BROKEN_PNG, DUPLICATE_IHDR_PNG], ids=["bad-zlib", "duplicate-ihdr"])
async def test_broken_png_returns_415_before_any_storage_write(data: bytes) -> None:
uow = Mock(spec=AttachmentsUnitOfWork)
uow.attachments = AsyncMock(spec=AttachmentRepository)
uow.collect_new_events.return_value = []
storage = AsyncMock(spec=ObjectStorage)
membership = AsyncMock(spec=ChatMembership)
membership.is_member.return_value = True
logger = NullLogger()
publisher = RecordingPublisher()
handler = UploadAttachmentHandler(
uow,
membership,
PillowImageInspector(40_000_000, 1),
storage,
clock=Mock(spec=Clock),
ids=Mock(spec=IdGenerator),
limit=10_485_760,
slots=UploadSlots(1),
logger=logger,
)
bus = AttachmentsCommandBus({UploadAttachment: handler}, uow, publisher)
container = SimpleNamespace(get=AsyncMock(return_value=bus))
owner, chat = uuid4(), uuid4()
async def guard(scope: Scope) -> None:
scope["state"].update(actor=owner, dishka_container=container)
app = FastAPI()
app.include_router(uploads_router)
install(app, logger, ERROR_CODES, lambda _: "Bearer", "offline-test")
transport = ASGITransport(
app=RequestPipeline(app, logger, 10_485_760, 5, guard, "offline-test")
)
async with AsyncClient(transport=transport, base_url="http://testserver") as http:
> response = await http.post(
f"/api/v1/chats/{chat}/attachments?filename=broken.png",
headers={"Content-Type": "image/png", "X-Request-Id": "png-regression"},
content=data,
)
student-tests/unit/test_png_upload.py:64:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
.venv/lib/python3.14/site-packages/httpx/_client.py:1859: in post
return await self.request(
.venv/lib/python3.14/site-packages/httpx/_client.py:1540: in request
return await self.send(request, auth=auth, follow_redirects=follow_redirects)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14/site-packages/httpx/_client.py:1629: in send
response = await self._send_handling_auth(
.venv/lib/python3.14/site-packages/httpx/_client.py:1657: in _send_handling_auth
response = await self._send_handling_redirects(
.venv/lib/python3.14/site-packages/httpx/_client.py:1694: in _send_handling_redirects
response = await self._send_single_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14/site-packages/httpx/_client.py:1730: in _send_single_request
response = await transport.handle_async_request(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.14/site-packages/httpx/_transports/asgi.py:170: in handle_async_request
await self.app(scope, receive, send)
src/messenger/shared/entrypoints/pipeline.py:162: in __call__
await self._app(scope, *pace.around(limited_receive, wrapped_send))
.venv/lib/python3.14/site-packages/fastapi/applications.py:1163: in __call__
await super().__call__(scope, receive, send)
.venv/lib/python3.14/site-packages/starlette/applications.py:96: in __call__
await self.middleware_stack(scope, receive, send)
.venv/lib/python3.14/site-packages/starlette/middleware/errors.py:186: in __call__
raise exc
.venv/lib/python3.14/site-packages/starlette/middleware/errors.py:164: in __call__
await self.app(scope, receive, _send)
.venv/lib/python3.14/site-packages/starlette/middleware/exceptions.py:63: in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
.venv/lib/python3.14/site-packages/starlette/_exception_handler.py:53: in wrapped_app
raise exc
.venv/lib/python3.14/site-packages/starlette/_exception_handler.py:42: in wrapped_app
await app(scope, receive, sender)
.venv/lib/python3.14/site-packages/fastapi/middleware/asyncexitstack.py:18: in __call__
await self.app(scope, receive, send)
.venv/lib/python3.14/site-packages/starlette/routing.py:676: in __call__
await self.middleware_stack(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:2734: in app
await route.handle(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:1780: in handle
await self.original_router.handle(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:2789: in handle
await included_router._handle_selected(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:1800: in _handle_selected
await original_route.handle(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:1279: in handle
await app(scope, receive, send)
.venv/lib/python3.14/site-packages/fastapi/routing.py:158: in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
.venv/lib/python3.14/site-packages/starlette/_exception_handler.py:53: in wrapped_app
raise exc
.venv/lib/python3.14/site-packages/starlette/_exception_handler.py:42: in wrapped_app
await app(scope, receive, sender)
.venv/lib/python3.14/site-packages/fastapi/routing.py:144: in app
response = await f(request)
^^^^^^^^^^^^^^^^
.venv/lib/python3.14/site-packages/fastapi/routing.py:706: in app
raw_response = await run_endpoint_function(
.venv/lib/python3.14/site-packages/fastapi/routing.py:352: in run_endpoint_function
return await dependant.call(**values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<dishka_func_upload_attachment>:3: in dishka_func_upload_attachment
return await func_upload_attachment(*args, **kwargs, bus=await container.get(AttachmentsCommandBus, ''))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
src/messenger/attachments/entrypoints/http.py:42: in upload_attachment
attachment = await bus.execute(
src/messenger/shared/application/messagebus.py:32: in execute
return await handler(command)
^^^^^^^^^^^^^^^^^^^^^^
src/messenger/attachments/application/handlers.py:86: in __call__
attachment = await self._write(command, filename, declared)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <messenger.attachments.application.handlers.UploadAttachmentHandler object at 0x1071417e0>
command = UploadAttachment(owner_id=UUID('c6753b91-81b7-4b38-8940-beb79af87481'), chat_id=UUID('38a84a73-25f2-4ff2-8381-2d63f6f2a205'), filename='broken.png', content_type='image/png', body=<async_generator object body_of at 0x10712d8c0>)
filename = Filename(value='broken.png'), declared = <ImageKind.PNG: 'image/png'>
async def _write(
self, command: UploadAttachment, filename: Filename, declared: ImageKind
) -> Attachment:
data, digest = await read_limited(command.body, self._limit)
image = await self._images.inspect(data, declared)
attachment = Attachment.stage(
attachment_id=self._ids.new_id(),
chat_id=command.chat_id,
owner_id=command.owner_id,
filename=filename,
image=image,
size_bytes=len(data),
sha256=digest,
now=self._clock.now(),
)
> async with self._uow.transaction():
^^^^^^^^^^^^^^^^^^^^^^^
E TypeError: 'unittest.mock.Mock' object does not support the asynchronous context manager protocol (missed __aexit__ method)
src/messenger/attachments/application/handlers.py:112: TypeError
=========================== short test summary info ============================
FAILED student-tests/unit/test_image_inspection.py::test_duplicate_ihdr_cannot_disagree_with_pixel_validation
FAILED student-tests/unit/test_png_upload.py::test_broken_png_returns_415_before_any_storage_write[duplicate-ihdr]
2 failed, 1 passed in 0.29s
+20
View File
@@ -0,0 +1,20 @@
PASS test_identity_does_not_know_about_messaging
PASS test_attachments_and_other_zones_do_not_import_each_other
PASS test_domains_do_not_import_infrastructure
PASS test_core_layers_do_not_import_pydantic
PASS test_shared_knows_nothing_about_zones
PASS test_shared_core_is_free_of_transport
PASS test_shared_core_holds_only_platform
PASS test_shared_entrypoints_hold_only_transport
PASS test_every_zone_owns_its_errors_events_and_commands
PASS test_every_zone_owns_its_http_layer
PASS test_only_main_knows_several_zones
PASS test_application_has_no_separate_entrypoints_root
PASS test_shared_source_mentions_no_domain_vocabulary
PASS test_shared_declares_no_concrete_commands_or_events
PASS test_shared_has_no_test_doubles
PASS test_zone_errors_do_not_leak_transport_codes
PASS test_sql_of_each_zone_reads_only_its_tables
PASS test_messaging_does_not_import_identity_at_all
PASS test_sqlalchemy_stays_in_infrastructure_and_asyncpg_is_only_a_driver
19 static boundary checks passed; no pytest API database fixture invoked
+2
View File
@@ -0,0 +1,2 @@
python3 scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
+12
View File
@@ -0,0 +1,12 @@
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
E501 Line too long (102 > 100)
--> student-tests/unit/test_png_upload.py:30:101
|
30 | @pytest.mark.parametrize("data", [BROKEN_PNG, DUPLICATE_IHDR_PNG], ids=["bad-zlib", "duplicate-ihdr"])
| ^^
31 | async def test_broken_png_returns_415_before_any_storage_write(data: bytes) -> None:
32 | uow = Mock(spec=AttachmentsUnitOfWork)
|
Found 1 error.
make: *** [lint] Error 1
+6
View File
@@ -0,0 +1,6 @@
.venv/bin/ruff check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
All checks passed!
.venv/bin/ruff format --check src student-tests scripts/capture_evidence.py alembic scripts/scaling.py tools scripts/probe.py scripts/limits.py scripts/lab4_scenarios.py scripts/lab4_seed.py scripts/upload_memory.py scripts/reconcile_check.py scripts/reconcile_track.py
166 files already formatted
.venv/bin/ty check src student-tests alembic
All checks passed!
+20
View File
@@ -0,0 +1,20 @@
✓ change/fix-png-header-consistency
✓ spec/lab1-event-publication
✓ spec/lab1-messenger-chats
✓ spec/lab1-messenger-history
✓ spec/lab1-messenger-identity
✓ spec/lab1-service-operability
✓ spec/lab2-auth-sessions
✓ spec/lab2-dependency-failures
✓ spec/lab2-history-index
✓ spec/lab2-persistent-storage
✓ spec/lab2-session-cache
✓ spec/lab3-failover-operations
✓ spec/lab3-idempotent-messages
✓ spec/lab3-load-balancing
✓ spec/lab4-attachments
✓ spec/lab4-evidence-runs
✓ spec/lab4-object-storage
✓ spec/lab4-storage-reconciler
✓ spec/lab4-upload-resilience
Totals: 19 passed, 0 failed (19 items)
@@ -0,0 +1,10 @@
.venv/bin/pytest --collect-only -q -m stack student-tests/stack/test_attachment_faults.py
student-tests/stack/test_attachment_faults.py::test_user_errors_never_become_500
student-tests/stack/test_attachment_faults.py::test_commit_failure_is_compensated_at_once
student-tests/stack/test_attachment_faults.py::test_crash_between_put_and_commit_is_swept_after_grace
student-tests/stack/test_attachment_faults.py::test_aborted_upload_leaves_nothing
student-tests/stack/test_attachment_faults.py::test_stalled_upload_is_cut_and_leaves_nothing
student-tests/stack/test_attachment_faults.py::test_token_is_checked_before_the_declared_size
student-tests/stack/test_attachment_faults.py::test_slow_but_steady_transfers_outlive_the_request_timeout
7 tests collected in 0.10s
+5
View File
@@ -0,0 +1,5 @@
........................................................................ [ 31%]
........................................................................ [ 63%]
........................................................................ [ 95%]
........... [100%]
227 passed in 0.34s
+8
View File
@@ -0,0 +1,8 @@
.venv/bin/pytest -q --tb=short student-tests/unit
........................................................................ [ 17%]
........................................................................ [ 35%]
........................................................................ [ 53%]
........................................................................ [ 70%]
........................................................................ [ 88%]
............................................... [100%]
407 passed in 0.50s
+2
View File
@@ -0,0 +1,2 @@
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.