lab5: закрытие остаточных замечаний

Validate tRNS semantics and bind PLTE entry count to the IHDR bit depth so malformed PNGs are rejected with 415 instead of failing in the worker. Refuse replay of an older failed version while a newer pipeline job exists, preventing loss of the shared staging source, and retire version-stale queued jobs as superseded instead of republishing them forever.
This commit is contained in:
Vladislav Kunetskiy
2026-10-31 01:46:26 +03:00
parent 624f76b7d0
commit ac30972d48
14 changed files with 357 additions and 33 deletions
+44
View File
@@ -82,7 +82,9 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
first = true
hasIDAT bool
paletteReady bool
trnsSeen bool
colorType byte
bitDepth byte
idat bytes.Buffer
raster []pngPass
rasterBytes int64
@@ -166,6 +168,7 @@ 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)
@@ -201,9 +204,50 @@ func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
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")
}
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)
}
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)
+94
View File
@@ -318,6 +318,100 @@ func TestValidateAcceptsStandardEncodings(t *testing.T) {
}
}
func TestValidateRejectsPNGPLTEEntriesExceedBitDepth(t *testing.T) {
data := pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0, 0, 0, 255}),
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 TestValidateRejectsInvalidTRNS(t *testing.T) {
rgb := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30}))
gray := pngChunk("IDAT", zlibBytes(t, []byte{0, 10}))
rgba := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30, 255}))
paletted := pngChunk("IDAT", zlibBytes(t, []byte{0, 0}))
cases := map[string][]byte{
"tRNS on RGBA": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
pngChunk("tRNS", []byte{0}),
rgba,
pngChunk("IEND", nil),
),
"RGB length": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", []byte{0}),
rgb,
pngChunk("IEND", nil),
),
"gray length": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
pngChunk("tRNS", []byte{0}),
gray,
pngChunk("IEND", nil),
),
"palette before PLTE": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
pngChunk("tRNS", []byte{0}),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
paletted,
pngChunk("IEND", nil),
),
"duplicate tRNS": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", make([]byte, 6)),
pngChunk("tRNS", make([]byte, 6)),
rgb,
pngChunk("IEND", nil),
),
"tRNS after IDAT": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
rgb,
pngChunk("tRNS", make([]byte, 6)),
pngChunk("IEND", nil),
),
}
for name, data := range cases {
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.ErrorIs(t, err, imagecheck.ErrCorrupt, name)
}
}
func TestValidateAcceptsValidTRNS(t *testing.T) {
cases := map[string][]byte{
"RGB": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
pngChunk("tRNS", make([]byte, 6)),
pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30})),
pngChunk("IEND", nil),
),
"gray": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
pngChunk("tRNS", make([]byte, 2)),
pngChunk("IDAT", zlibBytes(t, []byte{0, 10})),
pngChunk("IEND", nil),
),
"palette": pngFile(
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
pngChunk("tRNS", []byte{128}),
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
pngChunk("IEND", nil),
),
}
for name, data := range cases {
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
require.NoError(t, err, name)
}
}
// 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) {
@@ -578,6 +578,23 @@ func (r *PipelineRepository) ClaimJob(
switch {
case job.PipelineVersion < attachment.PipelineVersion:
// A queued job left behind by an older version (for example a
// replay accepted before the newer version committed) can never
// make progress. Retire it instead of acknowledging and
// republishing it through reconciliation forever.
if job.Status == domain.JobQueued {
if _, err := tx.Exec(ctx, `
UPDATE attachment_jobs
SET status = 'superseded', updated_at = now(), completed_at = now()
WHERE job_id = $1 AND status = 'queued'`, job.ID); err != nil {
return fmt.Errorf("supersede version-stale job: %w", mapError(err))
}
if err := insertEventTx(ctx, tx, job.ID, domain.EventSuperseded, job.Attempt, ""); err != nil {
return err
}
}
result.Outcome = domain.ClaimVersionStale
return nil
@@ -1455,6 +1472,24 @@ func (r *PipelineRepository) ReplayJob(
return fmt.Errorf("%w: job is superseded by a newer pipeline version", domain.ErrConflict)
}
// A newer version may still be unpublished (attachment.pipeline_version
// changes only when it commits), so compare against job rows too. An
// older replay must not compete with a newer job for the same staging
// source or return the attachment to an older state.
var newerJob bool
if err := tx.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND pipeline_version > $2
)`, job.AttachmentID, job.PipelineVersion).Scan(&newerJob); err != nil {
return fmt.Errorf("check newer pipeline version: %w", mapError(err))
}
if newerJob {
return fmt.Errorf("%w: a newer pipeline version already has a job", domain.ErrConflict)
}
nextAttempt := job.Attempt + 1
_, err = tx.Exec(ctx, `
@@ -413,6 +413,90 @@ func (s *PipelineSuite) TestReplayNewerFailedVersionKeepsReadyServingVersion() {
s.Nil(current.ErrorCode)
}
// Replaying an older failed version is refused while a newer job exists,
// even before that newer version becomes the published serving version.
func (s *PipelineSuite) TestReplayOlderFailedVersionRefusedWhenNewerJobExists() {
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)
failed, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease-1", "invalid_image")
s.Require().NoError(err)
s.True(failed)
reprocessID, err := uuid.NewV7()
s.Require().NoError(err)
_, err = repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
s.Require().NoError(err)
_, err = repo.ReplayJob(s.T().Context(), job.ID, 1)
s.Require().ErrorIs(err, domain.ErrConflict)
var v1Status string
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&v1Status))
s.Equal(string(domain.JobFailed), v1Status)
}
// A queued job for an older version is retired on claim instead of being
// acknowledged and republished by reconciliation forever.
func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() {
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)
variants := []domain.Variant{
{
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
Width: 256, Height: 160, SHA256: strings.Repeat("d", 64),
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
},
}
ok, err := repo.CompleteJob(s.T().Context(), reprocess.ID, 1, "lease-2", variants)
s.Require().NoError(err)
s.True(ok)
// Simulate a legacy/racing replay that left the old version queued.
_, err = s.pool.Exec(s.T().Context(), `
UPDATE attachment_jobs
SET status = 'queued', attempt = 1, last_error_code = NULL
WHERE job_id = $1`, job.ID)
s.Require().NoError(err)
stale, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-3", time.Minute)
s.Require().NoError(err)
s.Equal(domain.ClaimVersionStale, stale.Outcome)
var status string
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status))
s.Equal(string(domain.JobSuperseded), status)
}
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
alice := s.createUser("alice")
chat := s.createChat(alice)