Files
mtusi2026lab2/openspec/changes/add-lab4-image-attachments/tasks.md
T
ArtyomandClaude Opus 5.5 00826a40d3 Serve attachment upload, metadata and download through the API
Add the adapters behind the attachments ports: PostgreSQL for the
pending and ready rows, with a foreign key violation on the chat member
turned into 404; Pillow that opens only PNG and JPEG, refuses a type
that differs from Content-Type, checks the pixel count from the header
before any decoding, verifies PNG chunks and decodes JPEG at 1/8 scale
in a worker thread under a semaphore; and S3 on aiobotocore with path
style, SigV4, short timeouts and checksums only when required. botocore
sends Expect: 100-continue for streamed bodies and RustFS behind the
Docker port proxy never answers it, so the PUT hung until the read
timeout; the handler that adds the header is unregistered.

The HTTP layer streams the raw body into the use case, returns the
contract Attachment and streams the original back with its content
type and length and no redirect. The request pipeline takes a body
limit per route, so uploads may carry 10 MiB while JSON stays at 1 MiB.
main.py wires the zone and answers its membership port from the
messaging chat directory.

Tests run the API with an in-memory object store: download by another
member, 404 for strangers, the exact 10 MiB limit and one byte over it
with Content-Length and chunked, 40 MP and above, spoofed and truncated
images, unsupported types, dangerous names, the variant, a failing
store and a lost object.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:44:32 +03:00

