fix: harden attachment cleanup
This commit is contained in:
@@ -11,6 +11,7 @@ import (
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -68,7 +69,7 @@ type Service struct {
|
||||
}
|
||||
|
||||
func NewService(logger *slog.Logger, repository Repository, objects ObjectStore, config Config) (*Service, error) {
|
||||
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.CleanupTimeout <= 0 {
|
||||
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.MaxPixels > math.MaxInt64/8 || config.CleanupTimeout <= 0 {
|
||||
return nil, errors.New("invalid attachment service configuration")
|
||||
}
|
||||
if config.BodyMemoryBytes < config.MaxBytes {
|
||||
@@ -207,11 +208,11 @@ func (s *Service) readImage(input Upload) ([]byte, string, func(), error) {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > s.config.MaxPixels {
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || int64(imageConfig.Width) > s.config.MaxPixels/int64(imageConfig.Height) {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
decodeBytes := pixels * 8
|
||||
if !s.decodeMemory.TryAcquire(decodeBytes) {
|
||||
releaseBody()
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -69,6 +70,28 @@ func TestUploadUsesSeparateBodyAndDecodeBudgets(t *testing.T) {
|
||||
service.decodeMemory.Release(32)
|
||||
}
|
||||
|
||||
func TestUploadReleasesBodyMemoryAfterOversizedDimensions(t *testing.T) {
|
||||
oversized := pngFixture(t, 3, 2)
|
||||
valid := pngFixture(t, 2, 2)
|
||||
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
|
||||
|
||||
_, err := service.Upload(context.Background(), upload(oversized, "image/png"))
|
||||
require.ErrorIs(t, err, model.ErrPayloadTooLarge)
|
||||
_, err = service.Upload(context.Background(), upload(valid, "image/png"))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestNewServiceRejectsDecodeBudgetOverflow(t *testing.T) {
|
||||
_, err := NewService(
|
||||
slog.New(slog.NewTextHandler(io.Discard, nil)), &repositoryStub{}, &objectStub{},
|
||||
Config{
|
||||
MaxBytes: 1024, MaxPixels: math.MaxInt64/8 + 1, BodyMemoryBytes: 1024,
|
||||
DecodeMemoryBytes: math.MaxInt64, CleanupTimeout: time.Second,
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestUploadCleansPendingMetadataWhenObjectWriteFails(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
repository := &repositoryStub{}
|
||||
|
||||
Reference in New Issue
Block a user