lab5: закрытие второго ревью
Validate the PNG raster itself: exact Adam7/non-interlaced row layout, scanline filter bytes, palette/PLTE rules, bounded streaming without keeping the raster. Settle an attachment as failed when a newer pipeline fails before any version was published, while keeping a ready serving version intact. Reject unsupported pipeline versions in jobctl before changing state.
This commit is contained in:
@@ -110,7 +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, PNG со структурой, но не zlib-потоком в IDAT — 415 до 202 | `evidence/lab5/attachments-negative.txt` |
|
| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр и недопустимый scanline-фильтр — 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` |
|
||||||
@@ -150,6 +150,8 @@ flowchart LR
|
|||||||
| 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, v2 ready |
|
| Reprocess queued при остановленном worker | v2 берёт проверенный staging, а не несуществующий original | pv=2 ready, v1 superseded, v2 ready |
|
||||||
|
| Reprocess v2 падает до публикации | вложение терминально failed, не вечный queued | failed/error_code, active jobs 0 |
|
||||||
|
| 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.
|
||||||
|
|||||||
@@ -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))
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
# async 2026-10-30T21:41:04Z
|
# make test-queue 2026-10-30T22:06:09Z
|
||||||
|
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 pipel 2 accepted, upload still queued
|
worker down: reprocess pipeline 2 accepted, upload still queued
|
||||||
worker up: reprocessed upload reached ready at pipeline 2, v1 superseded
|
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
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
# attachments-negative 2026-10-30T21:41:23Z
|
# make test-attachments 2026-10-30T22:06:08Z
|
||||||
|
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
|
structurally valid PNG with non-zlib IDAT: 415
|
||||||
|
valid zlib, empty PNG raster: 415
|
||||||
|
valid zlib, invalid PNG scanline filter: 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
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
ok mtusi-messenger/internal/storage/postgres 9.969s
|
ok mtusi-messenger/internal/storage/postgres 8.719s
|
||||||
ok mtusi-messenger/internal/storage/redis 1.214s
|
ok mtusi-messenger/internal/storage/redis 1.153s
|
||||||
|
|||||||
+11
-11
@@ -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.895333ms: 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 5.412375ms: 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 (deps|exports_file|files|compiled_files|imports|name|types_sizes) took 373.996667ms"
|
level=info msg="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|files|name|types_sizes|imports) took 201.838125ms"
|
||||||
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.67575ms"
|
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 9.454875ms"
|
||||||
level=info msg="[linters_context/goanalysis] analyzers took 22.17725772s with top 10 stages: goimports: 5.594564459s, revive: 3.573092538s, gosec: 1.883430624s, unparam: 1.121477541s, wastedassign: 697.2435ms, gofumpt: 404.984666ms, buildir: 380.350244ms, buildssa: 301.575415ms, gocritic: 286.099209ms, errorlint: 252.740461ms"
|
level=info msg="[linters_context/goanalysis] analyzers took 459.537383ms with top 10 stages: revive: 313.452167ms, goimports: 34.1165ms, gosec: 14.898584ms, wastedassign: 14.345375ms, gomoddirectives: 12.584584ms, unparam: 9.832959ms, buildir: 8.875714ms, gocritic: 8.4825ms, buildssa: 3.619034ms, nilness: 2.914125ms"
|
||||||
level=info msg="[runner/exclusion_rules] Skipped 9 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: 882, after processing: 0"
|
level=info msg="[runner] Issues before processing: 887, after processing: 0"
|
||||||
level=info msg="[runner] Processors filtering stat (in/out): filename_unadjuster: 882/882, generated_file_filter: 882/293, exclusion_rules: 293/6, invalid_issue: 882/882, path_relativity: 882/882, path_absoluter: 882/882, cgo: 882/882, exclusion_paths: 882/882, nolint_filter: 6/0"
|
level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 887/887, generated_file_filter: 887/298, exclusion_rules: 298/6, nolint_filter: 6/0, invalid_issue: 887/887, path_absoluter: 887/887, filename_unadjuster: 887/887, path_relativity: 887/887, cgo: 887/887"
|
||||||
level=info msg="[runner] processing took 3.132833ms with stages: generated_file_filter: 1.925416ms, nolint_filter: 617.626µs, exclusion_rules: 278.75µs, path_relativity: 272.167µs, invalid_issue: 13.042µs, cgo: 11.75µs, path_absoluter: 6.958µs, filename_unadjuster: 3.667µs, sort_results: 875ns, max_same_issues: 792ns, fixer: 334ns, exclusion_paths: 291ns, source_code: 250ns, diff: 249ns, path_prettifier: 167ns, uniq_by_line: 167ns, max_from_linter: 166ns, path_shortener: 125ns, max_per_file_from_linter: 41ns, severity-rules: 0s"
|
level=info msg="[runner] processing took 3.208459ms with stages: generated_file_filter: 2.020333ms, nolint_filter: 610.416µs, path_relativity: 272.751µs, exclusion_rules: 265.791µs, invalid_issue: 14.541µs, cgo: 13.167µs, path_absoluter: 4.667µs, filename_unadjuster: 4.25µs, sort_results: 708ns, max_same_issues: 500ns, fixer: 292ns, path_prettifier: 209ns, exclusion_paths: 209ns, source_code: 167ns, diff: 125ns, path_shortener: 84ns, uniq_by_line: 83ns, max_per_file_from_linter: 83ns, severity-rules: 42ns, max_from_linter: 41ns"
|
||||||
level=info msg="[runner] linters took 2.843002292s with stages: goanalysis_metalinter: 2.839817416s"
|
level=info msg="[runner] linters took 848.949083ms with stages: goanalysis_metalinter: 845.707708ms"
|
||||||
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: 34 samples, avg is 394.2MB, max is 716.6MB"
|
level=info msg="Memory: 12 samples, avg is 104.3MB, max is 151.3MB"
|
||||||
level=info msg="Execution took 3.234388375s"
|
level=info msg="Execution took 1.066180875s"
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
# make test 2026-10-30T21:41:33Z
|
# make test 2026-10-30T22:06:01Z
|
||||||
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
@@ -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.948s
|
ok mtusi-messenger/internal/config 1.789s
|
||||||
ok mtusi-messenger/internal/domain 1.309s
|
ok mtusi-messenger/internal/domain 1.219s
|
||||||
? mtusi-messenger/internal/failpoint [no test files]
|
? mtusi-messenger/internal/failpoint [no test files]
|
||||||
ok mtusi-messenger/internal/health 1.572s
|
ok mtusi-messenger/internal/health 2.129s
|
||||||
ok mtusi-messenger/internal/imagecheck 2.518s
|
ok mtusi-messenger/internal/imagecheck 1.564s
|
||||||
ok mtusi-messenger/internal/imageproc 3.215s
|
ok mtusi-messenger/internal/imageproc 2.376s
|
||||||
ok mtusi-messenger/internal/logger 2.222s
|
ok mtusi-messenger/internal/logger 2.342s
|
||||||
? mtusi-messenger/internal/outbox [no test files]
|
? mtusi-messenger/internal/outbox [no test files]
|
||||||
ok mtusi-messenger/internal/platform/cache 3.331s
|
ok mtusi-messenger/internal/platform/cache 2.769s
|
||||||
? 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.854s
|
ok mtusi-messenger/internal/platform/objectstore 3.754s
|
||||||
ok mtusi-messenger/internal/platform/password 3.647s
|
ok mtusi-messenger/internal/platform/password 3.408s
|
||||||
ok mtusi-messenger/internal/platform/token 4.137s
|
ok mtusi-messenger/internal/platform/token 2.640s
|
||||||
ok mtusi-messenger/internal/service/attachment 4.415s
|
ok mtusi-messenger/internal/service/attachment 3.341s
|
||||||
? mtusi-messenger/internal/service/attachment/mocks [no test files]
|
? mtusi-messenger/internal/service/attachment/mocks [no test files]
|
||||||
ok mtusi-messenger/internal/service/chat 4.715s
|
ok mtusi-messenger/internal/service/chat 3.958s
|
||||||
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
||||||
ok mtusi-messenger/internal/service/message 5.321s
|
ok mtusi-messenger/internal/service/message 3.549s
|
||||||
? mtusi-messenger/internal/service/message/mocks [no test files]
|
? mtusi-messenger/internal/service/message/mocks [no test files]
|
||||||
ok mtusi-messenger/internal/service/session 5.938s
|
ok mtusi-messenger/internal/service/session 3.168s
|
||||||
? mtusi-messenger/internal/service/session/mocks [no test files]
|
? mtusi-messenger/internal/service/session/mocks [no test files]
|
||||||
ok mtusi-messenger/internal/service/user 5.169s
|
ok mtusi-messenger/internal/service/user 4.651s
|
||||||
? mtusi-messenger/internal/service/user/mocks [no test files]
|
? mtusi-messenger/internal/service/user/mocks [no test files]
|
||||||
ok mtusi-messenger/internal/storage/postgres 5.635s
|
ok mtusi-messenger/internal/storage/postgres 4.711s
|
||||||
? 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 5.926s
|
ok mtusi-messenger/internal/transport/rest 4.363s
|
||||||
? 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]
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
// 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 (
|
||||||
@@ -75,13 +77,16 @@ 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
|
||||||
idat bytes.Buffer
|
paletteReady bool
|
||||||
maxInflated int64
|
colorType byte
|
||||||
maxIDAT int64 = -1
|
idat bytes.Buffer
|
||||||
|
raster []pngPass
|
||||||
|
rasterBytes int64
|
||||||
|
maxIDAT int64 = -1
|
||||||
)
|
)
|
||||||
|
|
||||||
info.ContentType = "image/png"
|
info.ContentType = "image/png"
|
||||||
@@ -147,6 +152,7 @@ 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]
|
||||||
|
|
||||||
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)
|
||||||
@@ -158,20 +164,33 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
|||||||
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 := pngInflateBound(info, data[8], data[9])
|
bound, err := pngRasterLayout(info, data[8], data[9], data[10], data[11], data[12])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Info{}, err
|
return Info{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
maxInflated = bound
|
raster = bound
|
||||||
if maxInflated <= 1<<40 {
|
rasterBytes = pngRasterBytes(bound)
|
||||||
|
if rasterBytes <= 1<<40 {
|
||||||
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
|
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
|
||||||
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
|
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
|
||||||
// images where the relative term vanishes.
|
// images where the relative term vanishes.
|
||||||
maxIDAT = maxInflated + maxInflated/256 + 1<<20
|
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 !hasIDAT {
|
||||||
|
paletteReady = 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)
|
||||||
@@ -181,11 +200,15 @@ 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
|
// The chunk walker proves structure, but a stream whose bytes
|
||||||
// merely look like a chunk layout (valid length/type/CRC) may
|
// merely look like a chunk layout (valid length/type/CRC) may
|
||||||
// still not be a zlib stream at all. Inflate the concatenated
|
// still not be a PNG raster: the zlib payload must inflate to
|
||||||
// IDAT payload to catch those before the upload is accepted.
|
// exactly the IHDR-declared scanlines with valid filter bytes.
|
||||||
if err := inflateIDAT(idat.Bytes(), maxInflated); err != nil {
|
if err := validateRaster(idat.Bytes(), raster); err != nil {
|
||||||
return Info{}, err
|
return Info{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,10 +221,41 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pngInflateBound returns the exact decompressed size of a full PNG raster:
|
// pngPass is one consecutive block of scanlines in the inflated image stream.
|
||||||
// one filter byte per row plus ceil(width*bitsPerPixel/8) row bytes, with
|
// Non-interlaced PNGs have a single pass; Adam7 has up to seven.
|
||||||
// slack for the extra passes of an Adam7-interlaced stream.
|
type pngPass struct {
|
||||||
func pngInflateBound(info Info, bitDepth, colorType byte) (int64, error) {
|
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
|
var bitsPerPixel int64
|
||||||
|
|
||||||
switch colorType {
|
switch colorType {
|
||||||
@@ -216,46 +270,99 @@ func pngInflateBound(info Info, bitDepth, colorType byte) (int64, error) {
|
|||||||
case 6: // RGBA
|
case 6: // RGBA
|
||||||
bitsPerPixel = 4 * int64(bitDepth)
|
bitsPerPixel = 4 * int64(bitDepth)
|
||||||
default:
|
default:
|
||||||
return 0, corruptf("png invalid color type %d", colorType)
|
return nil, corruptf("png invalid color type %d", colorType)
|
||||||
}
|
}
|
||||||
|
|
||||||
switch bitDepth {
|
switch bitDepth {
|
||||||
case 1, 2, 4, 8, 16:
|
case 1, 2, 4, 8, 16:
|
||||||
default:
|
default:
|
||||||
return 0, corruptf("png invalid bit depth %d", bitDepth)
|
return nil, corruptf("png invalid bit depth %d", bitDepth)
|
||||||
}
|
}
|
||||||
|
|
||||||
rowBytes := (info.Width*bitsPerPixel + 7) / 8
|
specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}}
|
||||||
rows := info.Height + 8
|
switch interlace {
|
||||||
|
case 0:
|
||||||
if rowBytes+1 > (1<<62)/rows {
|
case 1:
|
||||||
return 0, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
|
specs = adam7Passes
|
||||||
|
default:
|
||||||
|
return nil, corruptf("png invalid interlace method %d", interlace)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (rowBytes + 1) * rows, nil
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// inflateIDAT decompresses the concatenated IDAT payload and requires a clean
|
func pngRasterBytes(passes []pngPass) int64 {
|
||||||
// zlib EOF, which verifies stream framing and the Adler-32 trailer. Corrupt
|
var total int64
|
||||||
// streams (e.g. an IDAT filled with bytes that are not a zlib stream at all)
|
|
||||||
// fail here; streams that inflate beyond the IHDR-declared raster size are
|
for _, pass := range passes {
|
||||||
// rejected as compression bombs.
|
row := (pass.rowBytes + 1) * pass.rows
|
||||||
func inflateIDAT(compressed []byte, maxInflated int64) error {
|
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 {
|
||||||
reader, err := zlib.NewReader(bytes.NewReader(compressed))
|
reader, err := zlib.NewReader(bytes.NewReader(compressed))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return corrupt("png idat zlib header", err)
|
return corrupt("png idat zlib header", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
count, err := io.CopyN(io.Discard, reader, maxInflated+1)
|
for _, pass := range passes {
|
||||||
switch {
|
for range pass.rows {
|
||||||
case errors.Is(err, io.EOF):
|
var filter [1]byte
|
||||||
return nil
|
if _, err := io.ReadFull(reader, filter[:]); err != nil {
|
||||||
case err != nil:
|
return corrupt("png scanline filter", err)
|
||||||
return corrupt("png idat zlib stream", err)
|
}
|
||||||
default:
|
|
||||||
_ = count
|
|
||||||
|
|
||||||
return fmt.Errorf("%w: png idat inflates beyond declared dimensions", ErrTooLarge)
|
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.
|
||||||
|
return nil
|
||||||
|
case err == nil:
|
||||||
|
return fmt.Errorf("%w: png raster exceeds declared dimensions", ErrTooLarge)
|
||||||
|
default:
|
||||||
|
return corrupt("png idat zlib trailer", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package imagecheck_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"compress/zlib"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"hash/crc32"
|
"hash/crc32"
|
||||||
"image"
|
"image"
|
||||||
@@ -47,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)
|
||||||
@@ -91,33 +116,131 @@ func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
|
|||||||
// correct CRCs) whose IDAT payload is not a zlib stream at all. Merely a
|
// 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.
|
// stream-like structure must not make the upload pass: it has to inflate.
|
||||||
func TestValidateRejectsPNGIDATNotAZlibStream(t *testing.T) {
|
func TestValidateRejectsPNGIDATNotAZlibStream(t *testing.T) {
|
||||||
chunk := func(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
|
|
||||||
}
|
|
||||||
|
|
||||||
ihdr := make([]byte, 13)
|
ihdr := make([]byte, 13)
|
||||||
binary.BigEndian.PutUint32(ihdr[0:4], 64) // width
|
binary.BigEndian.PutUint32(ihdr[0:4], 64) // width
|
||||||
binary.BigEndian.PutUint32(ihdr[4:8], 32) // height
|
binary.BigEndian.PutUint32(ihdr[4:8], 32) // height
|
||||||
ihdr[8] = 8 // bit depth
|
ihdr[8] = 8 // bit depth
|
||||||
ihdr[9] = 6 // color type RGBA
|
ihdr[9] = 6 // color type RGBA
|
||||||
|
|
||||||
data := append([]byte("\x89PNG\r\n\x1a\n"), chunk("IHDR", ihdr)...)
|
data := pngFile(
|
||||||
data = append(data, chunk("IDAT", []byte("this is not a zlib stream, but the CRC is right"))...)
|
pngChunk("IHDR", ihdr),
|
||||||
data = append(data, chunk("IEND", nil)...)
|
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)
|
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
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()
|
||||||
|
|
||||||
|
var idat bytes.Buffer
|
||||||
|
writer := zlib.NewWriter(&idat)
|
||||||
|
_, err := writer.Write(raster)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, writer.Close())
|
||||||
|
|
||||||
|
ihdr := make([]byte, 13)
|
||||||
|
binary.BigEndian.PutUint32(ihdr[0:4], uint32(width))
|
||||||
|
binary.BigEndian.PutUint32(ihdr[4:8], uint32(height))
|
||||||
|
ihdr[8] = 8 // bit depth
|
||||||
|
ihdr[9] = colorType
|
||||||
|
ihdr[12] = interlace
|
||||||
|
|
||||||
|
return pngFile(
|
||||||
|
pngChunk("IHDR", ihdr),
|
||||||
|
pngChunk("IDAT", idat.Bytes()),
|
||||||
|
pngChunk("IEND", nil),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|||||||
@@ -998,7 +998,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',
|
||||||
|
|||||||
@@ -221,6 +221,86 @@ func (s *PipelineSuite) TestReprocessReadyUsesObjectSource() {
|
|||||||
s.Equal(draft.ObjectKey, created.SourceKey)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
||||||
alice := s.createUser("alice")
|
alice := s.createUser("alice")
|
||||||
chat := s.createChat(alice)
|
chat := s.createChat(alice)
|
||||||
|
|||||||
@@ -26,6 +26,22 @@ 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):
|
||||||
|
"""PNG with correct chunk lengths and CRCs around arbitrary IDAT bytes."""
|
||||||
|
ihdr = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, interlace)
|
||||||
|
return (
|
||||||
|
b'\x89PNG\r\n\x1a\n'
|
||||||
|
+ png_chunk(b'IHDR', ihdr)
|
||||||
|
+ 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)
|
||||||
@@ -56,23 +72,21 @@ def main():
|
|||||||
# not accept it: the stream has to inflate. Regression for a review
|
# not accept it: the stream has to inflate. Regression for a review
|
||||||
# finding that used to produce 202 queued and then failed/invalid_image
|
# finding that used to produce 202 queued and then failed/invalid_image
|
||||||
# in the worker.
|
# in the worker.
|
||||||
def craft_not_a_zlib_png():
|
upload(
|
||||||
def chunk(ctype, payload):
|
client, alice, chat,
|
||||||
crc = zlib.crc32(ctype + payload) & 0xffffffff
|
crafted_png(64, 32, 0, b'this is not a zlib stream'),
|
||||||
return struct.pack('>I', len(payload)) + ctype + payload + struct.pack('>I', crc)
|
expected=415,
|
||||||
|
)
|
||||||
ihdr = struct.pack('>IIBBBBB', 64, 32, 8, 6, 0, 0, 0) # 64x32, RGBA
|
|
||||||
return (
|
|
||||||
b'\x89PNG\r\n\x1a\n'
|
|
||||||
+ chunk(b'IHDR', ihdr)
|
|
||||||
+ chunk(b'IDAT', b'this is not a zlib stream, but the CRC is right')
|
|
||||||
+ chunk(b'IEND', b'')
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
upload(client, alice, chat, craft_not_a_zlib_png(), expected=415)
|
|
||||||
print('structurally valid PNG with non-zlib IDAT: 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')
|
||||||
|
|
||||||
# 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)
|
||||||
|
|||||||
@@ -120,6 +120,27 @@ def main():
|
|||||||
'old job not superseded or new job not ready')
|
'old job not superseded or new job not ready')
|
||||||
print('worker up: reprocessed upload reached ready at pipeline 2, v1 superseded')
|
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')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user