lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
This commit is contained in:
@@ -1,12 +1,16 @@
|
||||
// Package imagecheck validates PNG and JPEG structure without decoding the
|
||||
// raster. A full decode of a 40-megapixel image would allocate hundreds of
|
||||
// megabytes; attachment uploads must stay bounded. The parser verifies chunk
|
||||
// CRCs and the JPEG marker/scan structure, which catches truncation and
|
||||
// corruption while using constant memory.
|
||||
// raster into an image. A full decode of a 40-megapixel image would allocate
|
||||
// hundreds of megabytes; attachment uploads must stay bounded. For PNG the
|
||||
// parser verifies chunk CRCs and streams the zlib image data to check exact
|
||||
// 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
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -73,10 +77,20 @@ 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
|
||||
paletteReady bool
|
||||
trnsSeen bool
|
||||
colorType byte
|
||||
bitDepth byte
|
||||
paletteEntries int
|
||||
idat bytes.Buffer
|
||||
raster []pngPass
|
||||
rasterBytes int64
|
||||
maxIDAT int64 = -1
|
||||
lastChunk string
|
||||
)
|
||||
|
||||
info.ContentType = "image/png"
|
||||
@@ -107,11 +121,32 @@ 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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -133,6 +168,8 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
|
||||
info.Width = int64(binary.BigEndian.Uint32(data[0:4]))
|
||||
info.Height = int64(binary.BigEndian.Uint32(data[4:8]))
|
||||
colorType = data[9]
|
||||
bitDepth = data[8]
|
||||
|
||||
if info.Width <= 0 || info.Height <= 0 {
|
||||
return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height)
|
||||
@@ -143,8 +180,84 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
if maxPixels > 0 && (info.Width > maxPixels || info.Height > maxPixels || info.Width*info.Height > maxPixels) {
|
||||
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
|
||||
}
|
||||
|
||||
bound, err := pngRasterLayout(info, data[8], data[9], data[10], data[11], data[12])
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
raster = bound
|
||||
rasterBytes = pngRasterBytes(bound)
|
||||
if rasterBytes <= 1<<40 {
|
||||
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
|
||||
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
|
||||
// images where the relative term vanishes.
|
||||
maxIDAT = rasterBytes + rasterBytes/256 + 1<<20
|
||||
}
|
||||
case "IDAT":
|
||||
hasIDAT = true
|
||||
case "PLTE":
|
||||
if colorType == 0 || colorType == 4 {
|
||||
return Info{}, corruptf("png PLTE is invalid for color type %d", colorType)
|
||||
}
|
||||
|
||||
if length == 0 || length%3 != 0 || length > 3*256 {
|
||||
return Info{}, corruptf("png PLTE length %d", length)
|
||||
}
|
||||
|
||||
if length/3 > 1<<bitDepth {
|
||||
return Info{}, corruptf(
|
||||
"png PLTE has %d entries for bit depth %d", length/3, bitDepth,
|
||||
)
|
||||
}
|
||||
|
||||
if trnsSeen {
|
||||
return Info{}, corruptf("png PLTE chunk after tRNS")
|
||||
}
|
||||
|
||||
paletteEntries = int(length / 3)
|
||||
|
||||
if !hasIDAT {
|
||||
paletteReady = true
|
||||
}
|
||||
case "tRNS":
|
||||
if trnsSeen {
|
||||
return Info{}, corruptf("png duplicate tRNS chunk")
|
||||
}
|
||||
|
||||
if hasIDAT {
|
||||
return Info{}, corruptf("png tRNS chunk after IDAT")
|
||||
}
|
||||
|
||||
switch colorType {
|
||||
case 0:
|
||||
if length != 2 {
|
||||
return Info{}, corruptf("png tRNS length %d for color type 0", length)
|
||||
}
|
||||
case 2:
|
||||
if length != 6 {
|
||||
return Info{}, corruptf("png tRNS length %d for color type 2", length)
|
||||
}
|
||||
case 3:
|
||||
if !paletteReady {
|
||||
return Info{}, corruptf("png tRNS before PLTE")
|
||||
}
|
||||
|
||||
if length > 256 {
|
||||
return Info{}, corruptf("png tRNS length %d", length)
|
||||
}
|
||||
|
||||
if int(length) > paletteEntries {
|
||||
return Info{}, corruptf(
|
||||
"png tRNS length %d exceeds %d palette entries",
|
||||
length, paletteEntries,
|
||||
)
|
||||
}
|
||||
default:
|
||||
return Info{}, corruptf("png tRNS invalid for color type %d", colorType)
|
||||
}
|
||||
|
||||
trnsSeen = true
|
||||
case "IEND":
|
||||
if length != 0 {
|
||||
return Info{}, corruptf("png IEND length %d", length)
|
||||
@@ -154,18 +267,200 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
return Info{}, corruptf("png has no IDAT chunk")
|
||||
}
|
||||
|
||||
if colorType == 3 && !paletteReady {
|
||||
return Info{}, corruptf("png palette image has no PLTE before IDAT")
|
||||
}
|
||||
|
||||
// The chunk walker proves structure, but a stream whose bytes
|
||||
// merely look like a chunk layout (valid length/type/CRC) may
|
||||
// still not be a PNG raster: the zlib payload must inflate to
|
||||
// exactly the IHDR-declared scanlines with valid filter bytes.
|
||||
if err := validateRaster(idat.Bytes(), raster); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return Info{}, corrupt("png trailing data", err)
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
lastChunk = chunkType
|
||||
}
|
||||
}
|
||||
|
||||
// pngPass is one consecutive block of scanlines in the inflated image stream.
|
||||
// Non-interlaced PNGs have a single pass; Adam7 has up to seven.
|
||||
type pngPass struct {
|
||||
rowBytes int64
|
||||
rows int64
|
||||
}
|
||||
|
||||
type pngPassSpec struct {
|
||||
x0, y0 int64
|
||||
dx, dy int64
|
||||
}
|
||||
|
||||
var adam7Passes = []pngPassSpec{
|
||||
{x0: 0, y0: 0, dx: 8, dy: 8},
|
||||
{x0: 4, y0: 0, dx: 8, dy: 8},
|
||||
{x0: 0, y0: 4, dx: 4, dy: 8},
|
||||
{x0: 2, y0: 0, dx: 4, dy: 4},
|
||||
{x0: 0, y0: 2, dx: 2, dy: 4},
|
||||
{x0: 1, y0: 0, dx: 2, dy: 2},
|
||||
{x0: 0, y0: 1, dx: 1, dy: 2},
|
||||
}
|
||||
|
||||
// pngRasterLayout returns the exact inflated size and row layout for the
|
||||
// IHDR. The Adam7 layout matters: a single non-interlaced formula either
|
||||
// rejects valid interlaced images or accepts oversized streams.
|
||||
func pngRasterLayout(
|
||||
info Info,
|
||||
bitDepth, colorType, compression, filter, interlace byte,
|
||||
) ([]pngPass, error) {
|
||||
if compression != 0 || filter != 0 {
|
||||
return nil, corruptf(
|
||||
"png compression/filter method %d/%d", compression, filter,
|
||||
)
|
||||
}
|
||||
|
||||
var bitsPerPixel int64
|
||||
|
||||
switch colorType {
|
||||
case 0: // grayscale
|
||||
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 0", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 2: // truecolor
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 2", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 3 * int64(bitDepth)
|
||||
case 3: // palette
|
||||
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 3", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 4: // grayscale + alpha
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 4", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 2 * int64(bitDepth)
|
||||
case 6: // RGBA
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 6", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 4 * int64(bitDepth)
|
||||
default:
|
||||
return nil, corruptf("png invalid color type %d", colorType)
|
||||
}
|
||||
|
||||
specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}}
|
||||
switch interlace {
|
||||
case 0:
|
||||
case 1:
|
||||
specs = adam7Passes
|
||||
default:
|
||||
return nil, corruptf("png invalid interlace method %d", interlace)
|
||||
}
|
||||
|
||||
passes := make([]pngPass, 0, len(specs))
|
||||
|
||||
for _, spec := range specs {
|
||||
if info.Width <= spec.x0 || info.Height <= spec.y0 {
|
||||
continue
|
||||
}
|
||||
|
||||
width := (info.Width - spec.x0 + spec.dx - 1) / spec.dx
|
||||
rows := (info.Height - spec.y0 + spec.dy - 1) / spec.dy
|
||||
rowBytes := (width*bitsPerPixel + 7) / 8
|
||||
|
||||
// Keep the total overflow-safe. Valid PNGs are additionally bounded
|
||||
// by the pixel limit checked by the caller.
|
||||
if rowBytes+1 > (1<<62)/rows {
|
||||
return nil, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
|
||||
}
|
||||
|
||||
passes = append(passes, pngPass{rowBytes: rowBytes, rows: rows})
|
||||
}
|
||||
|
||||
return passes, nil
|
||||
}
|
||||
|
||||
func pngRasterBytes(passes []pngPass) int64 {
|
||||
var total int64
|
||||
|
||||
for _, pass := range passes {
|
||||
row := (pass.rowBytes + 1) * pass.rows
|
||||
if total > (1<<62)-row {
|
||||
return 1<<62 - 1
|
||||
}
|
||||
|
||||
total += row
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
// validateRaster streams the inflated image data, checking every scanline
|
||||
// filter byte and requiring exactly the IHDR-declared number of rows. It
|
||||
// catches zlib streams that decompress cleanly but do not describe a valid
|
||||
// raster (empty payloads, bogus filter bytes) and rejects extra data as a
|
||||
// decompression bomb.
|
||||
func validateRaster(compressed []byte, passes []pngPass) error {
|
||||
source := bytes.NewReader(compressed)
|
||||
|
||||
reader, err := zlib.NewReader(source)
|
||||
if err != nil {
|
||||
return corrupt("png idat zlib header", err)
|
||||
}
|
||||
|
||||
for _, pass := range passes {
|
||||
for range pass.rows {
|
||||
var filter [1]byte
|
||||
if _, err := io.ReadFull(reader, filter[:]); err != nil {
|
||||
return corrupt("png scanline filter", err)
|
||||
}
|
||||
|
||||
if filter[0] > 4 {
|
||||
return corruptf("png invalid scanline filter %d", filter[0])
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(io.Discard, reader, pass.rowBytes); err != nil {
|
||||
return corrupt("png scanline data", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var extra [1]byte
|
||||
switch _, err := io.ReadFull(reader, extra[:]); {
|
||||
case errors.Is(err, io.EOF):
|
||||
// A clean zlib EOF also verifies the Adler-32 trailer. bytes.Reader
|
||||
// satisfies io.ByteReader, so the inflater consumes exactly the zlib
|
||||
// stream; anything left is data after the stream, which PNG forbids.
|
||||
if source.Len() != 0 {
|
||||
return corruptf("png idat has %d trailing bytes", source.Len())
|
||||
}
|
||||
|
||||
return nil
|
||||
case err == nil:
|
||||
return fmt.Errorf("%w: png raster exceeds declared dimensions", ErrTooLarge)
|
||||
default:
|
||||
return corrupt("png idat zlib trailer", err)
|
||||
}
|
||||
}
|
||||
|
||||
func checkCriticalChunk(chunkType string, seen map[string]bool) error {
|
||||
if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" {
|
||||
seen[chunkType] = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -176,7 +471,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 +479,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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user