lab5: исправления второго ревью
Reprocess of a queued/processing/failed upload now sources from verified staging instead of the not-yet-written final original, which used to supersede v1 and strand the attachment in queued. PNG uploads now inflate the concatenated IDAT stream (bounded by IHDR dimensions) before acceptance, so a structurally valid PNG whose IDAT is not a zlib stream is rejected with 415 instead of 202.
This commit is contained in:
@@ -110,6 +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, PNG со структурой, но не zlib-потоком в IDAT — 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` |
|
||||
@@ -148,6 +149,7 @@ flowchart LR
|
||||
| Transient errors | 5 attempts, backoff+jitter, failed | attempts=5, `retry_exhausted`, DLQ |
|
||||
| Failed replay | failed→queued→ready без дубля | ready, один thumbnail |
|
||||
| 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 |
|
||||
|
||||
Измерения: recovery времени и counts — из `evidence/lab5/faults.txt`, `track2/runs.csv`.
|
||||
Стенд: 2 vCPU, 2 ГБ Docker VM; синтетические пользователи/чат; fixture 320×200 PNG.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# lab5_async 2026-10-30T20:15:54Z
|
||||
# async 2026-10-30T21:41:04Z
|
||||
worker down: 202 queued, content 409, queued attachment linked, API restarted
|
||||
worker restarted: ready, thumbnail and original downloadable, staging cleared
|
||||
broker down: upload accepted into outbox
|
||||
broker + relay recovered: queued job reached ready
|
||||
stack restart: ready attachment and original preserved
|
||||
worker down: reprocess pipel 2 accepted, upload still queued
|
||||
worker up: reprocessed upload reached ready at pipeline 2, v1 superseded
|
||||
PASS: lab5 async worker/broker durability
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# attachments negative 2026-10-30T20:11: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/attachments_negative.py --base-url "http://localhost:8080"
|
||||
# attachments-negative 2026-10-30T21:41:23Z
|
||||
10 MiB + 1 body: 413
|
||||
empty body: 415
|
||||
corrupt PNG (IDAT CRC): 415
|
||||
MIME spoof (PNG declared as JPEG): 415
|
||||
structurally valid PNG with non-zlib IDAT: 415
|
||||
dangerous filenames: 400
|
||||
foreign attachment metadata/content: 404
|
||||
empty text without attachments: 400
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
ok mtusi-messenger/internal/storage/postgres 8.765s
|
||||
ok mtusi-messenger/internal/storage/redis 1.264s
|
||||
ok mtusi-messenger/internal/storage/postgres 9.969s
|
||||
ok mtusi-messenger/internal/storage/redis 1.214s
|
||||
|
||||
+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] Used config file .golangci.yml"
|
||||
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 5.895333ms: 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 (types_sizes|compiled_files|deps|exports_file|files|imports|name) took 398.270958ms"
|
||||
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 8.419166ms"
|
||||
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="[runner/exclusion_rules] Skipped 8 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] 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] 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] linters took 2.038491625s with stages: goanalysis_metalinter: 2.035411833s"
|
||||
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="[runner/filename_unadjuster] Pre-built 0 adjustments in 10.67575ms"
|
||||
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="[runner/exclusion_rules] Skipped 9 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] 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] 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] linters took 2.843002292s with stages: goanalysis_metalinter: 2.839817416s"
|
||||
0 issues.
|
||||
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="Execution took 2.45183725s"
|
||||
level=info msg="Memory: 34 samples, avg is 394.2MB, max is 716.6MB"
|
||||
level=info msg="Execution took 3.234388375s"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# make test 2026-10-30T20:15:52Z
|
||||
# make test 2026-10-30T21:41:33Z
|
||||
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.
|
||||
|
||||
+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/worker [no test files]
|
||||
? mtusi-messenger/internal/broker [no test files]
|
||||
ok mtusi-messenger/internal/config 1.386s
|
||||
ok mtusi-messenger/internal/domain 1.658s
|
||||
ok mtusi-messenger/internal/config 1.948s
|
||||
ok mtusi-messenger/internal/domain 1.309s
|
||||
? mtusi-messenger/internal/failpoint [no test files]
|
||||
ok mtusi-messenger/internal/health 2.083s
|
||||
ok mtusi-messenger/internal/imagecheck 4.315s
|
||||
ok mtusi-messenger/internal/imageproc 5.409s
|
||||
ok mtusi-messenger/internal/logger 4.670s
|
||||
ok mtusi-messenger/internal/health 1.572s
|
||||
ok mtusi-messenger/internal/imagecheck 2.518s
|
||||
ok mtusi-messenger/internal/imageproc 3.215s
|
||||
ok mtusi-messenger/internal/logger 2.222s
|
||||
? mtusi-messenger/internal/outbox [no test files]
|
||||
ok mtusi-messenger/internal/platform/cache 4.248s
|
||||
ok mtusi-messenger/internal/platform/cache 3.331s
|
||||
? mtusi-messenger/internal/platform/cache/mocks [no test files]
|
||||
ok mtusi-messenger/internal/platform/objectstore 3.614s
|
||||
ok mtusi-messenger/internal/platform/password 6.512s
|
||||
ok mtusi-messenger/internal/platform/token 5.267s
|
||||
ok mtusi-messenger/internal/service/attachment 5.575s
|
||||
ok mtusi-messenger/internal/platform/objectstore 3.854s
|
||||
ok mtusi-messenger/internal/platform/password 3.647s
|
||||
ok mtusi-messenger/internal/platform/token 4.137s
|
||||
ok mtusi-messenger/internal/service/attachment 4.415s
|
||||
? mtusi-messenger/internal/service/attachment/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/chat 5.869s
|
||||
ok mtusi-messenger/internal/service/chat 4.715s
|
||||
? mtusi-messenger/internal/service/chat/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/message 3.241s
|
||||
ok mtusi-messenger/internal/service/message 5.321s
|
||||
? mtusi-messenger/internal/service/message/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/session 2.799s
|
||||
ok mtusi-messenger/internal/service/session 5.938s
|
||||
? mtusi-messenger/internal/service/session/mocks [no test files]
|
||||
ok mtusi-messenger/internal/service/user 3.064s
|
||||
ok mtusi-messenger/internal/service/user 5.169s
|
||||
? mtusi-messenger/internal/service/user/mocks [no test files]
|
||||
ok mtusi-messenger/internal/storage/postgres 6.169s
|
||||
ok mtusi-messenger/internal/storage/postgres 5.635s
|
||||
? 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 6.517s
|
||||
ok mtusi-messenger/internal/transport/rest 5.926s
|
||||
? 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]
|
||||
|
||||
@@ -7,6 +7,8 @@ package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -73,10 +75,13 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
}
|
||||
|
||||
var (
|
||||
info Info
|
||||
seen = make(map[string]bool, 4)
|
||||
first = true
|
||||
hasIDAT bool
|
||||
info Info
|
||||
seen = make(map[string]bool, 4)
|
||||
first = true
|
||||
hasIDAT bool
|
||||
idat bytes.Buffer
|
||||
maxInflated int64
|
||||
maxIDAT int64 = -1
|
||||
)
|
||||
|
||||
info.ContentType = "image/png"
|
||||
@@ -111,7 +116,16 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
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 {
|
||||
return Info{}, corrupt("png chunk data", err)
|
||||
}
|
||||
@@ -143,6 +157,19 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
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)
|
||||
}
|
||||
|
||||
bound, err := pngInflateBound(info, data[8], data[9])
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
maxInflated = bound
|
||||
if maxInflated <= 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 = maxInflated + maxInflated/256 + 1<<20
|
||||
}
|
||||
case "IDAT":
|
||||
hasIDAT = true
|
||||
case "IEND":
|
||||
@@ -154,6 +181,14 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
return Info{}, corruptf("png has no IDAT chunk")
|
||||
}
|
||||
|
||||
// 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 zlib stream at all. Inflate the concatenated
|
||||
// IDAT payload to catch those before the upload is accepted.
|
||||
if err := inflateIDAT(idat.Bytes(), maxInflated); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return Info{}, corrupt("png trailing data", err)
|
||||
}
|
||||
@@ -163,9 +198,71 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// pngInflateBound returns the exact decompressed size of a full PNG raster:
|
||||
// one filter byte per row plus ceil(width*bitsPerPixel/8) row bytes, with
|
||||
// slack for the extra passes of an Adam7-interlaced stream.
|
||||
func pngInflateBound(info Info, bitDepth, colorType byte) (int64, error) {
|
||||
var bitsPerPixel int64
|
||||
|
||||
switch colorType {
|
||||
case 0: // grayscale
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 2: // truecolor
|
||||
bitsPerPixel = 3 * int64(bitDepth)
|
||||
case 3: // palette
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 4: // grayscale + alpha
|
||||
bitsPerPixel = 2 * int64(bitDepth)
|
||||
case 6: // RGBA
|
||||
bitsPerPixel = 4 * int64(bitDepth)
|
||||
default:
|
||||
return 0, corruptf("png invalid color type %d", colorType)
|
||||
}
|
||||
|
||||
switch bitDepth {
|
||||
case 1, 2, 4, 8, 16:
|
||||
default:
|
||||
return 0, corruptf("png invalid bit depth %d", bitDepth)
|
||||
}
|
||||
|
||||
rowBytes := (info.Width*bitsPerPixel + 7) / 8
|
||||
rows := info.Height + 8
|
||||
|
||||
if rowBytes+1 > (1<<62)/rows {
|
||||
return 0, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
|
||||
}
|
||||
|
||||
return (rowBytes + 1) * rows, nil
|
||||
}
|
||||
|
||||
// inflateIDAT decompresses the concatenated IDAT payload and requires a clean
|
||||
// zlib EOF, which verifies stream framing and the Adler-32 trailer. Corrupt
|
||||
// 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
|
||||
// rejected as compression bombs.
|
||||
func inflateIDAT(compressed []byte, maxInflated int64) error {
|
||||
reader, err := zlib.NewReader(bytes.NewReader(compressed))
|
||||
if err != nil {
|
||||
return corrupt("png idat zlib header", err)
|
||||
}
|
||||
|
||||
count, err := io.CopyN(io.Discard, reader, maxInflated+1)
|
||||
switch {
|
||||
case errors.Is(err, io.EOF):
|
||||
return nil
|
||||
case err != nil:
|
||||
return corrupt("png idat zlib stream", err)
|
||||
default:
|
||||
_ = count
|
||||
|
||||
return fmt.Errorf("%w: png idat inflates beyond declared dimensions", ErrTooLarge)
|
||||
}
|
||||
}
|
||||
|
||||
func checkCriticalChunk(chunkType string, seen map[string]bool) error {
|
||||
if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" {
|
||||
seen[chunkType] = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -176,7 +273,7 @@ func checkCriticalChunk(chunkType string, seen map[string]bool) error {
|
||||
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 {
|
||||
data := make([]byte, length)
|
||||
if _, err := io.ReadFull(reader, data); err != nil {
|
||||
@@ -184,11 +281,19 @@ func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte,
|
||||
}
|
||||
|
||||
_, _ = checksum.Write(data)
|
||||
if sink != nil {
|
||||
_, _ = sink.Write(data)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package imagecheck_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
@@ -85,6 +87,37 @@ func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
|
||||
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) {
|
||||
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)
|
||||
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 := append([]byte("\x89PNG\r\n\x1a\n"), chunk("IHDR", ihdr)...)
|
||||
data = append(data, chunk("IDAT", []byte("this is not a zlib stream, but the CRC is right"))...)
|
||||
data = append(data, chunk("IEND", nil)...)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsTruncatedJPEG(t *testing.T) {
|
||||
data := encodeJPEG(t, 64, 64)
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000)
|
||||
|
||||
@@ -1338,9 +1338,24 @@ func (r *PipelineRepository) Reprocess(
|
||||
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 == "" {
|
||||
sourceKey = attachment.StagingKey
|
||||
sourceKey = attachment.ObjectKey
|
||||
}
|
||||
if sourceKey == "" {
|
||||
return fmt.Errorf("%w: attachment has no source object", domain.ErrConflict)
|
||||
|
||||
@@ -158,6 +158,69 @@ func (s *PipelineSuite) TestAdmissionCountsPendingPresignAndIsAtomic() {
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
@@ -5,10 +5,12 @@ Run against a live stand:
|
||||
python3 student-tests/attachments_negative.py --base-url http://localhost:8080
|
||||
"""
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
@@ -49,6 +51,28 @@ def main():
|
||||
upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=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.
|
||||
def craft_not_a_zlib_png():
|
||||
def chunk(ctype, payload):
|
||||
crc = zlib.crc32(ctype + payload) & 0xffffffff
|
||||
return struct.pack('>I', len(payload)) + ctype + payload + struct.pack('>I', crc)
|
||||
|
||||
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')
|
||||
|
||||
# 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)
|
||||
|
||||
@@ -12,7 +12,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
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'
|
||||
|
||||
@@ -97,6 +97,29 @@ def main():
|
||||
check(body['bytes'] == content, 'original lost across restart')
|
||||
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')
|
||||
print('worker down: reprocess pipeline 2 accepted, 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')
|
||||
|
||||
print('PASS: lab5 async worker/broker durability')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user