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:
Vladislav Kunetskiy
2026-10-31 00:41:38 +03:00
parent ecdd91a15b
commit b965350cc9
13 changed files with 311 additions and 44 deletions
+112 -7
View File
@@ -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
}
+33
View File
@@ -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)