From a856128b452f6165b5fcb5b593442e63eac15e37 Mon Sep 17 00:00:00 2001 From: alenchha Date: Thu, 5 Nov 2026 13:53:08 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D1=80=D0=B5=D0=B2=D1=8C=D1=8E:=20=D0=B1=D0=B8=D1=82?= =?UTF-8?q?=D1=8B=D0=B9=20JPEG,=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82=D1=8C=20n?= =?UTF-8?q?ginx,=20502=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20413?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JPEG проверяется через djpeg -strict: обрезанный поток с дописанным EOI теперь даёт 415. Память nginx больше не зависит от тел файлов: загрузка идёт потоком до API, скачивание без временных файлов, воркеров 2. API не закрывает соединение при недочитанном теле, что давало HTML 502; nginx сам отклоняет тела больше лимитов API. Лимит памяти API поднят до 512 MiB под проверку CMYK-JPEG на 40 Мпикс. Добавлен стресс-тест через LB. --- Dockerfile | 6 +- REPORT.md | 26 ++-- app/imagecheck.py | 51 +++++-- app/main.py | 4 +- compose.yaml | 2 +- evidence/attachments_tests.txt | 7 + evidence/failover.txt | 2 +- evidence/input_hardening.txt | 1 + evidence/jpeg_check.txt | 24 ++- evidence/lb_stress.txt | 25 +++ evidence/lb_stress_30.txt | 25 +++ evidence/memory_experiment.txt | 22 +-- evidence/private_bucket.txt | 7 +- evidence/reconciler_experiment.txt | 12 +- infra/nginx.conf | 7 +- scripts/jpeg_check_experiment.py | 112 ++++++++++---- student-tests/memory_experiment.py | 2 +- student-tests/test_input_hardening.py | 11 ++ student-tests/test_lb_stress.py | 210 ++++++++++++++++++++++++++ 19 files changed, 470 insertions(+), 86 deletions(-) create mode 100644 evidence/lb_stress.txt create mode 100644 evidence/lb_stress_30.txt create mode 100644 student-tests/test_lb_stress.py diff --git a/Dockerfile b/Dockerfile index 9072779..a355319 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,6 +7,10 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ PIP_DEFAULT_TIMEOUT=120 \ PIP_RETRIES=10 +RUN apt-get update \ + && apt-get install -y --no-install-recommends libjpeg-turbo-progs=1:2.1.5-2 \ + && rm -rf /var/lib/apt/lists/* + RUN groupadd --system --gid 10001 app \ && useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app @@ -17,7 +21,7 @@ RUN pip install --no-deps -r requirements.txt COPY app/ app/ COPY migrations/ migrations/ -COPY scripts/migrate.py scripts/reconcile.py scripts/reconcile_experiment.py scripts/ +COPY scripts/migrate.py scripts/reconcile.py scripts/reconcile_experiment.py scripts/jpeg_check_experiment.py scripts/ USER 10001:10001 diff --git a/REPORT.md b/REPORT.md index 0baf806..f154bab 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор, группа: Алёна Курлова, БВТ2301 - Целевая оценка; выбранный трек 5: **5, трек 2 «Согласованность двух хранилищ»** -- Commit/PR: PR [#49](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/49), основной коммит `ba6e32a`, ветка `solution/bvt2301-kurlova` +- Commit/PR: PR [#49](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/49), ветка `solution/bvt2301-kurlova` - Источники, библиотеки, помощь ИИ: FastAPI, psycopg, boto3, Pillow, MinIO; код лабы 3 перенесён и расширен. Реализацию, тесты и черновик отчёта выполнял Claude Code (ИИ) под руководством автора; результаты прогонов ниже получены на локальном стенде. ## Запуск из чистого clone @@ -39,7 +39,7 @@ make test # ждёт готовности **Источник истины.** Метаданные — PostgreSQL (`attachments`, `message_attachments`), байты — приватный bucket. Object key назначает сервер (`attachments/`), `filename` хранится только как отображаемое имя. **Порядок записи и границы согласованности** (ответ на «что если PUT прошёл, а COMMIT нет»): -1. тело читается потоком в `SpooledTemporaryFile` (1 MiB в RAM, остальное во временный файл), считается SHA-256, лимит 10 MiB применяется на лету; MIME проверяется по magic bytes и Pillow, лимит пикселей проверяется по заголовку до декодирования; целостность проверяет [app/imagecheck.py](app/imagecheck.py): для PNG собственный потоковый сканер (CRC всех chunk'ов, поля IHDR, zlib-поток разжимается порциями по 1 MiB, filter-байт каждой строки ∈ 0..4, размер данных точно равен вычисленному по IHDR, Adam7 учитывается), для JPEG полное декодирование через libjpeg в масштабе 1/8 (память ~1/64 изображения) плюс проверка маркера EOI; +1. тело читается потоком в `SpooledTemporaryFile` (1 MiB в RAM, остальное во временный файл), считается SHA-256, лимит 10 MiB применяется на лету; MIME проверяется по magic bytes и Pillow, лимит пикселей проверяется по заголовку до декодирования; целостность проверяет [app/imagecheck.py](app/imagecheck.py): для PNG собственный потоковый сканер (CRC всех chunk'ов, поля IHDR, zlib-поток разжимается порциями по 1 MiB, filter-байт каждой строки ∈ 0..4, размер данных точно равен вычисленному по IHDR, Adam7 учитывается), для JPEG дочерний процесс `djpeg -strict` (libjpeg-turbo 2.1.5) декодирует весь поток в масштабе 1/8 и считает любое предупреждение libjpeg ошибкой, поэтому обрезанный поток отвергается и с дописанным EOI; одновременно идёт одна такая проверка на реплику, память процесса ограничена `-maxmemory`, число сканов `-maxscans 100`; 2. в БД вставляется строка `status='uploading'` (коммит); 3. PUT в S3; 4. `UPDATE … SET status='ready' WHERE status='uploading'` — только после этого клиент получает **201**. @@ -52,7 +52,7 @@ make test # ждёт готовности - `ready`-строка, подтверждённая (`updated_at`) раньше grace, без объекта (перепроверка HEAD) → `status='failed'`, `error_code='object_missing'`; строка **не удаляется**, даже если на неё ссылается сообщение; - по умолчанию dry-run (`--apply` меняет данные), повторный запуск идемпотентен. -**Что изменено в lab3-коде.** Сообщение принимает `attachment_ids` (0–10) и допускает пустой `text` при наличии вложений (миграция 0004 ослабляет CHECK). Хеш идемпотентности включает `attachment_ids`; повтор без ключа `attachment_ids` равен `[]`. **Критичные зависимости `/health/ready`: PostgreSQL и S3.** Недоступность любой из них даёт 503 в общем формате ошибки с `X-Instance-Id`; состояние S3 обновляется фоновой пробой раз в секунду (отдельный клиент с таймаутами 1 с / 1.5 с, чтобы зависший S3 не вешал проверку). При этом недоступный S3 **не** блокирует остальной API: текстовые сообщения и метаданные продолжают работать (запросы блокируются только при недоступной БД), а вложения отвечают 503. Чтобы 503 не выбивал реплики из upstream и клиенты не видели 502, nginx не использует `http_503` как признак сбоя для `/health/`, `/attachments/` и upload; если обе реплики не готовы, health-скрипт оставляет обе в ротации. nginx также отдаёт JSON-ошибку 413 (с `X-Request-Id`) для тел больше `client_max_body_size` 11m. S3-клиент: без повторов, connect 3 с, read 6 с; компенсация при сбое PUT выполняется в фоне. +**Что изменено в lab3-коде.** Сообщение принимает `attachment_ids` (0–10) и допускает пустой `text` при наличии вложений (миграция 0004 ослабляет CHECK). Хеш идемпотентности включает `attachment_ids`; повтор без ключа `attachment_ids` равен `[]`. **Критичные зависимости `/health/ready`: PostgreSQL и S3.** Недоступность любой из них даёт 503 в общем формате ошибки с `X-Instance-Id`; состояние S3 обновляется фоновой пробой раз в секунду (отдельный клиент с таймаутами 1 с / 1.5 с, чтобы зависший S3 не вешал проверку). При этом недоступный S3 **не** блокирует остальной API: текстовые сообщения и метаданные продолжают работать (запросы блокируются только при недоступной БД), а вложения отвечают 503. Чтобы 503 не выбивал реплики из upstream и клиенты не видели 502, nginx не использует `http_503` как признак сбоя для `/health/`, `/attachments/` и upload; если обе реплики не готовы, health-скрипт оставляет обе в ротации. **Лимиты тела и память LB.** nginx сам отклоняет слишком большие тела JSON-ошибкой 413 (с `X-Request-Id`): 10 MiB для загрузки вложений и 64 KiB для остальных запросов, то есть те же границы, что в API. Загрузка идёт потоком до API (`proxy_request_buffering off`), скачивание — без временных файлов (`proxy_max_temp_file_size 0`), поэтому тела файлов не попадают в память и page cache контейнера nginx; воркеров 2, а не `auto`, чтобы потребление не зависело от числа ядер хоста. API больше не отправляет `Connection: close` на отказах с недочитанным телом: это закрывало соединение раньше, чем nginx успевал прочитать ответ, и давало HTML 502; uvicorn дочитывает и отбрасывает остаток тела. Лимит памяти контейнера API поднят до 512 MiB, потому что проверка законного прогрессивного CMYK-JPEG на 40 Мпикс требует 307 MiB. S3-клиент: без повторов, connect 3 с, read 6 с; компенсация при сбое PUT выполняется в фоне. **Дополнительная валидация входных данных.** filename: 1..255 code points, не только пробелы, не `.`/`..`, без `/`, `\` и любых символов категорий Cc/Cs/Zl/Zp (в том числе DEL и C1). `Idempotency-Key` не обрезается (HTTP-парсер уже убирает крайние пробелы); порядок `attachment_ids` сохраняется в ответе, повторе и истории, переставленный список с тем же ключом — 409. @@ -65,14 +65,15 @@ make test # ждёт готовности | Публичный smoke | `make test` | PASS (загрузка, привязка, скачивание вторым участником, 404 постороннему) | [evidence/smoke.txt](evidence/smoke.txt) | | Байты в S3, метаданные в БД, 201 после сохранения | код `upload_attachment`; `student-tests/test_attachments.py` | sha256/размер совпадают, `Content-Length` скачивания равен оригиналу | [evidence/attachments_tests.txt](evidence/attachments_tests.txt) | | Upload → остановка реплики → download через другую; restart с volumes | `student-tests/test_attachment_resilience.py` | загрузил api-1, скачал api-2, sha256 совпал; после рестарта postgres/valkey/minio/api/nginx метаданные и оригинал целы | [evidence/attachment_resilience.txt](evidence/attachment_resilience.txt) | -| Общие persistence / failover | `make test-persistence`, `make test-failover` (хуки `scripts/restart.sh`, `scripts/stop-one.sh`) | PASS; failover: 131 успешная запись, 0 ошибок, восстановление 0.45 с | [evidence/persistence.txt](evidence/persistence.txt), [evidence/failover.txt](evidence/failover.txt) | +| Общие persistence / failover | `make test-persistence`, `make test-failover` (хуки `scripts/restart.sh`, `scripts/stop-one.sh`) | PASS; failover: 131 успешная запись, 0 ошибок, восстановление 0.44 с | [evidence/persistence.txt](evidence/persistence.txt), [evidence/failover.txt](evidence/failover.txt) | | Лимиты 10 MiB / 40 Mpx, MIME по содержимому, опасные filename | `test_attachments.py` | 10 MiB+ → 413; PNG 8000×6000 → 413 до декодирования; подмена MIME и мусор → 415; `../`, `/`, `\`, NUL, `\n`, пустое, 256 символов → 400 | [evidence/attachments_tests.txt](evidence/attachments_tests.txt) | -| Устойчивость к некорректным входным данным | `student-tests/test_input_hardening.py`, `scripts/jpeg_check_experiment.py` (запуск: `docker compose cp scripts/jpeg_check_experiment.py api-1:/tmp/ && docker compose exec -T api-1 python /tmp/jpeg_check_experiment.py`) | усечённый PNG, filter-байт 5/0xFF, битый IDAT, 27-байтный JPEG → 415 (в том числе для изображений 6 и 36 Mpx); filename из пробелов, DEL, C1, `.` → 400; порядок вложений; `[]` ≡ отсутствует; 12 MiB → JSON 413 | [evidence/input_hardening.txt](evidence/input_hardening.txt), [evidence/jpeg_check.txt](evidence/jpeg_check.txt) | +| Устойчивость к некорректным входным данным | `student-tests/test_input_hardening.py`, `scripts/jpeg_check_experiment.py` (запуск: `docker run --rm --entrypoint python mtusi-messenger:lab4 scripts/jpeg_check_experiment.py`) | усечённый PNG, filter-байт 5/0xFF, битый IDAT, 27-байтный JPEG, настоящий JPEG, обрезанный наполовину с дописанным `FF D9` и без него → 415 (PNG-дефекты также на 6 и 36 Mpx); валидные baseline, progressive, grayscale, CMYK, файл с данными после EOI и 40 Mpx принимаются; filename из пробелов, DEL, C1, `.` → 400; порядок вложений; `[]` ≡ отсутствует; 12 MiB → JSON 413 | [evidence/input_hardening.txt](evidence/input_hardening.txt), [evidence/jpeg_check.txt](evidence/jpeg_check.txt) | | Чужое / неизвестное / чужого чата attachment_id, ошибки не 500 | `test_attachments.py` | 404 / 404 / 404; дубликаты, не-UUID, >10 → 400 | там же | | Недоступность и зависание S3 | `student-tests/test_s3_outage.py` | остановка: upload/download/ready → 503 JSON с `X-Instance-Id`, метаданные и текст работают, без 502; `docker pause`: upload отвечает 503 за 7 с; восстановление за секунды | [evidence/s3_outage.txt](evidence/s3_outage.txt) | | Прерывание загрузки | обрыв сокета на половине тела в `test_attachments.py` | сервер здоров, следующий upload проходит | там же | | Компенсация / сверка, безопасный grace | трек 2, ниже | 18/18 проверок | [evidence/reconciler_experiment.txt](evidence/reconciler_experiment.txt) | -| Пик памяти при ≥10 одновременных загрузках | `student-tests/memory_experiment.py` | см. ниже | [evidence/memory_experiment.txt](evidence/memory_experiment.txt) | +| Пик памяти при ≥10 одновременных загрузках | `student-tests/memory_experiment.py`, `student-tests/test_lb_stress.py` | см. ниже | [evidence/memory_experiment.txt](evidence/memory_experiment.txt), [evidence/lb_stress.txt](evidence/lb_stress.txt) | +| Нагрузка на LB: нет OOM и падений, отказы в JSON | `python3 student-tests/test_lb_stress.py --concurrency 10 --rounds 3 --oversize 100` и то же с 30 параллельными | загрузки 201, скачивания 200, 800 запросов-отказов дают правильный JSON без единого 502, событий `oom`/`die` контейнеров нет, пик nginx 28–34 MiB при лимите 64 | [evidence/lb_stress.txt](evidence/lb_stress.txt), [evidence/lb_stress_30.txt](evidence/lb_stress_30.txt) | | Private bucket вне API, консоль не открыта | `student-tests/check_private_bucket.sh` | анонимные GET/LIST из сети compose → 403, порты 9000/9001 на хосте не опубликованы, `mc anonymous get` → private | [evidence/private_bucket.txt](evidence/private_bucket.txt) | | Отдельные S3 credentials с ограниченными правами | `infra/minio/app-policy.json`, `init.sh` | API работает под `messenger_app`; root-secret API не получает | `compose.yaml` | @@ -84,15 +85,17 @@ make test # ждёт готовности Гипотеза: основная память уходит на параллельное декодирование Pillow и S3 PUT, а не на хранение тел запросов; ограничение числа одновременных тяжёлых стадий снизит пик. -Методика: [student-tests/memory_experiment.py](student-tests/memory_experiment.py), PNG 8.27 MiB (1700×1700, несжимаемый шум), 10 параллельных загрузок через LB, 3 раунда, замер `docker stats` каждого API (лимит контейнера 256 MiB, 0.5 CPU). Mac arm64, Docker Desktop. +Методика: [student-tests/memory_experiment.py](student-tests/memory_experiment.py), PNG 8.27 MiB (1700×1700, несжимаемый шум), 10 параллельных загрузок через LB, 3 раунда, замер `docker stats` каждого API (0.5 CPU; лимит контейнера был 256 MiB, в итоговой версии 512 MiB). Mac arm64, Docker Desktop. | Вариант | Простой, MiB | Пик api-1 / api-2, MiB | Динамика по раундам | 201 / всего | | --- | --- | --- | --- | --- | | До: без ограничения тяжёлых стадий | 88 | 182 / 155 | рост 144 → 166 → 182 | 30 / 30 | | После: `UPLOAD_CONCURRENCY=2` на реплику | 87 | 110 / 116 | 110 → 109 → 110, роста нет | 30 / 30 | -| После + потоковый PNG-сканер и JPEG-проверка (итоговая версия) | 98–100 | 115 / 114 | 115 → 115 → 115, роста нет | 30 / 30 | +| После + потоковый PNG-сканер (итоговая версия) | см. файл | 116 / 107 | роста нет | 30 / 30 | -Сырые данные: [evidence/memory_experiment_before_semaphore.txt](evidence/memory_experiment_before_semaphore.txt), [evidence/memory_experiment.txt](evidence/memory_experiment.txt). Ограничения: `docker stats` даёт моментальные срезы (раз в ~1–2 с), настоящий пик мог быть выше; одна конфигурация железа; один размер файла; медиана длительности загрузки выросла с 0.82 до 1.15 с (цена ограничения), в итоговой версии 0.76 с. Причину роста «до» (фрагментация аллокатора или реальная утечка) я не выяснял. +**Цифры таблицы занижены.** `docker stats` не учитывает page cache и даёт срезы раз в 1–2 с. Точный показатель лимита — `memory.peak` из cgroup: в этом же сценарии 154–163 MiB, `oom_kill=0`. Худший сценарий — стресс-тест с 10–30 параллельными прогрессивными CMYK-JPEG на 40 Мпикс: `memory.peak` API 444–491 MiB из 512 (вместе с page cache, который ядро может вытеснить), `oom_kill=0`, рестартов нет. Постоянная память процесса API после такой нагрузки около 133 MiB, один процесс проверки до 307 MiB ([evidence/jpeg_check.txt](evidence/jpeg_check.txt)). Запас в худшем случае небольшой. + +Сырые данные: [evidence/memory_experiment_before_semaphore.txt](evidence/memory_experiment_before_semaphore.txt), [evidence/memory_experiment.txt](evidence/memory_experiment.txt). Ограничения: одна конфигурация железа; один размер файла; медиана длительности загрузки выросла с 0.82 до 1.15 с (цена ограничения), в итоговой версии 0.63 с. Причину роста «до» (фрагментация аллокатора или реальная утечка) я не выяснял. ### 2. Трек 2 — reconciler с внедрением ошибок @@ -125,12 +128,15 @@ make test # ждёт готовности | Зависание MinIO (`docker pause`) | быстрый 503 без вечного ожидания | upload → 503 за 7 с, download → 503 | восстановление после `unpause` | | Остановка PostgreSQL | 503 JSON с `X-Instance-Id` на ready и бизнес-эндпоинтах | так и есть | возврат после старта | | Рестарт postgres, valkey, minio, API, nginx с volumes | метаданные и байты на месте | сохранены | без потерь | +| 10 и 30 одновременных загрузок 8.3 MiB через LB | ограниченная обработка без падения стенда | все 201, событий `oom`/`die` нет, пик nginx 28–34 MiB | потерь нет | | Обрыв клиента на середине upload | нет 500 и мусора | сервер здоров; строка в БД ещё не создана | — | ## Ограничения и следующие шаги - **Образ MinIO.** Официальные образы `minio/minio` на Docker Hub и `quay.io/minio/minio` в моей среде недоступны (pull denied / 401), поэтому использован сторонний `madlabcg/minio`, закреплённый по digest. Его происхождение и содержимое я не проверял; для защиты нужно заменить образ на проверенный (собрать из исходников MinIO или взять образ, указанный преподавателем). -- **Валидация изображений.** PNG проверяется собственным потоковым сканером (структура, CRC, filter-байты, точный размер данных), JPEG — полным декодированием libjpeg в масштабе 1/8 и проверкой EOI. Не обнаруживается JPEG, у которого поток обрезан посередине, а после обрезки дописан маркер EOI: libjpeg трактует это как нормальный конец данных (и Pillow тоже принимает такой файл). Также сканер не проверяет содержимое palette/ancillary chunk'ов, кроме CRC и PLTE-правил. +- **Валидация изображений.** `djpeg -strict` считает ошибкой любое предупреждение libjpeg, поэтому будет отвергнут и JPEG с мелким дефектом, который обычные программы показывают (например, лишние байты перед маркером). Это сознательный выбор в пользу строгости. Подмена байтов внутри данных, не нарушающая структуру потока, может не обнаруживаться: такой файл корректно декодируется в другую картинку. PNG-сканер не проверяет содержимое ancillary chunk'ов, кроме CRC. +- **OOM балансировщика.** Само падение nginx по OOM на моей машине (10 ядер, Docker Desktop) не воспроизвелось, воспроизвелся пик у лимита: 67–80 MiB при 64. Устранена причина (тела файлов через nginx больше не спулятся на диск, число воркеров фиксировано); после правок пик 28–34 MiB. На конфигурации, где наблюдалось падение, правка отдельно не проверялась. +- **Потоковая загрузка через LB.** С `proxy_request_buffering off` медленный клиент занимает слот API на всё время передачи, но не дольше `REQUEST_TIMEOUT` (30 с) и в пределах `MAX_INFLIGHT_REQUESTS`. Ошибка 413, выданная самим nginx, содержит `X-Instance-Id: lb`, потому что запрос до реплики не доходил. - Проверка размера по `Content-Length` невозможна для chunked-запросов: тогда лимит применяется по факту чтения потока. - Проверка PNG ограничена по времени (`SCAN_SECONDS`=10 с); на очень медленной машине валидный файл с огромной степенью сжатия может получить 415. - Вложения, загруженные, но так и не прикреплённые к сообщению, не считаются мусором и не удаляются; политики TTL для них нет. diff --git a/app/imagecheck.py b/app/imagecheck.py index 0d86959..fe698c5 100644 --- a/app/imagecheck.py +++ b/app/imagecheck.py @@ -1,17 +1,24 @@ """Integrity checks for uploaded PNG/JPEG with bounded memory. PNG: own streaming scanner (chunk CRCs, IHDR rules, zlib stream decoded 1 MiB at a time, every row filter byte in -0..4, decoded size equal to the size implied by IHDR, IEND present). JPEG: libjpeg decodes the whole entropy -stream through Pillow in 1/8 scale, so memory stays at ~1/64 of the image. Both finish before anything is stored. +0..4, decoded size equal to the size implied by IHDR, IEND present). JPEG: `djpeg -strict` decodes the whole entropy +stream in a child process at 1/8 scale; Pillow hides libjpeg warnings, and a scan cut short with an appended EOI is +only a warning. Both finish before anything is stored. """ +import logging +import os import struct +import subprocess +import threading import time import zlib from PIL import Image from app import config -from app.errors import ApiError +from app.errors import ApiError, unavailable + +log = logging.getLogger("messenger.imagecheck") PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" VALID_DEPTHS = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8), 4: (8, 16), 6: (8, 16)} @@ -22,6 +29,9 @@ FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"} FULL_DECODE_MAX_PIXELS = 4000000 SCAN_SECONDS = 10.0 OUT_STEP = 1 << 20 +# Progressive 40 Mpx CMYK needs ~320 MiB of coefficients; the cap keeps a hostile file from reaching the container limit. +DJPEG = ("djpeg", "-strict", "-scale", "1/8", "-maxscans", "100", "-maxmemory", "358400", "-outfile", "/dev/null") +jpeg_slot = threading.Lock() class Invalid(Exception): @@ -159,6 +169,25 @@ def scan_png(fileobj) -> None: raise Invalid("pixel data does not match IHDR") +def check_jpeg(fileobj) -> None: + fileobj.flush() + descriptor = fileobj.fileno() + os.lseek(descriptor, 0, os.SEEK_SET) + try: + with jpeg_slot: + done = subprocess.run(DJPEG, stdin=descriptor, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + timeout=SCAN_SECONDS, check=False) + except subprocess.TimeoutExpired: + log.error("jpeg_check_timeout") + raise unavailable("Проверка изображения не успела завершиться") from None + # A signal means the checker died (e.g. OOM killer), which says nothing about the file. + if done.returncode < 0: + log.error("jpeg_check_killed signal=%d", -done.returncode) + raise unavailable("Проверка изображения прервана") + if done.returncode != 0: + raise invalid() + + def inspect_image(fileobj, size: int, content_type: str) -> None: """Raises ApiError 413 (too many pixels) or 415 (not a decodable image of the declared type).""" try: @@ -169,21 +198,13 @@ def inspect_image(fileobj, size: int, content_type: str) -> None: raise invalid() if width * height > config.MAX_IMAGE_PIXELS: raise ApiError(413, "payload_too_large", "Изображение превышает 40 млн пикселей") - small = width * height <= FULL_DECODE_MAX_PIXELS if content_type == "image/png": scan_png(fileobj) - else: - fileobj.seek(max(0, size - 1024)) - if b"\xff\xd9" not in fileobj.read(): - raise invalid() - if not small: + if width * height <= FULL_DECODE_MAX_PIXELS: fileobj.seek(0) - scaled = Image.open(fileobj) - scaled.draft(scaled.mode, (1, 1)) - scaled.load() - if small: - fileobj.seek(0) - Image.open(fileobj).load() + Image.open(fileobj).load() + else: + check_jpeg(fileobj) except ApiError: raise except Exception: diff --git a/app/main.py b/app/main.py index 0cc5b09..12a8d3d 100644 --- a/app/main.py +++ b/app/main.py @@ -207,7 +207,7 @@ def non_blank(value: object, max_len: int) -> bool: async def read_json(request: Request, required: Tuple[str, ...], optional: Tuple[str, ...] = ()) -> dict: if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json": raise ApiError(415, "unsupported_media_type", "Ожидается application/json") - too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое", {"Connection": "close"}) + too_large = ApiError(413, "payload_too_large", "Тело запроса слишком большое") declared = request.headers.get("content-length") if declared and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES: raise too_large @@ -527,7 +527,7 @@ async def upload_attachment(chat_id: str, request: Request): raise ApiError(415, "unsupported_media_type", "Допускается только image/png или image/jpeg") declared_length = request.headers.get("content-length") - too_large = ApiError(413, "payload_too_large", "Файл превышает 10 MiB", {"Connection": "close"}) + too_large = ApiError(413, "payload_too_large", "Файл превышает 10 MiB") if declared_length and declared_length.isdigit() and int(declared_length) > config.MAX_UPLOAD_BYTES: raise too_large ensure_capacity() diff --git a/compose.yaml b/compose.yaml index 916790e..4fc0847 100644 --- a/compose.yaml +++ b/compose.yaml @@ -24,7 +24,7 @@ x-api: &api-defaults resources: limits: cpus: "0.50" - memory: 256M + memory: 512M healthcheck: test: ["CMD-SHELL", "python -c \"import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).status == 200 else 1)\""] interval: 5s diff --git a/evidence/attachments_tests.txt b/evidence/attachments_tests.txt index c1d3ac6..2565514 100644 --- a/evidence/attachments_tests.txt +++ b/evidence/attachments_tests.txt @@ -1,2 +1,9 @@ +ok auth and membership on upload +ok file over 10 MiB -> 413 +ok 48 Mpx image -> 413 before decoding +ok corrupted image -> 415 +ok MIME spoofing and unsupported types -> 415 +ok dangerous filenames -> 400 +ok unknown / foreign / other-chat attachment ids rejected, no 500 ok client abort mid-upload sent; server must stay healthy PASS: attachment negative scenarios diff --git a/evidence/failover.txt b/evidence/failover.txt index bb9e5a7..af74f33 100644 --- a/evidence/failover.txt +++ b/evidence/failover.txt @@ -1,2 +1,2 @@ -{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 0.447} +{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 0.441} PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/input_hardening.txt b/evidence/input_hardening.txt index 81f6419..8e04d88 100644 --- a/evidence/input_hardening.txt +++ b/evidence/input_hardening.txt @@ -1,4 +1,5 @@ ok truncated PNG, bad filter byte, broken IDAT, 27-byte JPEG stub -> 415 +ok real JPEG accepted; first half + EOI and first half alone -> 415 ok same defects in images above the full-decode threshold (6 Mpx) -> 415 ok valid 6 Mpx PNG accepted ok valid 36 Mpx PNG (116 KiB on the wire, 108 MiB decoded) accepted in 0.1s diff --git a/evidence/jpeg_check.txt b/evidence/jpeg_check.txt index 2f31831..12aa650 100644 --- a/evidence/jpeg_check.txt +++ b/evidence/jpeg_check.txt @@ -1,5 +1,19 @@ -valid 3000x2000 baseline accepted 0.08s ok -valid 3000x2000 progressive accepted 0.14s ok -27-byte stub rejected 415 0.00s ok -scan cut in half, no EOI rejected 415 0.00s ok -headers only + EOI rejected 415 0.01s ok +valid baseline 675893 bytes accepted 0.01s ok +valid progressive 616591 bytes accepted 0.02s ok +valid grayscale 359415 bytes accepted 0.00s ok +valid CMYK 1262509 bytes accepted 0.01s ok +valid, junk after EOI 675901 bytes accepted 0.01s ok +valid 40 Mpx baseline 626630 bytes accepted 0.01s ok +valid 40 Mpx progressive 352914 bytes accepted 0.07s ok +valid 40 Mpx progressive 444 704086 bytes accepted 0.13s ok +valid 40 Mpx progressive CMYK 626581 bytes accepted 0.17s ok +27-byte stub 27 bytes rejected 415 0.00s ok +first half + EOI 337948 bytes rejected 415 0.00s ok +first half, no EOI 337946 bytes rejected 415 0.00s ok +progressive half + EOI 308297 bytes rejected 415 0.00s ok +headers only + EOI 611 bytes rejected 415 0.01s ok + checker peak RSS, 40 Mpx baseline 1.7 MiB + checker peak RSS, 40 Mpx progressive 116.3 MiB + checker peak RSS, 40 Mpx progressive 444 230.6 MiB + checker peak RSS, 40 Mpx progressive CMYK 306.9 MiB +RESULT: 14/14 diff --git a/evidence/lb_stress.txt b/evidence/lb_stress.txt new file mode 100644 index 0000000..c3a1b04 --- /dev/null +++ b/evidence/lb_stress.txt @@ -0,0 +1,25 @@ +== 10 parallel uploads of 8674403 bytes, 3 rounds == +upload statuses: {201: 30} +== 10 parallel downloads == +download statuses: {200: 20} +== 10 parallel valid 40 Mpx progressive CMYK JPEGs (worst case for the checker), 3 rounds == +upload statuses: {201: 30} +== 10 MiB + 1 byte, Content-Length: 100 requests, 10 at a time == + {'413 application/json': 100} +== 10 MiB + 1 byte, chunked: 100 requests, 10 at a time == + {'413 application/json': 100} +== 10 MiB + 1 byte, chunked in 64 KiB pieces: 100 requests, 10 at a time == + {'413 application/json': 100} +== 8 MiB to a foreign chat: 100 requests, 10 at a time == + {'404 application/json': 100} +== 8 MiB without session: 100 requests, 10 at a time == + {'401 application/json': 100} +== 8 MiB with wrong magic: 100 requests, 10 at a time == + {'415 application/json': 100} +== 8 MiB with wrong Content-Type: 100 requests, 10 at a time == + {'415 application/json': 100} +== 70 KiB JSON message: 100 requests, 10 at a time == + {'413 application/json': 100} +container events during the run: none +cgroup memory.peak, MiB: {'mtusi-lab4-api-1-1': 475.1, 'mtusi-lab4-api-2-1': 490.5, 'mtusi-lab4-nginx-1': 34.3} +PASS: LB stress diff --git a/evidence/lb_stress_30.txt b/evidence/lb_stress_30.txt new file mode 100644 index 0000000..fe3a9c1 --- /dev/null +++ b/evidence/lb_stress_30.txt @@ -0,0 +1,25 @@ +== 30 parallel uploads of 8674403 bytes, 2 rounds == +upload statuses: {201: 60} +== 30 parallel downloads == +download statuses: {200: 60} +== 30 parallel valid 40 Mpx progressive CMYK JPEGs (worst case for the checker), 2 rounds == +upload statuses: {201: 60} +== 10 MiB + 1 byte, Content-Length: 30 requests, 30 at a time == + {'413 application/json': 30} +== 10 MiB + 1 byte, chunked: 30 requests, 30 at a time == + {'413 application/json': 30} +== 10 MiB + 1 byte, chunked in 64 KiB pieces: 30 requests, 30 at a time == + {'413 application/json': 30} +== 8 MiB to a foreign chat: 30 requests, 30 at a time == + {'404 application/json': 30} +== 8 MiB without session: 30 requests, 30 at a time == + {'401 application/json': 30} +== 8 MiB with wrong magic: 30 requests, 30 at a time == + {'415 application/json': 30} +== 8 MiB with wrong Content-Type: 30 requests, 30 at a time == + {'415 application/json': 30} +== 70 KiB JSON message: 30 requests, 30 at a time == + {'413 application/json': 30} +container events during the run: none +cgroup memory.peak, MiB: {'mtusi-lab4-api-1-1': 465.3, 'mtusi-lab4-api-2-1': 463.0, 'mtusi-lab4-nginx-1': 34.3} +PASS: LB stress diff --git a/evidence/memory_experiment.txt b/evidence/memory_experiment.txt index 639df83..eabf91d 100644 --- a/evidence/memory_experiment.txt +++ b/evidence/memory_experiment.txt @@ -1,23 +1,25 @@ payload bytes: 8674403 -round 1 peak MiB per api: {'mtusi-lab4-api-1-1': 114.5, 'mtusi-lab4-api-2-1': 113.7} statuses=[201] -round 2 peak MiB per api: {'mtusi-lab4-api-1-1': 115.1, 'mtusi-lab4-api-2-1': 113.5} statuses=[201] -round 3 peak MiB per api: {'mtusi-lab4-api-1-1': 115.2, 'mtusi-lab4-api-2-1': 114.0} statuses=[201] +round 1 peak MiB per api: {'mtusi-lab4-api-2-1': 95.5, 'mtusi-lab4-api-1-1': 115.6} statuses=[201] +round 2 peak MiB per api: {'mtusi-lab4-api-2-1': 104.8, 'mtusi-lab4-api-1-1': 115.6} statuses=[201] +round 3 peak MiB per api: {'mtusi-lab4-api-2-1': 106.6, 'mtusi-lab4-api-1-1': 115.3} statuses=[201] { "payload_mib": 8.27, "concurrency": 10, "rounds": 3, "idle_mib": { - "mtusi-lab4-api-1-1": 98.2, - "mtusi-lab4-api-2-1": 100.4 + "mtusi-lab4-api-2-1": 87.2, + "mtusi-lab4-api-1-1": 87.8 }, "peak_mib": { - "mtusi-lab4-api-1-1": 115.2, - "mtusi-lab4-api-2-1": 114.0 + "mtusi-lab4-api-2-1": 106.6, + "mtusi-lab4-api-1-1": 115.6 }, - "container_limit_mib": 256, + "container_limit_mib": 512, "statuses": { "201": 30 }, - "upload_seconds_median": 0.76, - "upload_seconds_max": 0.95 + "upload_seconds_median": 0.63, + "upload_seconds_max": 0.82 } +peak=163 MiB oom_kill 0 +peak=154 MiB oom_kill 0 diff --git a/evidence/private_bucket.txt b/evidence/private_bucket.txt index d3c3b8d..760bb1a 100644 --- a/evidence/private_bucket.txt +++ b/evidence/private_bucket.txt @@ -6,10 +6,7 @@ GET /messenger-attachments/ -> 403 GET /messenger-attachments/attachments/does-not-matter -> 403 GET /messenger-attachments?list-type=2 -> 403 == bucket policy == - Container mtusi-lab4-minio-init-run-ace02363dd5e Creating - Container mtusi-lab4-minio-init-run-ace02363dd5e Created -Access permission for `local/messenger-attachments` is `private` -PASS: bucket is private - Container mtusi-lab4-minio-init-run-bb29f48b3cc4 Created + Container mtusi-lab4-minio-init-run-85f57841572d Creating + Container mtusi-lab4-minio-init-run-85f57841572d Created Access permission for `local/messenger-attachments` is `private` PASS: bucket is private diff --git a/evidence/reconciler_experiment.txt b/evidence/reconciler_experiment.txt index b993179..a9438fe 100644 --- a/evidence/reconciler_experiment.txt +++ b/evidence/reconciler_experiment.txt @@ -1,11 +1,11 @@ -baseline (data left by earlier tests): {"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 113, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 86, "seconds": 0.17, "stale_uploading": 0} +baseline (data left by earlier tests): {"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 366, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 203, "seconds": 0.253, "stale_uploading": 0} == dry-run, grace=900 == -{"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 2, "objects_scanned": 118, "orphan_objects": 0, "protected_fresh_objects": 2, "removed_rows": 0, "rows_scanned": 89, "seconds": 0.087, "stale_uploading": 1} +{"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 2, "objects_scanned": 371, "orphan_objects": 0, "protected_fresh_objects": 2, "removed_rows": 0, "rows_scanned": 206, "seconds": 0.264, "stale_uploading": 1} ok dry-run: 1 new stale row (b), 2 old rows protected by young objects (a, h) ok dry-run: 2 new missing objects (e, g) ok dry-run changes nothing == apply, grace=900 == -{"deleted_objects": 0, "dry_run": false, "grace_seconds": 900, "marked_failed": 2, "missing_objects": 2, "objects_scanned": 118, "orphan_objects": 0, "protected_fresh_objects": 2, "removed_rows": 1, "rows_scanned": 89, "seconds": 0.1, "stale_uploading": 1} +{"deleted_objects": 0, "dry_run": false, "grace_seconds": 900, "marked_failed": 2, "missing_objects": 2, "objects_scanned": 371, "orphan_objects": 0, "protected_fresh_objects": 2, "removed_rows": 1, "rows_scanned": 206, "seconds": 0.273, "stale_uploading": 1} ok old row whose object is young is kept (a) ok stale row without object removed ok fresh in-flight upload untouched @@ -16,15 +16,15 @@ ok missing unused object marked failed ok used attachment with object untouched ok used attachment with lost object kept, marked failed == apply after grace expired (grace=2 after 3s) == -{"deleted_objects": 4, "dry_run": false, "grace_seconds": 2, "marked_failed": 1, "missing_objects": 1, "objects_scanned": 115, "orphan_objects": 1, "protected_fresh_objects": 0, "removed_rows": 3, "rows_scanned": 115, "seconds": 0.126, "stale_uploading": 3} +{"deleted_objects": 4, "dry_run": false, "grace_seconds": 2, "marked_failed": 1, "missing_objects": 1, "objects_scanned": 368, "orphan_objects": 1, "protected_fresh_objects": 0, "removed_rows": 3, "rows_scanned": 368, "seconds": 0.428, "stale_uploading": 3} ok orphan object deleted after grace ok expired in-flight row collected after grace ok old row + object collected once the object is older than grace (a, h) ok used attachment still untouched == second apply is idempotent == -{"deleted_objects": 0, "dry_run": false, "grace_seconds": 2, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 114, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 114, "seconds": 0.163, "stale_uploading": 0} +{"deleted_objects": 0, "dry_run": false, "grace_seconds": 2, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 367, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 367, "seconds": 0.457, "stale_uploading": 0} ok repeat run changes nothing == cost of a full walk, 1000 ready attachments == -{"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 1114, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 1087, "seconds": 1.63, "stale_uploading": 0} +{"deleted_objects": 0, "dry_run": true, "grace_seconds": 900, "marked_failed": 0, "missing_objects": 0, "objects_scanned": 1367, "orphan_objects": 0, "protected_fresh_objects": 0, "removed_rows": 0, "rows_scanned": 1204, "seconds": 1.605, "stale_uploading": 0} ok bulk walk finds nothing wrong RESULT: 18/18 checks passed diff --git a/infra/nginx.conf b/infra/nginx.conf index 6028a5b..5d791ed 100644 --- a/infra/nginx.conf +++ b/infra/nginx.conf @@ -1,4 +1,4 @@ -worker_processes auto; +worker_processes 2; events { worker_connections 256; @@ -22,7 +22,7 @@ http { server { listen 8080; - client_max_body_size 11m; + client_max_body_size 64k; error_page 413 @payload_too_large; proxy_http_version 1.1; @@ -42,6 +42,8 @@ http { } location ~ ^/api/v1/chats/[^/]+/attachments$ { + client_max_body_size 10m; + proxy_request_buffering off; proxy_pass http://api; proxy_next_upstream off; } @@ -60,6 +62,7 @@ http { } location ~ ^/api/v1/attachments/ { + proxy_max_temp_file_size 0; proxy_pass http://api; proxy_next_upstream error timeout; } diff --git a/scripts/jpeg_check_experiment.py b/scripts/jpeg_check_experiment.py index cbff869..4d1c8a8 100644 --- a/scripts/jpeg_check_experiment.py +++ b/scripts/jpeg_check_experiment.py @@ -1,33 +1,91 @@ -import io, os, sys, tempfile, time +#!/usr/bin/env python3 +"""JPEG integrity matrix and peak memory of the checker. + docker run --rm --entrypoint python mtusi-messenger:lab4 scripts/jpeg_check_experiment.py""" +import io +import os +import subprocess +import sys +import tempfile +import time + sys.path.insert(0, "/app") -from PIL import Image -from app.errors import ApiError -from app.imagecheck import inspect_image + +from PIL import Image # noqa: E402 + +from app.errors import ApiError # noqa: E402 +from app.imagecheck import DJPEG, inspect_image # noqa: E402 + + +def encode(img, **kw): + out = io.BytesIO() + img.save(out, "JPEG", **kw) + return out.getvalue() -def jpeg(w, h, progressive=False): - img = Image.frombytes("RGB", (w, h), os.urandom(w * h * 3)) - b = io.BytesIO(); img.save(b, "JPEG", quality=80, progressive=progressive); return b.getvalue() def verdict(data): - f = tempfile.SpooledTemporaryFile(); f.write(data) - started = time.monotonic() - try: - inspect_image(f, len(data), "image/jpeg"); r = "accepted" - except ApiError as e: - r = "rejected %d" % e.status - return r, time.monotonic() - started + with tempfile.SpooledTemporaryFile(max_size=1048576) as spool: + spool.write(data) + try: + inspect_image(spool, len(data), "image/jpeg") + return "accepted" + except ApiError as exc: + return "rejected %d" % exc.status -ok = True -for name, data, expect in [ - ("valid 3000x2000 baseline", jpeg(3000, 2000), "accepted"), - ("valid 3000x2000 progressive", jpeg(3000, 2000, True), "accepted"), + +def child_peak_kib(data): + with tempfile.NamedTemporaryFile() as handle: + handle.write(data) + handle.flush() + handle.seek(0) + proc = subprocess.Popen(DJPEG, stdin=handle) + peak = 0 + while proc.poll() is None: + try: + with open("/proc/%d/status" % proc.pid) as status: + for line in status: + if line.startswith("VmHWM"): + peak = max(peak, int(line.split()[1])) + except OSError: + pass + time.sleep(0.002) + return peak + + +noise = Image.frombytes("RGB", (1000, 750), os.urandom(1000 * 750 * 3)) +base = encode(noise, quality=90) +progressive = encode(noise, quality=90, progressive=True) +flat = Image.new("RGB", (8000, 5000), (120, 30, 200)) +big_base = encode(flat, quality=90) +big_progressive = encode(flat, quality=90, progressive=True) +big_444 = encode(flat, quality=90, progressive=True, subsampling=0) +big_cmyk = encode(flat.convert("CMYK"), quality=90, progressive=True) +del flat +sos = base.index(b"\xff\xda") +cases = [ + ("valid baseline", base, "accepted"), + ("valid progressive", progressive, "accepted"), + ("valid grayscale", encode(noise.convert("L")), "accepted"), + ("valid CMYK", encode(noise.convert("CMYK")), "accepted"), + ("valid, junk after EOI", base + b"trailing", "accepted"), + ("valid 40 Mpx baseline", big_base, "accepted"), + ("valid 40 Mpx progressive", big_progressive, "accepted"), + ("valid 40 Mpx progressive 444", big_444, "accepted"), + ("valid 40 Mpx progressive CMYK", big_cmyk, "accepted"), ("27-byte stub", bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9"), "rejected 415"), -]: - r, t = verdict(data); ok &= r == expect; print("%-34s %-13s %.2fs %s" % (name, r, t, "ok" if r == expect else "FAIL")) -big = jpeg(3000, 2000) -sos = big.index(b"\xff\xda") -cut = big[: len(big) // 2] -r, t = verdict(cut); ok &= r == "rejected 415"; print("%-34s %-13s %.2fs %s" % ("scan cut in half, no EOI", r, t, "ok" if r == "rejected 415" else "FAIL")) -noscan = big[:sos] + b"\xff\xd9" -r, t = verdict(noscan); ok &= r == "rejected 415"; print("%-34s %-13s %.2fs %s" % ("headers only + EOI", r, t, "ok" if r == "rejected 415" else "FAIL")) -sys.exit(0 if ok else 1) + ("first half + EOI", base[: len(base) // 2] + b"\xff\xd9", "rejected 415"), + ("first half, no EOI", base[: len(base) // 2], "rejected 415"), + ("progressive half + EOI", progressive[: len(progressive) // 2] + b"\xff\xd9", "rejected 415"), + ("headers only + EOI", base[:sos] + b"\xff\xd9", "rejected 415"), +] +failed = 0 +for name, data, expected in cases: + started = time.monotonic() + got = verdict(data) + ok = got == expected + failed += not ok + print("%-28s %9d bytes %-13s %.2fs %s" % (name, len(data), got, time.monotonic() - started, "ok" if ok else "FAIL")) +for name, data in (("40 Mpx baseline", big_base), ("40 Mpx progressive", big_progressive), + ("40 Mpx progressive 444", big_444), ("40 Mpx progressive CMYK", big_cmyk)): + print("checker peak RSS, %-24s %6.1f MiB" % (name, child_peak_kib(data) / 1024)) +print("RESULT: %d/%d" % (len(cases) - failed, len(cases))) +sys.exit(1 if failed else 0) diff --git a/student-tests/memory_experiment.py b/student-tests/memory_experiment.py index e042c42..ce69166 100644 --- a/student-tests/memory_experiment.py +++ b/student-tests/memory_experiment.py @@ -83,7 +83,7 @@ def main(): "payload_mib": round(len(body) / 1048576, 2), "concurrency": args.concurrency, "rounds": args.rounds, "idle_mib": {k: round(v, 1) for k, v in idle.items()}, "peak_mib": {k: round(max(p.get(k, 0) for p in peaks), 1) for k in idle}, - "container_limit_mib": 256, + "container_limit_mib": 512, "statuses": {str(s): statuses.count(s) for s in sorted(set(statuses))}, "upload_seconds_median": round(statistics.median(times), 2), "upload_seconds_max": round(max(times), 2), } diff --git a/student-tests/test_input_hardening.py b/student-tests/test_input_hardening.py index ad2a6a9..8ae649a 100644 --- a/student-tests/test_input_hardening.py +++ b/student-tests/test_input_hardening.py @@ -3,6 +3,7 @@ import hashlib import os import struct +import subprocess import sys import uuid import zlib @@ -44,6 +45,16 @@ def main(): up(png(64, 64, corrupt_idat=True), "image/png", 415) up(JPEG_STUB, "image/jpeg", 415) print("ok truncated PNG, bad filter byte, broken IDAT, 27-byte JPEG stub -> 415") + real = subprocess.run( + ["docker", "run", "--rm", "--entrypoint", "python", "mtusi-messenger:lab4", "-c", + "import io,os,sys;from PIL import Image;b=io.BytesIO();" + "Image.frombytes('RGB',(1000,750),os.urandom(2250000)).save(b,'JPEG',quality=90);" + "sys.stdout.buffer.write(b.getvalue())"], capture_output=True, check=True).stdout + whole = up(real, "image/jpeg", 201, name="real.jpg")["json"] + check(c.call("GET", "/api/v1/attachments/" + whole["id"] + "/content", actor=bob)["bytes"] == real, "JPEG bytes differ") + up(real[: len(real) // 2] + b"\xff\xd9", "image/jpeg", 415, name="cut.jpg") + up(real[: len(real) // 2], "image/jpeg", 415, name="cut.jpg") + print("ok real JPEG accepted; first half + EOI and first half alone -> 415") up(png(3000, 2000, filter_byte=7), "image/png", 415) up(png(3000, 2000, corrupt_idat=True, noise=True), "image/png", 415) print("ok same defects in images above the full-decode threshold (6 Mpx) -> 415") diff --git a/student-tests/test_lb_stress.py b/student-tests/test_lb_stress.py new file mode 100644 index 0000000..fa605d9 --- /dev/null +++ b/student-tests/test_lb_stress.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""LB under upload pressure: no OOM/restart of any container, no HTML 502, every rejection is API-shaped JSON. + python3 student-tests/test_lb_stress.py --concurrency 10 --rounds 3 --oversize 200""" +import argparse +import base64 +import collections +import http.client +import json +import os +import struct +import subprocess +import sys +import threading +import uuid +import zlib +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HOST, PORT = "localhost", 8080 +LIMIT = 10485760 + + +def noise_png(side): + raw = b"".join(b"\0" + os.urandom(side * 3) for _ in range(side)) + + def chunk(kind, body): + return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF) + + ihdr = struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b"") + + +def request(method, path, body=None, headers=None, timeout=90): + """Returns (status, content_type, payload) or ('EXC:', '', b'').""" + conn = http.client.HTTPConnection(HOST, PORT, timeout=timeout) + try: + conn.request(method, path, body=body, headers=headers or {}) + response = conn.getresponse() + return response.status, response.getheader("Content-Type", ""), response.read() + except Exception as exc: + return "EXC:" + type(exc).__name__, "", b"" + finally: + conn.close() + + +def actor(label): + username = "st_%s_%s" % (label, uuid.uuid4().hex[:10]) + password = "T3st-" + uuid.uuid4().hex + body = {"username": username, "display_name": label, "password": password} + status, _, _ = request("POST", "/api/v1/users", json.dumps(body), {"Content-Type": "application/json"}) + assert status == 201, status + basic = base64.b64encode((username + ":" + password).encode()).decode() + status, _, data = request("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}) + assert status == 201, status + session = json.loads(data) + return session["user"]["id"], {"Authorization": "Bearer " + session["token"]} + + +def container_ids(): + out = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() + names = {} + for cid in out: + name = subprocess.run(["docker", "inspect", "--format", "{{.Name}}", cid], capture_output=True, text=True).stdout + names[cid] = name.strip().lstrip("/") + return names + + +def peak_mib(name): + out = subprocess.run(["docker", "exec", name, "cat", "/sys/fs/cgroup/memory.peak"], capture_output=True, text=True) + return round(int(out.stdout) / 1048576, 1) if out.stdout.strip().isdigit() else None + + +class Events(threading.Thread): + def __init__(self): + super().__init__(daemon=True) + self.lines = [] + self.proc = subprocess.Popen( + ["docker", "events", "--filter", "type=container", "--filter", "event=oom", "--filter", "event=die", + "--filter", "event=restart", "--format", "{{.Action}} {{.Actor.Attributes.name}} exit={{.Actor.Attributes.exitCode}}"], + stdout=subprocess.PIPE, text=True, + ) + + def run(self): + for line in self.proc.stdout: + self.lines.append(line.strip()) + + def stop(self): + self.proc.terminate() + + +def is_json_error(result, code): + status, ctype, data = result + if status != code or not ctype.startswith("application/json"): + return False + return json.loads(data)["error"]["code"] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--concurrency", type=int, default=10) + parser.add_argument("--rounds", type=int, default=3) + parser.add_argument("--oversize", type=int, default=200) + args = parser.parse_args() + # memory.peak is cumulative since container start, so read it after a fresh recreate. + + failures = [] + events = Events() + events.start() + uid, auth = actor("a") + _, outsider = actor("b") + status, _, data = request("POST", "/api/v1/chats", json.dumps({"title": "stress", "member_ids": [uid]}), + {**auth, "Content-Type": "application/json"}) + assert status == 201, status + chat = json.loads(data)["id"] + upload = "/api/v1/chats/%s/attachments?filename=s.png" % chat + png_headers = {**auth, "Content-Type": "image/png"} + + body = noise_png(1700) + print("== %d parallel uploads of %d bytes, %d rounds ==" % (args.concurrency, len(body), args.rounds)) + ids, tally = [], collections.Counter() + for _ in range(args.rounds): + with ThreadPoolExecutor(args.concurrency) as pool: + results = list(pool.map(lambda _: request("POST", upload, body, png_headers), range(args.concurrency))) + for status, _, data in results: + tally[status] += 1 + if status == 201: + ids.append(json.loads(data)["id"]) + print("upload statuses:", dict(tally)) + if set(tally) != {201}: + failures.append("parallel uploads: %s" % dict(tally)) + + print("== %d parallel downloads ==" % args.concurrency) + with ThreadPoolExecutor(args.concurrency) as pool: + results = list(pool.map(lambda i: request("GET", "/api/v1/attachments/%s/content" % i, headers=auth), + ids[:args.concurrency * 2])) + tally = collections.Counter(r[0] for r in results) + print("download statuses:", dict(tally)) + if set(tally) != {200} or any(r[2] != body for r in results): + failures.append("parallel downloads: %s" % dict(tally)) + + print("== %d parallel valid 40 Mpx progressive CMYK JPEGs (worst case for the checker), %d rounds ==" % (args.concurrency, args.rounds)) + jpeg = subprocess.run( + ["docker", "run", "--rm", "--entrypoint", "python", "mtusi-messenger:lab4", "-c", + "import io,sys;from PIL import Image;b=io.BytesIO();" + "Image.new('CMYK',(8000,5000),(120,30,200,5)).save(b,'JPEG',quality=90,progressive=True);" + "sys.stdout.buffer.write(b.getvalue())"], capture_output=True, check=True).stdout + tally = collections.Counter() + for _ in range(args.rounds): + with ThreadPoolExecutor(args.concurrency) as pool: + results = list(pool.map(lambda _: request("POST", upload, jpeg, {**auth, "Content-Type": "image/jpeg"}), + range(args.concurrency))) + tally.update(r[0] for r in results) + print("upload statuses:", dict(tally)) + if set(tally) != {201}: + failures.append("parallel progressive JPEG: %s" % dict(tally)) + + cases = [ + ("10 MiB + 1 byte, Content-Length", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (LIMIT - 7), png_headers, 413, "payload_too_large"), + ("10 MiB + 1 byte, chunked", upload, iter([b"\x89PNG\r\n\x1a\n" + b"\0" * (LIMIT - 7)]), png_headers, 413, "payload_too_large"), + ("10 MiB + 1 byte, chunked in 64 KiB pieces", upload, + [b"\x89PNG\r\n\x1a\n"] + [b"\0" * 65536] * 160, png_headers, 413, "payload_too_large"), + ("8 MiB to a foreign chat", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (8 << 20), {**outsider, "Content-Type": "image/png"}, 404, "not_found"), + ("8 MiB without session", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (8 << 20), {"Content-Type": "image/png"}, 401, "unauthorized"), + ("8 MiB with wrong magic", upload, b"X" * (8 << 20), png_headers, 415, "unsupported_media_type"), + ("8 MiB with wrong Content-Type", upload, b"X" * (8 << 20), {**auth, "Content-Type": "image/gif"}, 415, "unsupported_media_type"), + ("70 KiB JSON message", "/api/v1/chats/%s/messages" % chat, b'{"text":"' + b"x" * (70 << 10) + b'"}', + {**auth, "Content-Type": "application/json", "Idempotency-Key": "k"}, 413, "payload_too_large"), + ] + for name, path, payload, headers, code, error in cases: + print("== %s: %d requests, %d at a time ==" % (name, args.oversize, args.concurrency)) + materialized = list(payload) if not isinstance(payload, bytes) else None + + def one(_): + data = payload if materialized is None else iter(materialized) + extra = {} if materialized is None else {"Transfer-Encoding": "chunked"} + conn_headers = {**headers, **extra} + conn = http.client.HTTPConnection(HOST, PORT, timeout=90) + try: + conn.request("POST", path, body=data, headers=conn_headers, encode_chunked=materialized is not None) + response = conn.getresponse() + return response.status, response.getheader("Content-Type", ""), response.read() + except Exception as exc: + return "EXC:" + type(exc).__name__, "", b"" + finally: + conn.close() + + with ThreadPoolExecutor(args.concurrency) as pool: + results = list(pool.map(one, range(args.oversize))) + tally = collections.Counter((r[0], r[1].split(";")[0]) for r in results) + print(" ", {"%s %s" % k: v for k, v in tally.items()}) + if not all(is_json_error(r, code) == error for r in results): + failures.append("%s: %s" % (name, dict(tally))) + + status, _, _ = request("GET", "/health/ready") + if status != 200: + failures.append("not ready after the run: %s" % status) + events.stop() + bad = [line for line in events.lines if " mtusi-lab4-" in line] + print("container events during the run:", bad or "none") + if bad: + failures.append("container events: %s" % bad) + print("cgroup memory.peak, MiB:", {n: peak_mib(n) for n in container_ids().values() if "api-" in n or "nginx" in n}) + for failure in failures: + print("FAIL:", failure) + print("PASS: LB stress" if not failures else "FAILED: %d" % len(failures)) + sys.exit(1 if failures else 0) + + +main()