lab5: завершение второго ревью
PNG: validate color-type/bit-depth pairs, reject duplicate IHDR/PLTE, non-consecutive IDAT, PLTE after IDAT, and trailing bytes after the zlib stream; keep accepting valid palette, split-IDAT, 16-bit, and Adam7 uploads. Replay: a newer failed unpublished version returns the attachment to queued, while a published ready version stays serving.
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user