1 Commits
Author SHA1 Message Date
Vladislav Kunetskiy 01b885e846 lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
2026-10-31 14:34:24 +03:00
18 changed files with 1431 additions and 57 deletions
+7
View File
@@ -110,6 +110,7 @@ flowchart LR
| Полный restart стека | `lab5_async.py` | ready-вложение и original сохранились | `evidence/lab5/async.txt` | | Полный restart стека | `lab5_async.py` | ready-вложение и original сохранились | `evidence/lab5/async.txt` |
| Варианты: thumbnail/crop/optimized | `make test-queue`/`lab5_variants.py` | thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP 320×200; metadata == bytes; EXIF отсутствует | `evidence/lab5/variants.txt` | | Варианты: thumbnail/crop/optimized | `make test-queue`/`lab5_variants.py` | thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized WebP 320×200; metadata == bytes; EXIF отсутствует | `evidence/lab5/variants.txt` |
| Состояния queued/processing/ready/failed | `lab5_async.py`, `lab5_faults.py` | queued/ready и failed/error_code наблюдаются через API | `evidence/lab5/async.txt`, `faults.txt` | | Состояния queued/processing/ready/failed | `lab5_async.py`, `lab5_faults.py` | queued/ready и failed/error_code наблюдаются через API | `evidence/lab5/async.txt`, `faults.txt` |
| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib, битый tRNS, PLTE сверх bit depth, tRNS сверх PLTE — 415 до 202 | `evidence/lab5/attachments-negative.txt` |
| Original неизменен | smoke + variants | скачанные байты и sha совпадают с загруженными | `evidence/lab5/smoke.txt`, `variants.txt` | | Original неизменен | smoke + variants | скачанные байты и sha совпадают с загруженными | `evidence/lab5/smoke.txt`, `variants.txt` |
| Retry/backoff/classification | `make test-faults` | permanent → failed сразу; transient → 5 attempts, 4 retry events, `retry_exhausted`; DLQ | `evidence/lab5/faults.txt` | | Retry/backoff/classification | `make test-faults` | permanent → failed сразу; transient → 5 attempts, 4 retry events, `retry_exhausted`; DLQ | `evidence/lab5/faults.txt` |
| DLQ/registry + replay | `lab5_faults.py` | failed виден в `jobctl failed`; replay → ready; replay ready refused | `evidence/lab5/faults.txt` | | DLQ/registry + replay | `lab5_faults.py` | failed виден в `jobctl failed`; replay → ready; replay ready refused | `evidence/lab5/faults.txt` |
@@ -148,6 +149,12 @@ flowchart LR
| Transient errors | 5 attempts, backoff+jitter, failed | attempts=5, `retry_exhausted`, DLQ | | Transient errors | 5 attempts, backoff+jitter, failed | attempts=5, `retry_exhausted`, DLQ |
| Failed replay | failed→queued→ready без дубля | ready, один thumbnail | | Failed replay | failed→queued→ready без дубля | ready, один thumbnail |
| v1 ready → reprocess v2 → old v1 delivery | v2 не перезаписывается | pv=2, variants v2, stale v1 ack | | v1 ready → reprocess v2 → old v1 delivery | v2 не перезаписывается | pv=2, variants v2, stale v1 ack |
| Reprocess queued при остановленном worker | v2 берёт проверенный staging, а не несуществующий original | pv=2 ready, v1 superseded, событие superseded записано |
| Reprocess v2 падает до публикации | вложение терминально failed, не вечный queued | failed/error_code, active jobs 0 |
| Replay упавшей v2 до публикации | API не показывает stale failed, работа возвращается | job queued, attachment queued, затем ready:v2 |
| Replay старой failed-v1 при наличии v2 | команда отклонена, источник v2 не потерян | v1 failed, v2 queued → ready:v2 |
| Version-stale queued job после публикации v2 | задание терминально superseded, не переиздаётся | claim → superseded, reconcile не создаёт работу |
| Reprocess на неподдерживаемую версию | команда отклонена, v1-задание не тронуто | jobctl exit != 0, v1 queued → ready |
Измерения: recovery времени и counts — из `evidence/lab5/faults.txt`, `track2/runs.csv`. Измерения: recovery времени и counts — из `evidence/lab5/faults.txt`, `track2/runs.csv`.
Стенд: 2 vCPU, 2 ГБ Docker VM; синтетические пользователи/чат; fixture 320×200 PNG. Стенд: 2 vCPU, 2 ГБ Docker VM; синтетические пользователи/чат; fixture 320×200 PNG.
+5
View File
@@ -12,6 +12,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"mtusi-messenger/internal/config" "mtusi-messenger/internal/config"
"mtusi-messenger/internal/imageproc"
"mtusi-messenger/internal/logger" "mtusi-messenger/internal/logger"
"mtusi-messenger/internal/storage/postgres" "mtusi-messenger/internal/storage/postgres"
) )
@@ -109,6 +110,10 @@ func runReprocess(ctx context.Context, repo *postgres.PipelineRepository, cfg co
version := flags.Int("pipeline", 2, "target pipeline version") version := flags.Int("pipeline", 2, "target pipeline version")
_ = flags.Parse(os.Args[2:]) _ = flags.Parse(os.Args[2:])
if _, ok := imageproc.Pipeline(*version); !ok {
fail(fmt.Errorf("unsupported pipeline version %d", *version))
}
id, err := uuid.Parse(*attachmentID) id, err := uuid.Parse(*attachmentID)
if err != nil { if err != nil {
fail(fmt.Errorf("invalid attachment id: %w", err)) fail(fmt.Errorf("invalid attachment id: %w", err))
+6 -1
View File
@@ -1,7 +1,12 @@
# lab5_async 2026-10-30T20:15:54Z # make test-queue 2026-10-31T11:26:40Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/lab5_async.py --base-url "http://localhost:8080"
worker down: 202 queued, content 409, queued attachment linked, API restarted worker down: 202 queued, content 409, queued attachment linked, API restarted
worker restarted: ready, thumbnail and original downloadable, staging cleared worker restarted: ready, thumbnail and original downloadable, staging cleared
broker down: upload accepted into outbox broker down: upload accepted into outbox
broker + relay recovered: queued job reached ready broker + relay recovered: queued job reached ready
stack restart: ready attachment and original preserved stack restart: ready attachment and original preserved
worker down: reprocess pipeline 2 accepted, v1 audit event recorded, upload still queued
worker up: reprocessed upload reached ready at pipeline 2, v1 superseded
worker down: reprocess pipeline 3 refused, v1 job untouched
worker up: preserved upload reached ready at pipeline 1
PASS: lab5 async worker/broker durability PASS: lab5 async worker/broker durability
+11 -1
View File
@@ -1,9 +1,19 @@
# attachments negative 2026-10-30T20:11:40Z # make test-attachments 2026-10-31T11:26:14Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/attachments_negative.py --base-url "http://localhost:8080" env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/attachments_negative.py --base-url "http://localhost:8080"
10 MiB + 1 body: 413 10 MiB + 1 body: 413
empty body: 415 empty body: 415
corrupt PNG (IDAT CRC): 415 corrupt PNG (IDAT CRC): 415
MIME spoof (PNG declared as JPEG): 415 MIME spoof (PNG declared as JPEG): 415
structurally valid PNG with non-zlib IDAT: 415
valid zlib, empty PNG raster: 415
valid zlib, invalid PNG scanline filter: 415
invalid PNG color type/bit depth pair: 415
duplicate PNG IHDR: 415
trailing bytes after PNG zlib stream: 415
tRNS on RGBA PNG: 415
short tRNS on RGB PNG: 415
PLTE entries exceed palette bit depth: 415
palette tRNS exceeds PLTE entries: 415
dangerous filenames: 400 dangerous filenames: 400
foreign attachment metadata/content: 404 foreign attachment metadata/content: 404
empty text without attachments: 400 empty text without attachments: 400
+5 -1
View File
@@ -1,7 +1,11 @@
# fault injection 2026-10-30T20:09:37Z # make test-faults 2026-10-31T11:27:03Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 student-tests/lab5_faults.py --base-url "http://localhost:8080"
permanent failure: failed/injected_failure, content 409, failed attachment not linkable, registry visible permanent failure: failed/injected_failure, content 409, failed attachment not linkable, registry visible
replay: failed -> queued -> ready, one thumbnail replay: failed -> queued -> ready, one thumbnail
replay ready job: refused replay ready job: refused
replay older failed version while v2 queued: refused, state intact
v2 published after older replay refusal
replay of failed reprocess: queued projection restored, then ready at pipeline 2
transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present
crash after first variant: redelivered, same three variants, attempts=2 crash after first variant: redelivered, same three variants, attempts=2
crash after commit before ack: ready remains, redelivery is a no-op crash after commit before ack: ready remains, redelivery is a no-op
+2 -2
View File
@@ -1,2 +1,2 @@
ok mtusi-messenger/internal/storage/postgres 8.765s ok mtusi-messenger/internal/storage/postgres 9.448s
ok mtusi-messenger/internal/storage/redis 1.264s ok mtusi-messenger/internal/storage/redis 1.238s
+11 -11
View File
@@ -3,18 +3,18 @@ level=info msg="golangci-lint has version 2.13.2 built with go1.27.1 from (unkno
level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab5 /Users/vladislav/Projects /Users/vladislav /Users /]" level=info msg="[config_reader] Config search paths: [./ /Users/vladislav/Projects/mtusi2026lab5 /Users/vladislav/Projects /Users/vladislav /Users /]"
level=info msg="[config_reader] Used config file .golangci.yml" level=info msg="[config_reader] Used config file .golangci.yml"
level=info msg="[config_reader] Module name \"mtusi-messenger\"" level=info msg="[config_reader] Module name \"mtusi-messenger\""
level=info msg="[goenv] Read go env for 5.669667ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}" level=info msg="[goenv] Read go env for 6.264542ms: map[string]string{\"GOCACHE\":\"/Users/vladislav/Library/Caches/go-build\", \"GOROOT\":\"/opt/homebrew/Cellar/go/1.27.1/libexec\"}"
level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]" level=info msg="[lintersdb] Active 50 linters: [asasalint bodyclose canonicalheader containedctx contextcheck copyloopvar depguard durationcheck errcheck errname errorlint exhaustive exptostd fatcontext forbidigo forcetypeassert gocheckcompilerdirectives gocritic gofumpt goimports gomoddirectives gosec govet ineffassign intrange makezero misspell musttag nilerr nilnil noctx nolintlint perfsprint prealloc reassign recvcheck revive rowserrcheck sloglint sqlclosecheck staticcheck testifylint thelper tparallel unconvert unparam unused usestdlibvars usetesting wastedassign]"
level=info msg="[loader] Using build tags: [integration]" level=info msg="[loader] Using build tags: [integration]"
level=info msg="[loader] Go packages loading at mode 8767 (types_sizes|compiled_files|deps|exports_file|files|imports|name) took 398.270958ms" level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|files|types_sizes|imports|name) took 193.808375ms"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 8.419166ms" level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 11.667ms"
level=info msg="[linters_context/goanalysis] analyzers took 17.795929123s with top 10 stages: revive: 2.679376249s, goimports: 2.060329333s, gosec: 959.427623ms, unparam: 664.839042ms, buildir: 377.707742ms, wastedassign: 367.190043ms, buildssa: 253.050133ms, gocritic: 223.117835ms, sloglint: 209.844082ms, gofumpt: 182.648499ms" level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages"
level=info msg="[runner/exclusion_rules] Skipped 8 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]" level=info msg="[runner/exclusion_rules] Skipped 14 issues by rules: [Path: \"_test\\\\.go\", Linters: \"gosec, prealloc, forcetypeassert, unparam\"]"
level=info msg="[runner] Issues before processing: 881, after processing: 0" level=info msg="[runner] Issues before processing: 887, after processing: 0"
level=info msg="[runner] Processors filtering stat (in/out): path_relativity: 881/881, nolint_filter: 6/0, path_absoluter: 881/881, cgo: 881/881, invalid_issue: 881/881, exclusion_paths: 881/881, generated_file_filter: 881/292, filename_unadjuster: 881/881, exclusion_rules: 292/6" level=info msg="[runner] Processors filtering stat (in/out): path_absoluter: 887/887, cgo: 887/887, filename_unadjuster: 887/887, nolint_filter: 6/0, invalid_issue: 887/887, exclusion_paths: 887/887, path_relativity: 887/887, generated_file_filter: 887/298, exclusion_rules: 298/6"
level=info msg="[runner] processing took 3.036ms with stages: generated_file_filter: 1.950667ms, nolint_filter: 532.917µs, path_relativity: 274.626µs, exclusion_rules: 236.792µs, invalid_issue: 18.708µs, cgo: 11.417µs, path_absoluter: 5.083µs, filename_unadjuster: 3.417µs, sort_results: 666ns, max_same_issues: 459ns, fixer: 291ns, exclusion_paths: 251ns, path_prettifier: 166ns, path_shortener: 124ns, diff: 84ns, uniq_by_line: 83ns, max_from_linter: 83ns, max_per_file_from_linter: 83ns, severity-rules: 42ns, source_code: 41ns" level=info msg="[runner] processing took 2.828168ms with stages: generated_file_filter: 1.490334ms, nolint_filter: 764.209µs, path_relativity: 284.917µs, exclusion_rules: 251.001µs, invalid_issue: 13.417µs, cgo: 12.25µs, path_absoluter: 4.666µs, sort_results: 2.916µs, filename_unadjuster: 2.542µs, max_same_issues: 874ns, diff: 167ns, fixer: 166ns, path_prettifier: 125ns, max_per_file_from_linter: 125ns, exclusion_paths: 125ns, path_shortener: 124ns, uniq_by_line: 84ns, severity-rules: 42ns, max_from_linter: 42ns, source_code: 42ns"
level=info msg="[runner] linters took 2.038491625s with stages: goanalysis_metalinter: 2.035411833s" level=info msg="[runner] linters took 629.148708ms with stages: goanalysis_metalinter: 626.277292ms"
0 issues. 0 issues.
level=info msg="File cache stats: 0 entries of total size 0B" level=info msg="File cache stats: 0 entries of total size 0B"
level=info msg="Memory: 26 samples, avg is 296.0MB, max is 586.1MB" level=info msg="Memory: 10 samples, avg is 87.2MB, max is 111.5MB"
level=info msg="Execution took 2.45183725s" level=info msg="Execution took 841.622625ms"
+1 -1
View File
@@ -1,3 +1,3 @@
# make test 2026-10-30T20:15:52Z # make test 2026-10-31T11:26:59Z
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://localhost:8080" env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+17 -17
View File
@@ -6,35 +6,35 @@ env -u APP_ENV -u SERVER_HOST -u SERVER_PORT -u SERVER_READ_HEADER_TIMEOUT -u SE
? mtusi-messenger/cmd/s3init [no test files] ? mtusi-messenger/cmd/s3init [no test files]
? mtusi-messenger/cmd/worker [no test files] ? mtusi-messenger/cmd/worker [no test files]
? mtusi-messenger/internal/broker [no test files] ? mtusi-messenger/internal/broker [no test files]
ok mtusi-messenger/internal/config 1.386s ok mtusi-messenger/internal/config 1.717s
ok mtusi-messenger/internal/domain 1.658s ok mtusi-messenger/internal/domain 2.647s
? mtusi-messenger/internal/failpoint [no test files] ? mtusi-messenger/internal/failpoint [no test files]
ok mtusi-messenger/internal/health 2.083s ok mtusi-messenger/internal/health 1.315s
ok mtusi-messenger/internal/imagecheck 4.315s ok mtusi-messenger/internal/imagecheck 3.766s
ok mtusi-messenger/internal/imageproc 5.409s ok mtusi-messenger/internal/imageproc 2.400s
ok mtusi-messenger/internal/logger 4.670s ok mtusi-messenger/internal/logger 2.338s
? mtusi-messenger/internal/outbox [no test files] ? mtusi-messenger/internal/outbox [no test files]
ok mtusi-messenger/internal/platform/cache 4.248s ok mtusi-messenger/internal/platform/cache 4.909s
? mtusi-messenger/internal/platform/cache/mocks [no test files] ? mtusi-messenger/internal/platform/cache/mocks [no test files]
ok mtusi-messenger/internal/platform/objectstore 3.614s ok mtusi-messenger/internal/platform/objectstore 6.507s
ok mtusi-messenger/internal/platform/password 6.512s ok mtusi-messenger/internal/platform/password 3.349s
ok mtusi-messenger/internal/platform/token 5.267s ok mtusi-messenger/internal/platform/token 3.304s
ok mtusi-messenger/internal/service/attachment 5.575s ok mtusi-messenger/internal/service/attachment 5.105s
? mtusi-messenger/internal/service/attachment/mocks [no test files] ? mtusi-messenger/internal/service/attachment/mocks [no test files]
ok mtusi-messenger/internal/service/chat 5.869s ok mtusi-messenger/internal/service/chat 4.460s
? mtusi-messenger/internal/service/chat/mocks [no test files] ? mtusi-messenger/internal/service/chat/mocks [no test files]
ok mtusi-messenger/internal/service/message 3.241s ok mtusi-messenger/internal/service/message 4.119s
? mtusi-messenger/internal/service/message/mocks [no test files] ? mtusi-messenger/internal/service/message/mocks [no test files]
ok mtusi-messenger/internal/service/session 2.799s ok mtusi-messenger/internal/service/session 5.771s
? mtusi-messenger/internal/service/session/mocks [no test files] ? mtusi-messenger/internal/service/session/mocks [no test files]
ok mtusi-messenger/internal/service/user 3.064s ok mtusi-messenger/internal/service/user 6.251s
? mtusi-messenger/internal/service/user/mocks [no test files] ? mtusi-messenger/internal/service/user/mocks [no test files]
ok mtusi-messenger/internal/storage/postgres 6.169s ok mtusi-messenger/internal/storage/postgres 6.484s
? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files] ? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [no test files]
? mtusi-messenger/internal/storage/postgres/migrations [no test files] ? mtusi-messenger/internal/storage/postgres/migrations [no test files]
? mtusi-messenger/internal/storage/redis [no test files] ? mtusi-messenger/internal/storage/redis [no test files]
? mtusi-messenger/internal/storage/redis/mocks [no test files] ? mtusi-messenger/internal/storage/redis/mocks [no test files]
ok mtusi-messenger/internal/transport/rest 6.517s ok mtusi-messenger/internal/transport/rest 6.893s
? mtusi-messenger/internal/transport/rest/internal/oas [no test files] ? mtusi-messenger/internal/transport/rest/internal/oas [no test files]
? mtusi-messenger/internal/transport/rest/mocks [no test files] ? mtusi-messenger/internal/transport/rest/mocks [no test files]
? mtusi-messenger/internal/worker [no test files] ? mtusi-messenger/internal/worker [no test files]
+2
View File
@@ -1 +1,3 @@
# make validate PYTHON=.venv/bin/python 2026-10-30T22:22:13Z
.venv/bin/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+314 -11
View File
@@ -1,12 +1,16 @@
// Package imagecheck validates PNG and JPEG structure without decoding the // Package imagecheck validates PNG and JPEG structure without decoding the
// raster. A full decode of a 40-megapixel image would allocate hundreds of // raster into an image. A full decode of a 40-megapixel image would allocate
// megabytes; attachment uploads must stay bounded. The parser verifies chunk // hundreds of megabytes; attachment uploads must stay bounded. For PNG the
// CRCs and the JPEG marker/scan structure, which catches truncation and // parser verifies chunk CRCs and streams the zlib image data to check exact
// corruption while using constant memory. // scanline sizes and filter types without keeping the raster in memory. The
// JPEG parser verifies marker/scan structure. Both catch truncation and
// corruption while using bounded memory.
package imagecheck package imagecheck
import ( import (
"bufio" "bufio"
"bytes"
"compress/zlib"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt" "fmt"
@@ -73,10 +77,20 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
} }
var ( var (
info Info info Info
seen = make(map[string]bool, 4) seen = make(map[string]bool, 4)
first = true first = true
hasIDAT bool hasIDAT bool
paletteReady bool
trnsSeen bool
colorType byte
bitDepth byte
paletteEntries int
idat bytes.Buffer
raster []pngPass
rasterBytes int64
maxIDAT int64 = -1
lastChunk string
) )
info.ContentType = "image/png" info.ContentType = "image/png"
@@ -107,11 +121,32 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
first = false first = false
if seen[chunkType] && (chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IEND") {
return Info{}, corruptf("png duplicate %s chunk", chunkType)
}
if chunkType == "PLTE" && hasIDAT {
return Info{}, corruptf("png PLTE chunk after IDAT")
}
if chunkType == "IDAT" && seen["IDAT"] && lastChunk != "IDAT" {
return Info{}, corruptf("png IDAT chunks must be consecutive")
}
if err := checkCriticalChunk(chunkType, seen); err != nil { if err := checkCriticalChunk(chunkType, seen); err != nil {
return Info{}, err return Info{}, err
} }
data, err := readChunkData(reader, checksum, length) var chunkSink io.Writer
if chunkType == "IDAT" {
if maxIDAT >= 0 && int64(idat.Len())+length > maxIDAT {
return Info{}, corruptf("png idat compressed data exceeds %d bytes", maxIDAT)
}
chunkSink = &idat
}
data, err := readChunkData(reader, checksum, length, chunkSink)
if err != nil { if err != nil {
return Info{}, corrupt("png chunk data", err) return Info{}, corrupt("png chunk data", err)
} }
@@ -133,6 +168,8 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
info.Width = int64(binary.BigEndian.Uint32(data[0:4])) info.Width = int64(binary.BigEndian.Uint32(data[0:4]))
info.Height = int64(binary.BigEndian.Uint32(data[4:8])) info.Height = int64(binary.BigEndian.Uint32(data[4:8]))
colorType = data[9]
bitDepth = data[8]
if info.Width <= 0 || info.Height <= 0 { if info.Width <= 0 || info.Height <= 0 {
return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height) return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height)
@@ -143,8 +180,84 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
if maxPixels > 0 && (info.Width > maxPixels || info.Height > maxPixels || info.Width*info.Height > maxPixels) { if maxPixels > 0 && (info.Width > maxPixels || info.Height > maxPixels || info.Width*info.Height > maxPixels) {
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height) return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
} }
bound, err := pngRasterLayout(info, data[8], data[9], data[10], data[11], data[12])
if err != nil {
return Info{}, err
}
raster = bound
rasterBytes = pngRasterBytes(bound)
if rasterBytes <= 1<<40 {
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
// images where the relative term vanishes.
maxIDAT = rasterBytes + rasterBytes/256 + 1<<20
}
case "IDAT": case "IDAT":
hasIDAT = true hasIDAT = true
case "PLTE":
if colorType == 0 || colorType == 4 {
return Info{}, corruptf("png PLTE is invalid for color type %d", colorType)
}
if length == 0 || length%3 != 0 || length > 3*256 {
return Info{}, corruptf("png PLTE length %d", length)
}
if length/3 > 1<<bitDepth {
return Info{}, corruptf(
"png PLTE has %d entries for bit depth %d", length/3, bitDepth,
)
}
if trnsSeen {
return Info{}, corruptf("png PLTE chunk after tRNS")
}
paletteEntries = int(length / 3)
if !hasIDAT {
paletteReady = true
}
case "tRNS":
if trnsSeen {
return Info{}, corruptf("png duplicate tRNS chunk")
}
if hasIDAT {
return Info{}, corruptf("png tRNS chunk after IDAT")
}
switch colorType {
case 0:
if length != 2 {
return Info{}, corruptf("png tRNS length %d for color type 0", length)
}
case 2:
if length != 6 {
return Info{}, corruptf("png tRNS length %d for color type 2", length)
}
case 3:
if !paletteReady {
return Info{}, corruptf("png tRNS before PLTE")
}
if length > 256 {
return Info{}, corruptf("png tRNS length %d", length)
}
if int(length) > paletteEntries {
return Info{}, corruptf(
"png tRNS length %d exceeds %d palette entries",
length, paletteEntries,
)
}
default:
return Info{}, corruptf("png tRNS invalid for color type %d", colorType)
}
trnsSeen = true
case "IEND": case "IEND":
if length != 0 { if length != 0 {
return Info{}, corruptf("png IEND length %d", length) return Info{}, corruptf("png IEND length %d", length)
@@ -154,18 +267,200 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
return Info{}, corruptf("png has no IDAT chunk") return Info{}, corruptf("png has no IDAT chunk")
} }
if colorType == 3 && !paletteReady {
return Info{}, corruptf("png palette image has no PLTE before IDAT")
}
// The chunk walker proves structure, but a stream whose bytes
// merely look like a chunk layout (valid length/type/CRC) may
// still not be a PNG raster: the zlib payload must inflate to
// exactly the IHDR-declared scanlines with valid filter bytes.
if err := validateRaster(idat.Bytes(), raster); err != nil {
return Info{}, err
}
if _, err := io.Copy(io.Discard, reader); err != nil { if _, err := io.Copy(io.Discard, reader); err != nil {
return Info{}, corrupt("png trailing data", err) return Info{}, corrupt("png trailing data", err)
} }
return info, nil return info, nil
} }
lastChunk = chunkType
}
}
// pngPass is one consecutive block of scanlines in the inflated image stream.
// Non-interlaced PNGs have a single pass; Adam7 has up to seven.
type pngPass struct {
rowBytes int64
rows int64
}
type pngPassSpec struct {
x0, y0 int64
dx, dy int64
}
var adam7Passes = []pngPassSpec{
{x0: 0, y0: 0, dx: 8, dy: 8},
{x0: 4, y0: 0, dx: 8, dy: 8},
{x0: 0, y0: 4, dx: 4, dy: 8},
{x0: 2, y0: 0, dx: 4, dy: 4},
{x0: 0, y0: 2, dx: 2, dy: 4},
{x0: 1, y0: 0, dx: 2, dy: 2},
{x0: 0, y0: 1, dx: 1, dy: 2},
}
// pngRasterLayout returns the exact inflated size and row layout for the
// IHDR. The Adam7 layout matters: a single non-interlaced formula either
// rejects valid interlaced images or accepts oversized streams.
func pngRasterLayout(
info Info,
bitDepth, colorType, compression, filter, interlace byte,
) ([]pngPass, error) {
if compression != 0 || filter != 0 {
return nil, corruptf(
"png compression/filter method %d/%d", compression, filter,
)
}
var bitsPerPixel int64
switch colorType {
case 0: // grayscale
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16 {
return nil, corruptf("png invalid bit depth %d for color type 0", bitDepth)
}
bitsPerPixel = int64(bitDepth)
case 2: // truecolor
if bitDepth != 8 && bitDepth != 16 {
return nil, corruptf("png invalid bit depth %d for color type 2", bitDepth)
}
bitsPerPixel = 3 * int64(bitDepth)
case 3: // palette
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 {
return nil, corruptf("png invalid bit depth %d for color type 3", bitDepth)
}
bitsPerPixel = int64(bitDepth)
case 4: // grayscale + alpha
if bitDepth != 8 && bitDepth != 16 {
return nil, corruptf("png invalid bit depth %d for color type 4", bitDepth)
}
bitsPerPixel = 2 * int64(bitDepth)
case 6: // RGBA
if bitDepth != 8 && bitDepth != 16 {
return nil, corruptf("png invalid bit depth %d for color type 6", bitDepth)
}
bitsPerPixel = 4 * int64(bitDepth)
default:
return nil, corruptf("png invalid color type %d", colorType)
}
specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}}
switch interlace {
case 0:
case 1:
specs = adam7Passes
default:
return nil, corruptf("png invalid interlace method %d", interlace)
}
passes := make([]pngPass, 0, len(specs))
for _, spec := range specs {
if info.Width <= spec.x0 || info.Height <= spec.y0 {
continue
}
width := (info.Width - spec.x0 + spec.dx - 1) / spec.dx
rows := (info.Height - spec.y0 + spec.dy - 1) / spec.dy
rowBytes := (width*bitsPerPixel + 7) / 8
// Keep the total overflow-safe. Valid PNGs are additionally bounded
// by the pixel limit checked by the caller.
if rowBytes+1 > (1<<62)/rows {
return nil, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
}
passes = append(passes, pngPass{rowBytes: rowBytes, rows: rows})
}
return passes, nil
}
func pngRasterBytes(passes []pngPass) int64 {
var total int64
for _, pass := range passes {
row := (pass.rowBytes + 1) * pass.rows
if total > (1<<62)-row {
return 1<<62 - 1
}
total += row
}
return total
}
// validateRaster streams the inflated image data, checking every scanline
// filter byte and requiring exactly the IHDR-declared number of rows. It
// catches zlib streams that decompress cleanly but do not describe a valid
// raster (empty payloads, bogus filter bytes) and rejects extra data as a
// decompression bomb.
func validateRaster(compressed []byte, passes []pngPass) error {
source := bytes.NewReader(compressed)
reader, err := zlib.NewReader(source)
if err != nil {
return corrupt("png idat zlib header", err)
}
for _, pass := range passes {
for range pass.rows {
var filter [1]byte
if _, err := io.ReadFull(reader, filter[:]); err != nil {
return corrupt("png scanline filter", err)
}
if filter[0] > 4 {
return corruptf("png invalid scanline filter %d", filter[0])
}
if _, err := io.CopyN(io.Discard, reader, pass.rowBytes); err != nil {
return corrupt("png scanline data", err)
}
}
}
var extra [1]byte
switch _, err := io.ReadFull(reader, extra[:]); {
case errors.Is(err, io.EOF):
// A clean zlib EOF also verifies the Adler-32 trailer. bytes.Reader
// satisfies io.ByteReader, so the inflater consumes exactly the zlib
// stream; anything left is data after the stream, which PNG forbids.
if source.Len() != 0 {
return corruptf("png idat has %d trailing bytes", source.Len())
}
return nil
case err == nil:
return fmt.Errorf("%w: png raster exceeds declared dimensions", ErrTooLarge)
default:
return corrupt("png idat zlib trailer", err)
} }
} }
func checkCriticalChunk(chunkType string, seen map[string]bool) error { func checkCriticalChunk(chunkType string, seen map[string]bool) error {
if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" { if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" {
seen[chunkType] = true seen[chunkType] = true
return nil return nil
} }
@@ -176,7 +471,7 @@ func checkCriticalChunk(chunkType string, seen map[string]bool) error {
return nil return nil
} }
func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte, error) { func readChunkData(reader io.Reader, checksum io.Writer, length int64, sink io.Writer) ([]byte, error) {
if length <= 64<<10 { if length <= 64<<10 {
data := make([]byte, length) data := make([]byte, length)
if _, err := io.ReadFull(reader, data); err != nil { if _, err := io.ReadFull(reader, data); err != nil {
@@ -184,11 +479,19 @@ func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte,
} }
_, _ = checksum.Write(data) _, _ = checksum.Write(data)
if sink != nil {
_, _ = sink.Write(data)
}
return data, nil return data, nil
} }
if _, err := io.CopyN(checksum, reader, length); err != nil { destination := checksum
if sink != nil {
destination = io.MultiWriter(checksum, sink)
}
if _, err := io.CopyN(destination, reader, length); err != nil {
return nil, err return nil, err
} }
+373
View File
@@ -2,6 +2,9 @@ package imagecheck_test
import ( import (
"bytes" "bytes"
"compress/zlib"
"encoding/binary"
"hash/crc32"
"image" "image"
"image/color" "image/color"
"image/jpeg" "image/jpeg"
@@ -45,6 +48,30 @@ func encodeJPEG(t *testing.T, width, height int) []byte {
return buffer.Bytes() return buffer.Bytes()
} }
func pngChunk(ctype string, payload []byte) []byte {
out := make([]byte, 12+len(payload))
binary.BigEndian.PutUint32(out[0:4], uint32(len(payload)))
copy(out[4:8], ctype)
copy(out[8:], payload)
checksum := crc32.NewIEEE()
_, _ = checksum.Write(out[4 : 8+len(payload)])
binary.BigEndian.PutUint32(out[8+len(payload):], checksum.Sum32())
return out
}
func pngFile(chunks ...[]byte) []byte {
data := []byte(pngSignatureForTest)
for _, chunk := range chunks {
data = append(data, chunk...)
}
return data
}
const pngSignatureForTest = "\x89PNG\r\n\x1a\n"
func TestValidatePNG(t *testing.T) { func TestValidatePNG(t *testing.T) {
info, err := imagecheck.Validate(bytes.NewReader(encodePNG(t, 32, 20)), 40_000_000) info, err := imagecheck.Validate(bytes.NewReader(encodePNG(t, 32, 20)), 40_000_000)
require.NoError(t, err) require.NoError(t, err)
@@ -85,6 +112,352 @@ func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
require.ErrorIs(t, err, imagecheck.ErrCorrupt) require.ErrorIs(t, err, imagecheck.ErrCorrupt)
} }
// Builds a structurally valid PNG (signature, well-formed IHDR/IDAT/IEND,
// correct CRCs) whose IDAT payload is not a zlib stream at all. Merely a
// stream-like structure must not make the upload pass: it has to inflate.
func TestValidateRejectsPNGIDATNotAZlibStream(t *testing.T) {
ihdr := make([]byte, 13)
binary.BigEndian.PutUint32(ihdr[0:4], 64) // width
binary.BigEndian.PutUint32(ihdr[4:8], 32) // height
ihdr[8] = 8 // bit depth
ihdr[9] = 6 // color type RGBA
data := pngFile(
pngChunk("IHDR", ihdr),
pngChunk("IDAT", []byte("this is not a zlib stream, but the CRC is right")),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func craftedPNG(t *testing.T, width, height int, interlace byte, raster []byte) []byte {
t.Helper()
return craftedPNGType(t, width, height, 6, interlace, raster)
}
func craftedPNGType(t *testing.T, width, height int, colorType, interlace byte, raster []byte) []byte {
t.Helper()
return craftedPNGDepth(t, width, height, 8, colorType, interlace, raster)
}
func craftedPNGDepth(t *testing.T, width, height int, bitDepth, colorType, interlace byte, raster []byte) []byte {
t.Helper()
return pngFile(
pngChunk("IHDR", pngIHDR(width, height, bitDepth, colorType, interlace)),
pngChunk("IDAT", zlibBytes(t, raster)),
pngChunk("IEND", nil),
)
}
func pngIHDR(width, height int, bitDepth, colorType, interlace byte) []byte {
ihdr := make([]byte, 13)
binary.BigEndian.PutUint32(ihdr[0:4], uint32(width))
binary.BigEndian.PutUint32(ihdr[4:8], uint32(height))
ihdr[8] = bitDepth
ihdr[9] = colorType
ihdr[12] = interlace
return ihdr
}
func zlibBytes(t *testing.T, raster []byte) []byte {
t.Helper()
var compressed bytes.Buffer
writer := zlib.NewWriter(&compressed)
_, err := writer.Write(raster)
require.NoError(t, err)
require.NoError(t, writer.Close())
return compressed.Bytes()
}
func TestValidateRejectsPNGEmptyRaster(t *testing.T) {
data := craftedPNG(t, 2, 2, 0, nil)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGInvalidScanlineFilter(t *testing.T) {
raster := []byte{5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
data := craftedPNG(t, 2, 2, 0, raster)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGPaletteWithoutPLTE(t *testing.T) {
raster := []byte{0, 0, 0, 0, 0, 0} // two rows of two 8-bit palette indexes
data := craftedPNGType(t, 2, 2, 3, 0, raster)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateAcceptsPalettePNG(t *testing.T) {
palette := color.Palette{color.RGBA{R: 255, A: 255}, color.RGBA{G: 255, A: 255}, color.RGBA{B: 255, A: 255}}
source := image.NewPaletted(image.Rect(0, 0, 13, 5), palette)
for x := range 13 {
for y := range 5 {
source.SetColorIndex(x, y, uint8((x+y)%len(palette)))
}
}
var buffer bytes.Buffer
require.NoError(t, png.Encode(&buffer, source))
info, err := imagecheck.Validate(bytes.NewReader(buffer.Bytes()), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(13), info.Width)
require.Equal(t, int64(5), info.Height)
}
func TestValidateRejectsPNGInvalidColorDepthCombination(t *testing.T) {
data := craftedPNGDepth(t, 1, 1, 1, 6, 0, []byte{0, 0, 0})
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGDuplicateIHDR(t *testing.T) {
ihdr := pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0))
data := pngFile(
ihdr,
ihdr,
pngChunk("IDAT", zlibBytes(t, []byte{0, 0, 0, 0, 0})),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGDuplicatePLTE(t *testing.T) {
plte := pngChunk("PLTE", []byte{255, 0, 0})
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
plte,
plte,
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGNonConsecutiveIDAT(t *testing.T) {
compressed := zlibBytes(t, []byte{0, 0, 0, 0, 0})
middle := len(compressed) / 2
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
pngChunk("IDAT", compressed[:middle]),
pngChunk("tEXt", []byte("k\x00v")),
pngChunk("IDAT", compressed[middle:]),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsPNGTrailingIDATData(t *testing.T) {
idat := append(zlibBytes(t, []byte{0, 0, 0, 0, 0}), []byte("junk")...)
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
pngChunk("IDAT", idat),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateAcceptsSplitIDAT(t *testing.T) {
compressed := zlibBytes(t, []byte{0, 0, 0, 0, 0})
middle := len(compressed) / 2
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
pngChunk("IDAT", compressed[:middle]),
pngChunk("IDAT", compressed[middle:]),
pngChunk("IEND", nil),
)
info, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(1), info.Width)
}
func TestValidateAcceptsStandardEncodings(t *testing.T) {
bounds := image.Rect(0, 0, 7, 5)
images := []image.Image{
image.NewGray(bounds),
image.NewGray16(bounds),
image.NewRGBA(bounds),
image.NewNRGBA(bounds),
image.NewNRGBA64(bounds),
}
for _, source := range images {
var buffer bytes.Buffer
require.NoError(t, png.Encode(&buffer, source))
info, err := imagecheck.Validate(bytes.NewReader(buffer.Bytes()), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(7), info.Width)
require.Equal(t, int64(5), info.Height)
}
}
func TestValidateRejectsPNGPLTEEntriesExceedBitDepth(t *testing.T) {
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0, 0, 0, 255}),
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
pngChunk("IEND", nil),
)
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
}
func TestValidateRejectsInvalidTRNS(t *testing.T) {
rgb := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30}))
gray := pngChunk("IDAT", zlibBytes(t, []byte{0, 10}))
rgba := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30, 255}))
paletted := pngChunk("IDAT", zlibBytes(t, []byte{0, 0}))
cases := map[string][]byte{
"tRNS on RGBA": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
pngChunk("tRNS", []byte{0}),
rgba,
pngChunk("IEND", nil),
),
"RGB length": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", []byte{0}),
rgb,
pngChunk("IEND", nil),
),
"gray length": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
pngChunk("tRNS", []byte{0}),
gray,
pngChunk("IEND", nil),
),
"palette before PLTE": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
pngChunk("tRNS", []byte{0}),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
paletted,
pngChunk("IEND", nil),
),
"palette tRNS longer than PLTE": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0}),
pngChunk("tRNS", []byte{0, 0}),
paletted,
pngChunk("IEND", nil),
),
"duplicate tRNS": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", make([]byte, 6)),
pngChunk("tRNS", make([]byte, 6)),
rgb,
pngChunk("IEND", nil),
),
"tRNS after IDAT": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
rgb,
pngChunk("tRNS", make([]byte, 6)),
pngChunk("IEND", nil),
),
}
for name, data := range cases {
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt, name)
}
}
func TestValidateAcceptsValidTRNS(t *testing.T) {
cases := map[string][]byte{
"RGB": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", make([]byte, 6)),
pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30})),
pngChunk("IEND", nil),
),
"gray": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
pngChunk("tRNS", make([]byte, 2)),
pngChunk("IDAT", zlibBytes(t, []byte{0, 10})),
pngChunk("IEND", nil),
),
"palette": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
pngChunk("tRNS", []byte{128}),
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
pngChunk("IEND", nil),
),
}
for name, data := range cases {
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.NoError(t, err, name)
}
}
// A valid Adam7 stream for a tall, narrow image exceeds the old
// (rowBytes+1)*(height+8) guess; the exact pass layout must accept it.
func TestValidateAcceptsAdam7PNG(t *testing.T) {
const width, height = 2, 256
var raster bytes.Buffer
passes := [][4]int{
{0, 0, 8, 8},
{4, 0, 8, 8},
{0, 4, 4, 8},
{2, 0, 4, 4},
{0, 2, 2, 4},
{1, 0, 2, 2},
{0, 1, 1, 2},
}
for _, pass := range passes {
x0, y0, dx, dy := pass[0], pass[1], pass[2], pass[3]
if width <= x0 || height <= y0 {
continue
}
for y := y0; y < height; y += dy {
raster.WriteByte(0) // filter: none
for x := x0; x < width; x += dx {
raster.Write([]byte{byte(x), byte(y), 128, 255})
}
}
}
data := craftedPNG(t, width, height, 1, raster.Bytes())
info, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.NoError(t, err)
require.Equal(t, int64(width), info.Width)
require.Equal(t, int64(height), info.Height)
}
func TestValidateRejectsTruncatedJPEG(t *testing.T) { func TestValidateRejectsTruncatedJPEG(t *testing.T) {
data := encodeJPEG(t, 64, 64) data := encodeJPEG(t, 64, 64)
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000) _, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000)
@@ -142,9 +142,9 @@ ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
(status = 'ready' AND error_code IS NULL) OR (status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR (status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending' status = 'pending'
); ) NOT VALID;
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check; ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK ( ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
status IN ('pending', 'ready', 'failed') status IN ('pending', 'ready', 'failed')
); ) NOT VALID;
@@ -578,6 +578,23 @@ func (r *PipelineRepository) ClaimJob(
switch { switch {
case job.PipelineVersion < attachment.PipelineVersion: case job.PipelineVersion < attachment.PipelineVersion:
// A queued job left behind by an older version (for example a
// replay accepted before the newer version committed) can never
// make progress. Retire it instead of acknowledging and
// republishing it through reconciliation forever.
if job.Status == domain.JobQueued {
if _, err := tx.Exec(ctx, `
UPDATE attachment_jobs
SET status = 'superseded', updated_at = now(), completed_at = now()
WHERE job_id = $1 AND status = 'queued'`, job.ID); err != nil {
return fmt.Errorf("supersede version-stale job: %w", mapError(err))
}
if err := insertEventTx(ctx, tx, job.ID, domain.EventSuperseded, job.Attempt, ""); err != nil {
return err
}
}
result.Outcome = domain.ClaimVersionStale result.Outcome = domain.ClaimVersionStale
return nil return nil
@@ -998,7 +1015,15 @@ func failJobTx(
return fmt.Errorf("mark job failed: %w", mapError(err)) return fmt.Errorf("mark job failed: %w", mapError(err))
} }
if job.PipelineVersion == attachment.PipelineVersion { // A failed job settles the attachment when its version is the serving one,
// or when it is a newer version attempted before any version was
// published (reprocess from queued/processing/failed). A newer version
// failing while an older ready version is serving must not disturb the
// published version: it stays ready and downloadable.
settlesAttachment := job.PipelineVersion == attachment.PipelineVersion ||
(job.PipelineVersion > attachment.PipelineVersion && attachment.Status != domain.AttachmentReady)
if settlesAttachment {
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE attachments UPDATE attachments
SET status = 'failed', SET status = 'failed',
@@ -1338,23 +1363,71 @@ func (r *PipelineRepository) Reprocess(
return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict) return fmt.Errorf("%w: target pipeline version must be newer", domain.ErrConflict)
} }
sourceKey := attachment.ObjectKey if attachment.Status == domain.AttachmentPending {
return fmt.Errorf("%w: attachment upload is not complete", domain.ErrConflict)
}
// The verified upload lives in staging until the first pipeline
// publishes the final original. A queued/processing/failed attachment
// must reprocess from staging: object_key points at a final original
// that may not exist yet (worker stopped before the first run), and
// choosing it would supersede v1 and leave the attachment queued with
// no jobs after v2 fails with source_missing.
sourceKey := attachment.StagingKey
if attachment.Status == domain.AttachmentReady {
// Ready means the final original was published; staging may have
// passed its retention window already.
sourceKey = attachment.ObjectKey
}
if sourceKey == "" { if sourceKey == "" {
sourceKey = attachment.StagingKey sourceKey = attachment.ObjectKey
} }
if sourceKey == "" { if sourceKey == "" {
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict) return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
} }
_, err = tx.Exec(ctx, ` rows, err := tx.Query(ctx, `
UPDATE attachment_jobs UPDATE attachment_jobs
SET status = 'superseded', updated_at = now(), completed_at = now() SET status = 'superseded', updated_at = now(), completed_at = now()
WHERE attachment_id = $1 AND status IN ('queued', 'processing') WHERE attachment_id = $1 AND status IN ('queued', 'processing')
AND pipeline_version < $2`, attachmentID, targetVersion) AND pipeline_version < $2
RETURNING job_id, attempt`, attachmentID, targetVersion)
if err != nil { if err != nil {
return fmt.Errorf("supersede old jobs: %w", mapError(err)) return fmt.Errorf("supersede old jobs: %w", mapError(err))
} }
type supersededJob struct {
id uuid.UUID
attempt int
}
superseded := make([]supersededJob, 0, 2)
for rows.Next() {
var old supersededJob
if err := rows.Scan(&old.id, &old.attempt); err != nil {
rows.Close()
return fmt.Errorf("scan superseded job: %w", mapError(err))
}
superseded = append(superseded, old)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("list superseded jobs: %w", mapError(err))
}
rows.Close()
for _, old := range superseded {
if err := insertEventTx(ctx, tx, old.id, domain.EventSuperseded, old.attempt, ""); err != nil {
return err
}
}
if attachment.Status != domain.AttachmentReady { if attachment.Status != domain.AttachmentReady {
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE attachments UPDATE attachments
@@ -1432,6 +1505,24 @@ func (r *PipelineRepository) ReplayJob(
return fmt.Errorf("%w: job is superseded by a newer pipeline version", domain.ErrConflict) return fmt.Errorf("%w: job is superseded by a newer pipeline version", domain.ErrConflict)
} }
// A newer version may still be unpublished (attachment.pipeline_version
// changes only when it commits), so compare against job rows too. An
// older replay must not compete with a newer job for the same staging
// source or return the attachment to an older state.
var newerJob bool
if err := tx.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND pipeline_version > $2
)`, job.AttachmentID, job.PipelineVersion).Scan(&newerJob); err != nil {
return fmt.Errorf("check newer pipeline version: %w", mapError(err))
}
if newerJob {
return fmt.Errorf("%w: a newer pipeline version already has a job", domain.ErrConflict)
}
nextAttempt := job.Attempt + 1 nextAttempt := job.Attempt + 1
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
@@ -1451,15 +1542,25 @@ func (r *PipelineRepository) ReplayJob(
return fmt.Errorf("replay job: %w", mapError(err)) return fmt.Errorf("replay job: %w", mapError(err))
} }
if job.PipelineVersion == attachment.PipelineVersion { // Mirror failJobTx: a replay of a newer unpublished version returns
// the attachment to queued so the API does not keep showing a stale
// terminal state while the replayed job waits. A published ready
// version is never disturbed by a newer version's replay.
switch {
case job.PipelineVersion == attachment.PipelineVersion:
_, err = tx.Exec(ctx, ` _, err = tx.Exec(ctx, `
UPDATE attachments UPDATE attachments
SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now() SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now()
WHERE id = $1 AND pipeline_version = $2`, WHERE id = $1 AND pipeline_version = $2`,
attachment.ID, job.PipelineVersion) attachment.ID, job.PipelineVersion)
if err != nil { case job.PipelineVersion > attachment.PipelineVersion && attachment.Status != domain.AttachmentReady:
return fmt.Errorf("replay attachment: %w", mapError(err)) _, err = tx.Exec(ctx, `
} UPDATE attachments
SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'`, attachment.ID)
}
if err != nil {
return fmt.Errorf("replay attachment: %w", mapError(err))
} }
if err := insertEventTx(ctx, tx, job.ID, domain.EventReplayed, nextAttempt, ""); err != nil { if err := insertEventTx(ctx, tx, job.ID, domain.EventReplayed, nextAttempt, ""); err != nil {
@@ -158,6 +158,352 @@ func (s *PipelineSuite) TestAdmissionCountsPendingPresignAndIsAtomic() {
s.Require().ErrorIs(err, domain.ErrRateLimited) s.Require().ErrorIs(err, domain.ErrRateLimited)
} }
// A queued upload whose worker never ran still has its verified bytes only in
// staging. Reprocessing it must use staging as the source; pointing at the
// not-yet-written final original left the attachment queued forever after the
// v1 job was superseded (v2 then failed with source_missing).
func (s *PipelineSuite) TestReprocessQueuedUsesStagingSource() {
alice := s.createUser("alice")
bob := s.createUser("bob")
chat := s.createChat(alice, bob)
draft, job := s.attachmentDraft(chat, alice, 1)
repo := s.store.Pipeline()
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
s.Equal(2, created.PipelineVersion)
s.Equal(draft.StagingKey, created.SourceKey)
}
// Once a pipeline has published the final original, the staging copy may be
// past its retention window; a reprocess of a ready attachment must source
// from the final object that actually exists.
func (s *PipelineSuite) TestReprocessReadyUsesObjectSource() {
alice := s.createUser("alice")
chat := s.createChat(alice)
draft, job := s.attachmentDraft(chat, alice, 1)
repo := s.store.Pipeline()
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
message := domain.NewJobMessage(job)
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
s.Require().NoError(err)
s.True(ok)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
s.Equal(2, created.PipelineVersion)
s.Equal(draft.ObjectKey, created.SourceKey)
}
// A reprocess failure before any version was published must settle the
// attachment as failed instead of leaving it queued with no active jobs.
func (s *PipelineSuite) TestReprocessFailureSettlesUnpublishedAttachment() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
s.Require().NoError(err)
s.True(failed)
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentFailed, current.Status)
s.Require().NotNil(current.ErrorCode)
s.Equal("invalid_image", *current.ErrorCode)
}
// A reprocess failure while an older ready version is serving must keep that
// version ready and downloadable; only the new job fails.
func (s *PipelineSuite) TestReprocessFailureKeepsReadyServingVersion() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
s.Require().NoError(err)
s.True(ok)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
s.Require().NoError(err)
s.True(failed)
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, current.Status)
s.Equal(1, current.PipelineVersion)
s.Nil(current.ErrorCode)
}
// Replaying a failed newer version must clear the stale terminal projection
// for an attachment that never published any version.
func (s *PipelineSuite) TestReplayNewerFailedVersionRequeuesUnpublishedAttachment() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
s.Require().NoError(err)
s.True(failed)
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentFailed, current.Status)
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 2)
s.Require().NoError(err)
s.Equal(2, replayed.Attempt)
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentQueued, current.Status)
s.Nil(current.ErrorCode)
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(replayed), "lease-3", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("c", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), replayed.ID, replayed.Attempt, "lease-3", variants)
s.Require().NoError(err)
s.True(ok)
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, current.Status)
s.Equal(2, current.PipelineVersion)
}
// Replaying a failed newer version must not disturb a published ready
// serving version; only the new job returns to queued.
func (s *PipelineSuite) TestReplayNewerFailedVersionKeepsReadyServingVersion() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
s.Require().NoError(err)
s.True(ok)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
s.Require().NoError(err)
s.True(failed)
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 1)
s.Require().NoError(err)
s.Equal(2, replayed.Attempt)
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
s.Require().NoError(err)
s.Equal(domain.AttachmentReady, current.Status)
s.Equal(1, current.PipelineVersion)
s.Nil(current.ErrorCode)
}
// Replaying an older failed version is refused while a newer job exists,
// even before that newer version becomes the published serving version.
func (s *PipelineSuite) TestReplayOlderFailedVersionRefusedWhenNewerJobExists() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
failed, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease-1", "invalid_image")
s.Require().NoError(err)
s.True(failed)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
_, err = repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
_, err = repo.ReplayJob(s.T().Context(), job.ID, 1)
s.Require().ErrorIs(err, domain.ErrConflict)
var v1Status string
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&v1Status))
s.Equal(string(domain.JobFailed), v1Status)
}
// A queued job for an older version is retired on claim instead of being
// acknowledged and republished by reconciliation forever.
func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() {
alice := s.createUser("alice")
chat := s.createChat(alice)
repo := s.store.Pipeline()
draft, job := s.attachmentDraft(chat, alice, 1)
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
s.Require().NoError(err)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimAcquired, claim.Outcome)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("d", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), reprocess.ID, 1, "lease-2", variants)
s.Require().NoError(err)
s.True(ok)
// Simulate a legacy/racing replay that left the old version queued.
_, err = s.pool.Exec(s.T().Context(), `
UPDATE attachment_jobs
SET status = 'queued', attempt = 1, last_error_code = NULL
WHERE job_id = $1`, job.ID)
s.Require().NoError(err)
stale, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-3", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimVersionStale, stale.Outcome)
var status string
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status))
s.Equal(string(domain.JobSuperseded), status)
var supersededEvents int
s.Require().NoError(s.pool.QueryRow(s.T().Context(), `
SELECT count(*) FROM attachment_job_events
WHERE job_id = $1 AND event = $2`,
job.ID, string(domain.EventSuperseded)).Scan(&supersededEvents))
s.Equal(2, supersededEvents)
}
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() { func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
alice := s.createUser("alice") alice := s.createUser("alice")
chat := s.createChat(alice) chat := s.createChat(alice)
+108
View File
@@ -5,10 +5,12 @@ Run against a live stand:
python3 student-tests/attachments_negative.py --base-url http://localhost:8080 python3 student-tests/attachments_negative.py --base-url http://localhost:8080
""" """
import hashlib import hashlib
import struct
import sys import sys
import urllib.error import urllib.error
import urllib.request import urllib.request
import uuid import uuid
import zlib
from pathlib import Path from pathlib import Path
from urllib.parse import quote from urllib.parse import quote
@@ -24,6 +26,31 @@ def upload(client, actor, chat, content, filename='sample.png', content_type='im
return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type}) return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type})
def png_chunk(ctype, payload):
crc = zlib.crc32(ctype + payload) & 0xffffffff
return struct.pack('>I', len(payload)) + ctype + payload + struct.pack('>I', crc)
def crafted_png(width, height, interlace, raster, bit_depth=8, color_type=6):
"""PNG with correct chunk lengths and CRCs around arbitrary IDAT bytes."""
return crafted_png_extra(
width, height, raster, bit_depth=bit_depth, color_type=color_type,
interlace=interlace,
)
def crafted_png_extra(width, height, raster, pre_idat=(), bit_depth=8, color_type=6, interlace=0):
"""PNG whose IDAT is preceded by caller-supplied chunks (PLTE/tRNS/...)."""
ihdr = struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, interlace)
return (
b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', ihdr)
+ b''.join(pre_idat)
+ png_chunk(b'IDAT', zlib.compress(raster))
+ png_chunk(b'IEND', b'')
)
def main(): def main():
args = arguments('Attachment negative scenarios (lab4)') args = arguments('Attachment negative scenarios (lab4)')
client = Client(args.base_url, args.ca_file) client = Client(args.base_url, args.ca_file)
@@ -49,6 +76,87 @@ def main():
upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=415) upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=415)
print('MIME spoof (PNG declared as JPEG): 415') print('MIME spoof (PNG declared as JPEG): 415')
# Structurally valid PNG (chunk layout, lengths, CRCs all correct) whose
# IDAT payload is not a zlib stream at all. Structure-checking alone must
# not accept it: the stream has to inflate. Regression for a review
# finding that used to produce 202 queued and then failed/invalid_image
# in the worker.
upload(
client, alice, chat,
crafted_png(64, 32, 0, b'this is not a zlib stream'),
expected=415,
)
print('structurally valid PNG with non-zlib IDAT: 415')
# Correct zlib stream that is not a valid PNG raster: an empty payload
# and a scanline with an undefined filter byte must both be 415, not 202.
upload(client, alice, chat, crafted_png(2, 2, 0, b''), expected=415)
print('valid zlib, empty PNG raster: 415')
invalid_filter = b'\x05' + b'\x00' * 8 + b'\x00' + b'\x00' * 8
upload(client, alice, chat, crafted_png(2, 2, 0, invalid_filter), expected=415)
print('valid zlib, invalid PNG scanline filter: 415')
# RGBA forbids bit depth 1; every chunk CRC is correct.
upload(client, alice, chat, crafted_png(1, 1, 0, b'\x00', bit_depth=1), expected=415)
print('invalid PNG color type/bit depth pair: 415')
# Duplicate IHDR is forbidden even with correct CRCs.
ihdr = png_chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 6, 0, 0, 0))
duplicate_header = (
b'\x89PNG\r\n\x1a\n'
+ ihdr + ihdr
+ png_chunk(b'IDAT', zlib.compress(b'\x00' + b'\x00' * 4))
+ png_chunk(b'IEND', b'')
)
upload(client, alice, chat, duplicate_header, expected=415)
print('duplicate PNG IHDR: 415')
# Bytes after the zlib stream inside IDAT are not part of a valid raster.
trailing = (
b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 6, 0, 0, 0))
+ png_chunk(b'IDAT', zlib.compress(b'\x00' + b'\x00' * 4) + b'junk')
+ png_chunk(b'IEND', b'')
)
upload(client, alice, chat, trailing, expected=415)
print('trailing bytes after PNG zlib stream: 415')
# tRNS is forbidden for alpha color types and has fixed lengths otherwise.
rgba_trns = crafted_png_extra(
1, 1, b'\x00' + b'\x00' * 4,
pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=6,
)
upload(client, alice, chat, rgba_trns, expected=415)
print('tRNS on RGBA PNG: 415')
rgb_trns = crafted_png_extra(
1, 1, b'\x00' + b'\x00' * 3,
pre_idat=(png_chunk(b'tRNS', b'\x00'),), color_type=2,
)
upload(client, alice, chat, rgb_trns, expected=415)
print('short tRNS on RGB PNG: 415')
# A 1-bit palette cannot address three entries.
palette_overflow = crafted_png_extra(
1, 1, b'\x00\x00',
pre_idat=(png_chunk(b'PLTE', bytes((255, 0, 0, 0, 255, 0, 0, 0, 255))),),
bit_depth=1, color_type=3,
)
upload(client, alice, chat, palette_overflow, expected=415)
print('PLTE entries exceed palette bit depth: 415')
# Palette transparency cannot describe more entries than PLTE provides.
palette_trns = crafted_png_extra(
1, 1, b'\x00\x00',
pre_idat=(
png_chunk(b'PLTE', bytes((255, 0, 0))),
png_chunk(b'tRNS', b'\x00\x00'),
),
bit_depth=8, color_type=3,
)
upload(client, alice, chat, palette_trns, expected=415)
print('palette tRNS exceeds PLTE entries: 415')
# Dangerous display names. # Dangerous display names.
for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'): for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'):
upload(client, alice, chat, fixture, filename=name, expected=400) upload(client, alice, chat, fixture, filename=name, expected=400)
+47 -1
View File
@@ -12,7 +12,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client, Failure, arguments, check, run # noqa: E402 from client import Client, Failure, arguments, check, run # noqa: E402
from tests_helpers import ROOT, compose, psql # noqa: E402 from tests_helpers import ROOT, compose, jobctl, psql # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png' FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
@@ -97,6 +97,52 @@ def main():
check(body['bytes'] == content, 'original lost across restart') check(body['bytes'] == content, 'original lost across restart')
print('stack restart: ready attachment and original preserved') print('stack restart: ready attachment and original preserved')
# 4. Reprocess of a queued upload while the worker is down. The final
# original has never been written, so pipeline 2 must source from staging;
# pointing at the not-yet-existing final original superseded v1 and left
# the attachment queued forever with v2 failed (source_missing).
compose('stop', 'worker')
try:
pinned, _ = client.attachment(alice, chat)
check(pinned['status'] == 'queued', 'reprocess fixture must be queued')
result = jobctl('reprocess', '-attachment', pinned['id'], '-pipeline', '2')
check('SourceKey' in result.stdout, 'reprocess did not return the created job')
queued2 = client.call('GET', '/api/v1/attachments/' + pinned['id'], actor=alice, schema='Attachment')['json']
check(queued2['status'] == 'queued', 'reprocessed upload is not queued')
check(psql("select count(*) from attachment_job_events e join attachment_jobs j on j.job_id=e.job_id where j.attachment_id='%s' and j.pipeline_version=1 and e.event='superseded'" % pinned['id']) == '1',
'reprocess did not record the v1 superseded event')
print('worker down: reprocess pipeline 2 accepted, v1 audit event recorded, upload still queued')
finally:
compose('up', '-d', '--no-deps', 'worker', check=False)
ready2 = client.wait_ready(alice, pinned, wait_seconds=90)
check(psql("select pipeline_version from attachments where id='%s'" % pinned['id']) == '2',
'serving pipeline version is not 2 after reprocess')
check(psql("select status from attachment_jobs where attachment_id='%s' order by pipeline_version" % pinned['id']) == 'superseded\nready',
'old job not superseded or new job not ready')
print('worker up: reprocessed upload reached ready at pipeline 2, v1 superseded')
# 5. A pipeline version the worker cannot execute must be refused by the
# operator CLI before any state change; the accepted v1 upload keeps its
# job and finishes normally instead of being superseded into queued.
compose('stop', 'worker')
try:
preserved, _ = client.attachment(alice, chat)
check(preserved['status'] == 'queued', 'unsupported-pipeline fixture must be queued')
refused = jobctl('reprocess', '-attachment', preserved['id'], '-pipeline', '3', check=False)
check(refused.returncode != 0 and 'unsupported pipeline version 3' in refused.stderr,
'unsupported pipeline version was not rejected')
check(psql("select status from attachment_jobs where attachment_id='%s' and pipeline_version=1" % preserved['id']) == 'queued',
'v1 job changed by rejected reprocess')
print('worker down: reprocess pipeline 3 refused, v1 job untouched')
finally:
compose('up', '-d', '--no-deps', 'worker', check=False)
client.wait_ready(alice, preserved, wait_seconds=90)
check(psql("select pipeline_version from attachments where id='%s'" % preserved['id']) == '1',
'rejected reprocess changed serving version')
print('worker up: preserved upload reached ready at pipeline 1')
print('PASS: lab5 async worker/broker durability') print('PASS: lab5 async worker/broker durability')
+64
View File
@@ -6,6 +6,7 @@ FAULTS_ENABLED=1 and targeted failpoints, then restores the normal services.
python3 student-tests/lab5_faults.py --base-url http://localhost:8080 python3 student-tests/lab5_faults.py --base-url http://localhost:8080
""" """
import json
import subprocess import subprocess
import sys import sys
import time import time
@@ -232,6 +233,67 @@ def scenario_lease_takeover(client, alice, chat):
reset_relay() reset_relay()
def scenario_replay_reprocessed_version(client, alice, chat):
compose('stop', 'worker')
attached, _ = client.attachment(alice, chat)
reprocessed = json.loads(jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2').stdout)
jid = reprocessed['ID']
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid, FAULT_WORKER_FAIL='permanent')
deadline = time.monotonic() + 40
last = ''
while time.monotonic() < deadline:
job_status = psql("select status from attachment_jobs where job_id='%s'" % jid)
last = psql("select status || '|' || coalesce(error_code,'') from attachments where id='%s'" % attached['id'])
if job_status == 'failed' and last.startswith('failed|'):
break
time.sleep(0.2)
check(job_status == 'failed' and last == 'failed|injected_failure',
'reprocessed failure did not settle: ' + last)
compose('stop', 'worker')
jobctl('replay', '-job', jid)
projection = client.call(
'GET', '/api/v1/attachments/' + attached['id'], actor=alice, schema='Attachment',
)['json']
check(projection['status'] == 'queued' and projection['error_code'] is None,
'replay left stale terminal projection: ' + str(projection['status']))
reset_worker()
client.wait_ready(alice, attached, wait_seconds=90)
check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2',
'replayed reprocess did not publish pipeline 2')
print('replay of failed reprocess: queued projection restored, then ready at pipeline 2')
def scenario_replay_older_version_refused(client, alice, chat):
compose('stop', 'worker')
attached, _ = client.attachment(alice, chat)
jid_v1 = job_id(attached['id'])
worker_with(FAULTS_ENABLED='1', FAULT_TARGET_JOB=jid_v1, FAULT_WORKER_FAIL='permanent')
status, code, _ = wait_db(attached['id'], lambda s, e, a: s == 'failed', 40, 'failed v1')
check(code == 'injected_failure', 'unexpected v1 failure: ' + code)
compose('stop', 'worker')
reprocessed = json.loads(jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2').stdout)
refused = jobctl('replay', '-job', jid_v1, check=False)
check(refused.returncode != 0, 'older failed version was replayed while v2 exists')
jobs = psql("select pipeline_version || ':' || status from attachment_jobs where attachment_id='%s' order by pipeline_version" % attached['id'])
check(jobs == '1:failed\n2:queued', 'older replay changed job state: ' + jobs.replace('\n', ', '))
print('replay older failed version while v2 queued: refused, state intact')
reset_worker()
client.wait_ready(alice, attached, wait_seconds=90)
check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2',
'v2 did not publish after older replay was refused')
check(psql("select job_id from attachment_jobs where attachment_id='%s' and pipeline_version=2" % attached['id']) == reprocessed['ID'],
'v2 job identity changed')
print('v2 published after older replay refusal')
def main(): def main():
args = arguments('Lab5 level 4 fault injection') args = arguments('Lab5 level 4 fault injection')
client = Client(args.base_url, args.ca_file) client = Client(args.base_url, args.ca_file)
@@ -239,6 +301,8 @@ def main():
scenarios = [ scenarios = [
scenario_permanent_failure_and_replay, scenario_permanent_failure_and_replay,
scenario_replay_older_version_refused,
scenario_replay_reprocessed_version,
scenario_transient_exhaustion, scenario_transient_exhaustion,
scenario_crash_after_first_variant, scenario_crash_after_first_variant,
scenario_crash_after_commit, scenario_crash_after_commit,