57 lines
7.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 1. Схема
- [x] 1.1 Миграция `0003_attachments.sql`: `attachments` (статус `pending`/`ready`, `object_key COLLATE "C"`, `UNIQUE (id, chat_id)`, FK на `chat_members`, частичный индекс `pending`), `message_attachments` (FK на `attachments (id, chat_id)` `ON DELETE RESTRICT`, индекс по `attachment_id`), ослабленный `messages_text_check`
- [x] 1.2 Проверка группы: тест миграций — версия `0003`, повтор без изменений, вложение не участника и ссылка на вложение другого чата отклоняются внешними ключами, пустой текст принимается схемой
## 2. Зона `attachments`: домен и приложение
- [x] 2.1 Домен: `Filename`, `ImageKind`, `ImageInfo`, агрегат `Attachment` (`stage` → `pending`, `store` → `ready` с событием `AttachmentStored`), ошибки зоны
- [x] 2.2 Порты: `ChatMembership`, `ObjectStorage` (`put`/`open`/`delete`, `ObjectContent`, `ObjectMissing`), `ImageInspector`, `AttachmentsUnitOfWork`, `AttachmentDirectory`
- [x] 2.3 Команда `UploadAttachment` и обработчик: членство → имя → `Content-Type` → поток со счётчиком и SHA-256 → проверка изображения → `pending` → `put` → `ready`; запросы `GetAttachment`, `OpenAttachment`
- [x] 2.4 Проверка группы: unit-тесты `Filename` (граничные и опасные имена), агрегата и порядка записи обработчика с фейковыми портами (сбой `put` даёт `503` и не делает вложение готовым)
## 3. Зона `attachments`: инфраструктура и HTTP
- [x] 3.1 Адаптер PostgreSQL: `add`, `save`, `get` готового; нарушение FK членства → `404`
- [x] 3.2 Адаптер `PillowImageInspector`: открытие только PNG/JPEG, подмена MIME, пиксели по заголовку, PNG `verify`, JPEG `draft` + `load`, `to_thread` под семафором
- [x] 3.3 Адаптер `S3ObjectStorage` на aiobotocore (path-style, SigV4, таймауты, checksum `when_required`), отображение ошибок в `ObjectMissing`/`Unavailable`; зависимости aiobotocore и Pillow в `uv.lock`
- [x] 3.4 Настройки зоны (`S3_*`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS`, таймауты, параллелизм проверки), провайдер dishka, схемы `AttachmentOut`, роутер upload/метаданных/скачивания, реестр ошибок, журнал
- [ ] 3.5 Проверка группы: тест адаптера S3 против одноразового RustFS (put/open/delete, пропавший объект, недоступный endpoint → `Unavailable` за ограниченное время)
## 4. Связь зон и платформа
- [x] 4.1 Платформа: лимит тела по шаблону маршрута в конвейере
- [x] 4.2 `main.py`: зона `attachments`, адаптер `MessagingMembership` для порта `ChatMembership`, лимит upload, поля журнала, реестр ошибок; `create_app` принимает дополнительные провайдеры для тестов
- [ ] 4.3 Проверка группы: тест графа импортов — `attachments` не импортирует `identity`/`messaging`, `messaging` не импортирует `attachments`, `shared` не знает зон
## 5. Зона `messaging`: `attachment_ids`
- [ ] 5.1 Домен: `Message.attachment_ids`, `Chat.post` с проверкой списка вложений, `MessageText` с пустой строкой, ошибки `InvalidAttachmentList` и `UnknownAttachment`
- [ ] 5.2 HTTP и команда: `CreateMessageRequest.attachment_ids` (по умолчанию `[]`, отпечаток), `MessageOut.attachment_ids`
- [ ] 5.3 PostgreSQL: запись `message_attachments` в операторе отправки, FK → `404`, `attachment_ids` в повторе и истории подзапросом
- [ ] 5.4 Проверка группы: тесты — пустой текст с вложением, порядок, другой чат и неизвестный id `404`, 11 и повторы `400`, посторонний `404` раньше `400`, повтор с вложением, отсутствующий ≡ `[]`, другой порядок `409`, история с `attachment_ids`
## 6. API-тесты вложений
- [x] 6.1 Генераторы тестовых PNG (произвольный размер в пикселях и байтах) и JPEG, фейковое `ObjectStorage` в `student-tests`
- [x] 6.2 Тесты: fixture `201` и побайтное скачивание вторым участником, посторонний `404` на метаданных и `/content`, ровно 10 MiB `201`, +1 байт `413` с `Content-Length` и chunked, 40 MP `201` и 40 MP+ `413`, подмена MIME, обрезанные PNG/JPEG, иной и пустой `Content-Type` `415`, опасные и пустые `filename` `400`, `variant=thumbnail` `400`, сбой хранилища `503` без готового вложения, пропавший объект `404`, заголовки на бинарном ответе
## 7. Стенд
- [ ] 7.1 `infra/s3/` (`init.sh`, `cli.sh`, `api-policy.json`, `lifecycle.json`) из заготовки
- [ ] 7.2 `compose.yaml`: `s3`, `s3-init`, `s3-cli`, volume `s3data`, секреты S3, якорь `x-s3-env` у `api`, зависимость от `s3-init`; `.env.example` (таймауты S3, параллелизм проверки)
- [ ] 7.3 `scripts/secrets.sh` (секреты S3), `scripts/restart.sh` (S3 в списке хранилищ), `scripts/evidence-stack.sh` (пакеты и образы лабы 4)
- [ ] 7.4 Проверка группы: `docker compose config --quiet`, у `api` только ключ API S3, `make up` из чистого состояния, все сервисы `healthy`, `s3-init` завершился кодом 0, опубликованы только порты `lb`
## 8. Сценарии отказов и обвязка
- [ ] 8.1 `scripts/lab4_scenarios.py` (`failover-upload`, `s3-outage`), `scripts/s3-check.sh`, `scripts/evidence-attachments.sh`; цели Makefile `scenario`, `s3-check`, `attachments-evidence`; ruff для новых `scripts/*.py`
- [ ] 8.2 CI-job под лабу 4: сценарии вложений после smoke
- [ ] 8.3 Проверка группы: `make test`, `make test-persistence ACTION_SCRIPT=scripts/restart.sh`, `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` по обеим репликам с `make restore`, `make scenario SCENARIO=failover-upload`, `make scenario SCENARIO=s3-outage`, `make s3-check`
## 9. Отчёт
- [ ] 9.1 `evidence/`: smoke, contract-checks, student-tests, stack, storage-layout, failover-upload, failover по каждой реплике, persistence со `StartedAt` (включая `s3`), s3-outage, s3-security, схема и миграции, окружение
- [ ] 9.2 `REPORT.md`: запуск из чистого clone, архитектура и решения, таблица ролей и сервисов, соответствие переменных `.env.example`, строки уровня «3», таблица отказов уровня «3»
- [ ] 9.3 Проверка группы: `make check`, `make validate`, `make lint`, `make student-test`, `make test` и сценарии зелёные