diff --git a/REPORT.md b/REPORT.md index b23cec7a..b2dbf534 100644 --- a/REPORT.md +++ b/REPORT.md @@ -110,7 +110,7 @@ flowchart LR | Полный 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` | | Состояния 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-фильтр — 415 до 202 | `evidence/lab5/attachments-negative.txt` | +| 415 на невалидное изображение | `make test-attachments` | пустое тело, IDAT-CRC, MIME spoof, не-zlib IDAT, пустой растр, недопустимый scanline-фильтр, несовместимые color type/bit depth, дубликаты IHDR, мусор после zlib — 415 до 202 | `evidence/lab5/attachments-negative.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` | | DLQ/registry + replay | `lab5_faults.py` | failed виден в `jobctl failed`; replay → ready; replay ready refused | `evidence/lab5/faults.txt` | @@ -151,6 +151,7 @@ flowchart LR | 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 v2 падает до публикации | вложение терминально failed, не вечный queued | failed/error_code, active jobs 0 | +| Replay упавшей v2 до публикации | API не показывает stale failed, работа возвращается | job queued, attachment queued, затем ready:v2 | | Reprocess на неподдерживаемую версию | команда отклонена, v1-задание не тронуто | jobctl exit != 0, v1 queued → ready | Измерения: recovery времени и counts — из `evidence/lab5/faults.txt`, `track2/runs.csv`. diff --git a/evidence/lab5/async.txt b/evidence/lab5/async.txt index 7ab81cce..dbd89bda 100644 --- a/evidence/lab5/async.txt +++ b/evidence/lab5/async.txt @@ -1,4 +1,4 @@ -# make test-queue 2026-10-30T22:06:09Z +# make test-queue 2026-10-30T22:19:06Z 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 restarted: ready, thumbnail and original downloadable, staging cleared diff --git a/evidence/lab5/attachments-negative.txt b/evidence/lab5/attachments-negative.txt index 233b1899..af69f36a 100644 --- a/evidence/lab5/attachments-negative.txt +++ b/evidence/lab5/attachments-negative.txt @@ -1,4 +1,4 @@ -# make test-attachments 2026-10-30T22:06:08Z +# make test-attachments 2026-10-30T22:19:04Z 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 empty body: 415 @@ -7,6 +7,9 @@ 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 dangerous filenames: 400 foreign attachment metadata/content: 404 empty text without attachments: 400 diff --git a/evidence/lab5/faults.txt b/evidence/lab5/faults.txt index 9c1ad93d..39cd3792 100644 --- a/evidence/lab5/faults.txt +++ b/evidence/lab5/faults.txt @@ -1,7 +1,9 @@ -# fault injection 2026-10-30T20:09:37Z +# make test-faults 2026-10-30T22:19:30Z +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 replay: failed -> queued -> ready, one thumbnail replay ready job: refused +replay of failed reprocess: queued projection restored, then ready at pipeline 2 transient exhaustion: attempts=5, retry_exhausted, four retries, DLQ message present crash after first variant: redelivered, same three variants, attempts=2 crash after commit before ack: ready remains, redelivery is a no-op diff --git a/evidence/lab5/integration-test.txt b/evidence/lab5/integration-test.txt index e0933dad..a612c13f 100644 --- a/evidence/lab5/integration-test.txt +++ b/evidence/lab5/integration-test.txt @@ -1,2 +1,2 @@ -ok mtusi-messenger/internal/storage/postgres 8.719s -ok mtusi-messenger/internal/storage/redis 1.153s +ok mtusi-messenger/internal/storage/postgres 9.691s +ok mtusi-messenger/internal/storage/redis 1.246s diff --git a/evidence/lab5/lint.txt b/evidence/lab5/lint.txt index 3f5c5e1f..47b88386 100644 --- a/evidence/lab5/lint.txt +++ b/evidence/lab5/lint.txt @@ -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] Used config file .golangci.yml" level=info msg="[config_reader] Module name \"mtusi-messenger\"" -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="[goenv] Read go env for 6.440209ms: 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="[loader] Using build tags: [integration]" -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 9.454875ms" -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="[loader] Go packages loading at mode 8767 (compiled_files|deps|exports_file|imports|files|name|types_sizes) took 200.621833ms" +level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.581125ms" +level=info msg="[linters_context/goanalysis] analyzers took 0s with no stages" 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: 887, after processing: 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.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 848.949083ms with stages: goanalysis_metalinter: 845.707708ms" +level=info msg="[runner] Processors filtering stat (in/out): exclusion_paths: 887/887, path_absoluter: 887/887, cgo: 887/887, invalid_issue: 887/887, exclusion_rules: 298/6, filename_unadjuster: 887/887, path_relativity: 887/887, nolint_filter: 6/0, generated_file_filter: 887/298" +level=info msg="[runner] processing took 3.023042ms with stages: generated_file_filter: 1.594792ms, nolint_filter: 794.292µs, path_relativity: 317.917µs, exclusion_rules: 278.458µs, invalid_issue: 13.25µs, cgo: 12.166µs, path_absoluter: 6.167µs, filename_unadjuster: 2.875µs, sort_results: 875ns, max_same_issues: 625ns, exclusion_paths: 416ns, fixer: 250ns, path_prettifier: 209ns, diff: 167ns, source_code: 167ns, max_per_file_from_linter: 125ns, path_shortener: 125ns, max_from_linter: 83ns, uniq_by_line: 83ns, severity-rules: 0s" +level=info msg="[runner] linters took 663.901083ms with stages: goanalysis_metalinter: 660.828ms" 0 issues. level=info msg="File cache stats: 0 entries of total size 0B" -level=info msg="Memory: 12 samples, avg is 104.3MB, max is 151.3MB" -level=info msg="Execution took 1.066180875s" +level=info msg="Memory: 10 samples, avg is 91.9MB, max is 127.5MB" +level=info msg="Execution took 882.402625ms" diff --git a/evidence/lab5/smoke.txt b/evidence/lab5/smoke.txt index 5964f30a..6aea81e8 100644 --- a/evidence/lab5/smoke.txt +++ b/evidence/lab5/smoke.txt @@ -1,3 +1,3 @@ -# make test 2026-10-30T22:06:01Z +# make test 2026-10-30T22:19:26Z 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. diff --git a/evidence/lab5/unit-test.txt b/evidence/lab5/unit-test.txt index b994d50c..d55d3234 100644 --- a/evidence/lab5/unit-test.txt +++ b/evidence/lab5/unit-test.txt @@ -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/worker [no test files] ? mtusi-messenger/internal/broker [no test files] -ok mtusi-messenger/internal/config 1.789s -ok mtusi-messenger/internal/domain 1.219s +ok mtusi-messenger/internal/config 1.556s +ok mtusi-messenger/internal/domain 2.720s ? mtusi-messenger/internal/failpoint [no test files] -ok mtusi-messenger/internal/health 2.129s -ok mtusi-messenger/internal/imagecheck 1.564s -ok mtusi-messenger/internal/imageproc 2.376s -ok mtusi-messenger/internal/logger 2.342s +ok mtusi-messenger/internal/health 1.789s +ok mtusi-messenger/internal/imagecheck 2.116s +ok mtusi-messenger/internal/imageproc 3.443s +ok mtusi-messenger/internal/logger 2.441s ? mtusi-messenger/internal/outbox [no test files] -ok mtusi-messenger/internal/platform/cache 2.769s +ok mtusi-messenger/internal/platform/cache 3.537s ? mtusi-messenger/internal/platform/cache/mocks [no test files] -ok mtusi-messenger/internal/platform/objectstore 3.754s -ok mtusi-messenger/internal/platform/password 3.408s -ok mtusi-messenger/internal/platform/token 2.640s -ok mtusi-messenger/internal/service/attachment 3.341s +ok mtusi-messenger/internal/platform/objectstore 3.995s +ok mtusi-messenger/internal/platform/password 4.080s +ok mtusi-messenger/internal/platform/token 3.091s +ok mtusi-messenger/internal/service/attachment 4.331s ? mtusi-messenger/internal/service/attachment/mocks [no test files] -ok mtusi-messenger/internal/service/chat 3.958s +ok mtusi-messenger/internal/service/chat 4.626s ? mtusi-messenger/internal/service/chat/mocks [no test files] -ok mtusi-messenger/internal/service/message 3.549s +ok mtusi-messenger/internal/service/message 4.943s ? mtusi-messenger/internal/service/message/mocks [no test files] -ok mtusi-messenger/internal/service/session 3.168s +ok mtusi-messenger/internal/service/session 5.870s ? mtusi-messenger/internal/service/session/mocks [no test files] -ok mtusi-messenger/internal/service/user 4.651s +ok mtusi-messenger/internal/service/user 6.026s ? mtusi-messenger/internal/service/user/mocks [no test files] -ok mtusi-messenger/internal/storage/postgres 4.711s +ok mtusi-messenger/internal/storage/postgres 5.253s ? mtusi-messenger/internal/storage/postgres/internal/sqlcgen [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/mocks [no test files] -ok mtusi-messenger/internal/transport/rest 4.363s +ok mtusi-messenger/internal/transport/rest 6.240s ? mtusi-messenger/internal/transport/rest/internal/oas [no test files] ? mtusi-messenger/internal/transport/rest/mocks [no test files] ? mtusi-messenger/internal/worker [no test files] diff --git a/evidence/lab5/validate.txt b/evidence/lab5/validate.txt index 248343ee..5eafe4a9 100644 --- a/evidence/lab5/validate.txt +++ b/evidence/lab5/validate.txt @@ -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. diff --git a/internal/imagecheck/imagecheck.go b/internal/imagecheck/imagecheck.go index 9820be1c..f3676f30 100644 --- a/internal/imagecheck/imagecheck.go +++ b/internal/imagecheck/imagecheck.go @@ -87,6 +87,7 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { raster []pngPass rasterBytes int64 maxIDAT int64 = -1 + lastChunk string ) info.ContentType = "image/png" @@ -117,6 +118,18 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { 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 { return Info{}, err } @@ -218,6 +231,8 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) { return info, nil } + + lastChunk = chunkType } } @@ -260,25 +275,39 @@ func pngRasterLayout( 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) } - switch bitDepth { - case 1, 2, 4, 8, 16: - default: - return nil, corruptf("png invalid bit depth %d", bitDepth) - } - specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}} switch interlace { case 0: @@ -332,7 +361,9 @@ func pngRasterBytes(passes []pngPass) int64 { // 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)) + source := bytes.NewReader(compressed) + + reader, err := zlib.NewReader(source) if err != nil { return corrupt("png idat zlib header", err) } @@ -357,7 +388,13 @@ func validateRaster(compressed []byte, passes []pngPass) error { 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. + // 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) diff --git a/internal/imagecheck/imagecheck_test.go b/internal/imagecheck/imagecheck_test.go index 9f705e1e..e7e42d33 100644 --- a/internal/imagecheck/imagecheck_test.go +++ b/internal/imagecheck/imagecheck_test.go @@ -141,24 +141,41 @@ func craftedPNG(t *testing.T, width, height int, interlace byte, raster []byte) func craftedPNGType(t *testing.T, width, height int, colorType, interlace byte, raster []byte) []byte { t.Helper() - var idat bytes.Buffer - writer := zlib.NewWriter(&idat) + 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()) - 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), - ) + return compressed.Bytes() } func TestValidateRejectsPNGEmptyRaster(t *testing.T) { @@ -202,6 +219,105 @@ func TestValidateAcceptsPalettePNG(t *testing.T) { 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) + } +} + // 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) { diff --git a/internal/storage/postgres/pipeline_repository.go b/internal/storage/postgres/pipeline_repository.go index d70dab37..6182da0e 100644 --- a/internal/storage/postgres/pipeline_repository.go +++ b/internal/storage/postgres/pipeline_repository.go @@ -1474,15 +1474,25 @@ func (r *PipelineRepository) ReplayJob( 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, ` UPDATE attachments SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = now() WHERE id = $1 AND pipeline_version = $2`, attachment.ID, job.PipelineVersion) - if err != nil { - return fmt.Errorf("replay attachment: %w", mapError(err)) - } + case job.PipelineVersion > attachment.PipelineVersion && attachment.Status != domain.AttachmentReady: + _, 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 { diff --git a/internal/storage/postgres/pipeline_repository_test.go b/internal/storage/postgres/pipeline_repository_test.go index 450d782f..435c8e32 100644 --- a/internal/storage/postgres/pipeline_repository_test.go +++ b/internal/storage/postgres/pipeline_repository_test.go @@ -301,6 +301,118 @@ func (s *PipelineSuite) TestReprocessFailureKeepsReadyServingVersion() { 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) +} + func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() { alice := s.createUser("alice") chat := s.createChat(alice) diff --git a/student-tests/attachments_negative.py b/student-tests/attachments_negative.py index b91a029e..989a81cf 100755 --- a/student-tests/attachments_negative.py +++ b/student-tests/attachments_negative.py @@ -31,9 +31,9 @@ def png_chunk(ctype, payload): return struct.pack('>I', len(payload)) + ctype + payload + struct.pack('>I', crc) -def crafted_png(width, height, interlace, raster): +def crafted_png(width, height, interlace, raster, bit_depth=8, color_type=6): """PNG with correct chunk lengths and CRCs around arbitrary IDAT bytes.""" - ihdr = struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, interlace) + 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) @@ -87,6 +87,31 @@ def main(): 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') + # Dangerous display names. 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) diff --git a/student-tests/lab5_faults.py b/student-tests/lab5_faults.py index cea7713f..8e246499 100755 --- a/student-tests/lab5_faults.py +++ b/student-tests/lab5_faults.py @@ -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 """ +import json import subprocess import sys import time @@ -232,6 +233,41 @@ def scenario_lease_takeover(client, alice, chat): 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 main(): args = arguments('Lab5 level 4 fault injection') client = Client(args.base_url, args.ca_file) @@ -239,6 +275,7 @@ def main(): scenarios = [ scenario_permanent_failure_and_replay, + scenario_replay_reprocessed_version, scenario_transient_exhaustion, scenario_crash_after_first_variant, scenario_crash_after_commit,