Files
Deluan Quintão 5ca6534a35
Pipeline: Test, Lint, Build / Get version info (push) Waiting to run
Pipeline: Test, Lint, Build / Lint Go code (push) Waiting to run
Pipeline: Test, Lint, Build / Validate DB migrations (push) Waiting to run
Pipeline: Test, Lint, Build / Test Go code (push) Waiting to run
Pipeline: Test, Lint, Build / Test Go plugins (push) Waiting to run
Pipeline: Test, Lint, Build / Test Go code (Windows) (push) Waiting to run
Pipeline: Test, Lint, Build / Test JS code (push) Waiting to run
Pipeline: Test, Lint, Build / Lint i18n files (push) Waiting to run
Pipeline: Test, Lint, Build / Check Docker configuration (push) Waiting to run
fix(server): abort truncated artwork responses and simplify WriteImage (#6572)
2026-11-28 15:11:35 -05:00

257 lines
9.7 KiB
Go

package imghttp_test
import (
"bytes"
"context"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing/fstest"
"testing/iotest"
"time"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/server/imghttp"
"github.com/navidrome/navidrome/utils/cache"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
const testHash = "0123456789abcdef"
const testRepTag = testHash + ".300.false.q75"
var lastMod = time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)
func found() *artwork.Image {
return &artwork.Image{
ReadCloser: io.NopCloser(strings.NewReader("IMG")),
Hash: testHash,
LastUpdated: lastMod,
}
}
func placeholder() *artwork.Image {
return &artwork.Image{ReadCloser: io.NopCloser(strings.NewReader("PH")), Placeholder: true}
}
// A re-encoded response carries a representation ETag distinct from the pixel hash, so the
// validator versions with the encode settings.
func resized() *artwork.Image {
return &artwork.Image{
ReadCloser: io.NopCloser(strings.NewReader("IMG")),
Hash: testHash,
ETag: testRepTag,
LastUpdated: lastMod,
}
}
func unvalidated() *artwork.Image {
return &artwork.Image{ReadCloser: io.NopCloser(strings.NewReader("IMG")), LastUpdated: lastMod}
}
var _ = Describe("WriteImageHeaders", func() {
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
})
type testCase struct {
img *artwork.Image
requestedHash string
ifNoneMatch string
want304 bool
wantCache string
wantETag string
wantLastMod bool
}
DescribeTable("applies the artwork caching contract",
func(c testCase) {
w := httptest.NewRecorder()
r := httptest.NewRequestWithContext(ctx, http.MethodGet, "/img", nil)
if c.ifNoneMatch != "" {
r.Header.Set("If-None-Match", c.ifNoneMatch)
}
Expect(imghttp.WriteImageHeaders(w, r, c.img, c.requestedHash)).To(Equal(c.want304))
h := w.Header()
Expect(h.Get("Cache-Control")).To(Equal(c.wantCache))
Expect(h.Get("ETag")).To(Equal(c.wantETag))
if c.img.Placeholder {
Expect(h.Get("ETag")).To(BeEmpty(), "placeholder must not set an ETag")
Expect(h.Get("Last-Modified")).To(BeEmpty(), "placeholder must not set Last-Modified")
}
if c.wantLastMod {
Expect(h.Get("Last-Modified")).ToNot(BeEmpty())
} else {
Expect(h.Get("Last-Modified")).To(BeEmpty())
}
if c.want304 {
Expect(w.Code).To(Equal(http.StatusNotModified))
Expect(w.Body.Len()).To(BeZero(), "a 304 must have an empty body")
}
},
Entry("placeholder is never cached and carries no validators",
testCase{img: placeholder(), wantCache: "no-store"}),
Entry("found with matching requested hash is immutable",
testCase{img: found(), requestedHash: testHash, wantCache: "public, max-age=31536000, immutable", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("found with bare id revalidates via no-cache",
testCase{img: found(), wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("found with mismatched requested hash revalidates",
testCase{img: found(), requestedHash: "ffffffffffffffff", wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("resized keeps pixel-hash immutable but serves the representation ETag",
testCase{img: resized(), requestedHash: testHash, wantCache: "public, max-age=31536000, immutable", wantETag: `"` + testRepTag + `"`, wantLastMod: true}),
Entry("resized 304s on the representation ETag, not the pixel hash",
testCase{img: resized(), ifNoneMatch: `"` + testRepTag + `"`, want304: true, wantCache: "public, no-cache", wantETag: `"` + testRepTag + `"`, wantLastMod: true}),
Entry("resized does not 304 on a stale pixel-hash validator (config changed)",
testCase{img: resized(), ifNoneMatch: `"` + testHash + `"`, want304: false, wantCache: "public, no-cache", wantETag: `"` + testRepTag + `"`, wantLastMod: true}),
Entry("If-None-Match matching the hash yields 304",
testCase{img: found(), requestedHash: testHash, ifNoneMatch: `"` + testHash + `"`, want304: true, wantCache: "public, max-age=31536000, immutable", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("weak If-None-Match matches (weak comparison)",
testCase{img: found(), ifNoneMatch: `W/"` + testHash + `"`, want304: true, wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("If-None-Match with multiple values matches one",
testCase{img: found(), ifNoneMatch: `"deadbeefdeadbeef", W/"` + testHash + `", "cafecafecafecafe"`, want304: true, wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("If-None-Match star matches any current representation",
testCase{img: found(), ifNoneMatch: "*", want304: true, wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("non-matching If-None-Match serves body",
testCase{img: found(), ifNoneMatch: `"deadbeefdeadbeef"`, want304: false, wantCache: "public, no-cache", wantETag: `"` + testHash + `"`, wantLastMod: true}),
Entry("placeholder ignores If-None-Match and never 304s",
testCase{img: placeholder(), ifNoneMatch: "*", want304: false, wantCache: "no-store"}),
// With no validator, an emitted ETag would be the same empty tag on every such response,
// and matching it would 304 changed bytes.
Entry("omits the ETag entirely when there is no validator",
testCase{img: unvalidated(), wantCache: "public, no-cache", wantLastMod: true}),
Entry("never 304s an empty validator echoed back by the client",
testCase{img: unvalidated(), ifNoneMatch: `""`, want304: false,
wantCache: "public, no-cache", wantLastMod: true}),
)
})
// statFile reports a regular file of the given size while serving r, so a read can fail partway.
type statFile struct {
io.Reader
info fs.FileInfo
}
func newStatFile(size int, r io.Reader) statFile {
info, err := fs.Stat(fstest.MapFS{"cover.jpg": {Data: make([]byte, size)}}, "cover.jpg")
Expect(err).ToNot(HaveOccurred())
return statFile{Reader: r, info: info}
}
func (f statFile) Stat() (fs.FileInfo, error) { return f.info, nil }
func (statFile) Close() error { return nil }
var _ = Describe("WriteImage", func() {
var ctx context.Context
var w *httptest.ResponseRecorder
var r *http.Request
BeforeEach(func() {
ctx = GinkgoT().Context()
w = httptest.NewRecorder()
r = httptest.NewRequestWithContext(ctx, http.MethodGet, "/img", nil)
})
writeImage := func(img *artwork.Image) error {
return imghttp.WriteImage(w, r, img)
}
write := func(rc io.ReadCloser) {
Expect(writeImage(&artwork.Image{ReadCloser: rc})).To(Succeed())
}
It("streams a file of any size with its size as Content-Length", func() {
data := bytes.Repeat([]byte{0xCD}, 5<<20)
path := filepath.Join(GinkgoT().TempDir(), "disc1.png")
Expect(os.WriteFile(path, data, 0600)).To(Succeed())
f, err := os.Open(path)
Expect(err).ToNot(HaveOccurred())
DeferCleanup(f.Close)
write(f)
Expect(w.Result().Header.Get("Content-Length")).To(Equal(strconv.Itoa(len(data))))
Expect(w.Body.Bytes()).To(Equal(data))
})
It("streams an embedded fs file with its size as Content-Length", func() {
f, err := fstest.MapFS{"placeholder.webp": {Data: []byte("PH")}}.Open("placeholder.webp")
Expect(err).ToNot(HaveOccurred())
write(f)
Expect(w.Result().Header.Get("Content-Length")).To(Equal("2"))
Expect(w.Body.String()).To(Equal("PH"))
})
It("streams a cache hit of any size with its size as Content-Length", func() {
data := bytes.Repeat([]byte{0xEF}, 5<<20)
sr := io.NewSectionReader(bytes.NewReader(data), 0, int64(len(data)))
write(&cache.CachedStream{Reader: sr, Seeker: sr, Cached: true})
Expect(w.Result().Header.Get("Content-Length")).To(Equal(strconv.Itoa(len(data))))
Expect(w.Body.Bytes()).To(Equal(data))
})
It("buffers a small image of unknown size to send its Content-Length", func() {
write(io.NopCloser(strings.NewReader("IMG")))
Expect(w.Result().Header.Get("Content-Length")).To(Equal("3"))
Expect(w.Body.String()).To(Equal("IMG"))
})
It("streams a large image of unknown size without Content-Length", func() {
data := bytes.Repeat([]byte{0xAB}, 5<<20)
write(io.NopCloser(bytes.NewReader(data)))
Expect(w.Result().Header.Get("Content-Length")).To(BeEmpty())
Expect(w.Body.Bytes()).To(Equal(data))
})
DescribeTable("aborts the response when the image fails after bytes were sent",
func(rc func() io.ReadCloser) {
Expect(func() { _ = writeImage(&artwork.Image{ReadCloser: rc()}) }).To(PanicWith(http.ErrAbortHandler))
Expect(w.Body.Len()).To(BeNumerically(">", 0))
},
Entry("unknown size, streamed without a Content-Length", func() io.ReadCloser {
return io.NopCloser(io.MultiReader(bytes.NewReader(make([]byte, 5<<20)), iotest.ErrReader(io.ErrUnexpectedEOF)))
}),
Entry("known size", func() io.ReadCloser {
return newStatFile(10, io.MultiReader(bytes.NewReader(make([]byte, 5)), iotest.ErrReader(io.ErrUnexpectedEOF)))
}),
)
DescribeTable("writes nothing and withdraws the caching headers when the image cannot be read",
func(rc func() io.ReadCloser) {
img := found()
img.ReadCloser = rc()
Expect(imghttp.WriteImageHeaders(w, r, img, testHash)).To(BeFalse())
Expect(writeImage(img)).To(MatchError(io.ErrUnexpectedEOF))
h := w.Header()
Expect(h.Get("Content-Length")).To(BeEmpty())
Expect(h.Get("ETag")).To(BeEmpty())
Expect(h.Get("Last-Modified")).To(BeEmpty())
Expect(h.Get("Cache-Control")).To(Equal("no-store"))
Expect(w.Body.Len()).To(BeZero())
},
Entry("unknown size", func() io.ReadCloser {
return io.NopCloser(iotest.ErrReader(io.ErrUnexpectedEOF))
}),
Entry("known size", func() io.ReadCloser {
return newStatFile(10, iotest.ErrReader(io.ErrUnexpectedEOF))
}),
)
})