diff --git a/conf/configuration.go b/conf/configuration.go index 8d0c0bcd9..4057c147c 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -144,6 +144,7 @@ type Options struct { DevUIShowConfig bool DevNewEventStream bool DevOffsetOptimize int + DevMaxPlaylistTracksPerRequest int DevArtworkMaxRequests int DevArtworkThrottleBacklogLimit int DevArtworkThrottleBacklogTimeout time.Duration @@ -1120,6 +1121,7 @@ func setViperDefaults() { viper.SetDefault("devneweventstream", true) viper.SetDefault("devapiv1", false) viper.SetDefault("devoffsetoptimize", 50000) + viper.SetDefault("devmaxplaylisttracksperrequest", 50000) // Half the pool: streams may take up to this many connections, leaving the rest for the scanner, // scrobbles and the UI. See MaxOpenConns. viper.SetDefault("jellyfin.maxconcurrentstreams", max(2, MaxOpenConns()/2)) diff --git a/core/playlists/import.go b/core/playlists/import.go index 491641a4e..427f7de8d 100644 --- a/core/playlists/import.go +++ b/core/playlists/import.go @@ -113,10 +113,7 @@ func (s *playlists) importFromFolder(ctx context.Context, folder *model.Folder, // noEntryLimit is passed to parseM3U for on-disk playlists. const noEntryLimit = 0 -// MaxImportM3UEntries caps uploads only: on-disk playlists in the scanner can legitimately be larger. -const MaxImportM3UEntries = 50_000 - -// ErrTooManyEntries is returned by ImportM3U when the playlist has more than MaxImportM3UEntries entries. +// ErrTooManyEntries is returned by ImportM3U when the playlist has more than MaxTracksPerRequest entries. var ErrTooManyEntries = errors.New("playlist has too many entries") // importM3USlot runs one upload import at a time, so concurrent uploads cannot stack their memory use. @@ -150,7 +147,8 @@ func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Pla Sync: false, } body := &errReader{r: reader} - err := s.parseM3U(ctx, pls, nil, body, MaxImportM3UEntries) + // Uploads only: on-disk playlists in the scanner can legitimately be larger. + err := s.parseM3U(ctx, pls, nil, body, MaxTracksPerRequest()) if err == nil { err = body.err } diff --git a/core/playlists/import_test.go b/core/playlists/import_test.go index f2bc81a96..b4052ddde 100644 --- a/core/playlists/import_test.go +++ b/core/playlists/import_test.go @@ -1004,32 +1004,40 @@ var _ = Describe("Playlists - Import", func() { } BeforeEach(func() { repo.data = []string{"tests/test.mp3"} + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 3 }) }) - It("imports a playlist with exactly the maximum number of entries, duplicates included", func() { - pls, err := ps.ImportM3U(ctx, strings.NewReader(repeat(playlists.MaxImportM3UEntries))) + It("imports a playlist with exactly DevMaxPlaylistTracksPerRequest entries, duplicates included", func() { + pls, err := ps.ImportM3U(ctx, strings.NewReader(repeat(3))) Expect(err).ToNot(HaveOccurred()) - Expect(pls.Tracks).To(HaveLen(playlists.MaxImportM3UEntries)) + Expect(pls.Tracks).To(HaveLen(3)) }) - It("rejects a playlist over the maximum without saving it", func() { - _, err := ps.ImportM3U(ctx, strings.NewReader(repeat(playlists.MaxImportM3UEntries+1))) + It("rejects a playlist over the limit without saving it", func() { + _, err := ps.ImportM3U(ctx, strings.NewReader(repeat(4))) Expect(err).To(MatchError(playlists.ErrTooManyEntries)) Expect(mockPlsRepo.Last).To(BeNil()) }) + It("imports any number of entries when the limit is 0", func() { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 0 }) + pls, err := ps.ImportM3U(ctx, strings.NewReader(repeat(4))) + Expect(err).ToNot(HaveOccurred()) + Expect(pls.Tracks).To(HaveLen(4)) + }) + It("does not cap playlists imported from disk", func() { tmpDir := GinkgoT().TempDir() libDir := filepath.Join(tmpDir, "music") Expect(os.Mkdir(libDir, 0755)).To(Succeed()) mockLibRepo.SetData([]model.Library{{ID: 1, Path: libDir}}) plsFile := filepath.Join(tmpDir, "big.m3u") - content := strings.Repeat(libDir+"/tests/test.mp3\n", playlists.MaxImportM3UEntries+1) + content := strings.Repeat(libDir+"/tests/test.mp3\n", 4) Expect(os.WriteFile(plsFile, []byte(content), 0600)).To(Succeed()) pls, err := ps.ImportFile(ctx, plsFile, false) Expect(err).ToNot(HaveOccurred()) - Expect(pls.Tracks).To(HaveLen(playlists.MaxImportM3UEntries + 1)) + Expect(pls.Tracks).To(HaveLen(4)) }) }) diff --git a/core/playlists/playlists.go b/core/playlists/playlists.go index 301bbd3b1..10068c1ac 100644 --- a/core/playlists/playlists.go +++ b/core/playlists/playlists.go @@ -17,6 +17,18 @@ import ( "github.com/navidrome/navidrome/model/request" ) +// MaxTracksPerRequest is how many tracks one API request may add or set; 0 means no limit. +// Native album, artist and disc ids are not counted: their expansion is bounded by the library size. +func MaxTracksPerRequest() int { + return max(conf.Server().DevMaxPlaylistTracksPerRequest, 0) +} + +// TooManyTracks reports whether n tracks exceed MaxTracksPerRequest. +func TooManyTracks(n int) bool { + limit := MaxTracksPerRequest() + return limit > 0 && n > limit +} + type Playlists interface { // Reads GetAll(ctx context.Context, options ...model.QueryOptions) (model.Playlists, error) diff --git a/server/jellyfin/annotations.go b/server/jellyfin/annotations.go index 1bb0b7846..49a5785ca 100644 --- a/server/jellyfin/annotations.go +++ b/server/jellyfin/annotations.go @@ -1,9 +1,7 @@ package jellyfin import ( - "encoding/json" "errors" - "io" "net/http" "strconv" @@ -167,8 +165,12 @@ func (api *Router) removeRating(w http.ResponseWriter, r *http.Request) { // updateUserItemData writes Rating, Likes and IsFavorite; omitted or null fields are left untouched. // Play state is ignored because it only changes through playback reporting. func (api *Router) updateUserItemData(w http.ResponseWriter, r *http.Request) { - body, ok := decodeUserDataBody(w, r) - if !ok { + var body *dto.UpdateUserItemDataDto + if !decodeJSONBody(w, r, maxUserDataBody, &body) { + return + } + if body == nil { + http.Error(w, "Bad Request", http.StatusBadRequest) return } change := userDataChange{favorite: body.IsFavorite} @@ -188,17 +190,3 @@ func (api *Router) updateUserItemData(w http.ResponseWriter, r *http.Request) { } const maxUserDataBody = 64 << 10 - -// decodeUserDataBody accepts exactly one JSON object; Decode alone would ignore anything after it. -func decodeUserDataBody(w http.ResponseWriter, r *http.Request) (*dto.UpdateUserItemDataDto, bool) { - dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUserDataBody)) - var body *dto.UpdateUserItemDataDto - err := dec.Decode(&body) - if err == nil && body != nil { - if _, err = dec.Token(); errors.Is(err, io.EOF) { - return body, true - } - } - http.Error(w, "Bad Request", http.StatusBadRequest) - return nil, false -} diff --git a/server/jellyfin/annotations_test.go b/server/jellyfin/annotations_test.go index f6a52a9c5..f00a4f56d 100644 --- a/server/jellyfin/annotations_test.go +++ b/server/jellyfin/annotations_test.go @@ -506,7 +506,7 @@ var _ = Describe("Annotations", func() { It("rejects a body larger than the limit", func() { mfRepo := songWith(model.Annotations{Rating: 4}) big := `{"Rating":8,"Pad":"` + strings.Repeat("x", 70<<10) + `"}` - Expect(post(big).Code).To(Equal(http.StatusBadRequest)) + Expect(post(big).Code).To(Equal(http.StatusRequestEntityTooLarge)) Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) }) diff --git a/server/jellyfin/api.go b/server/jellyfin/api.go index 9d28423e0..4be0aac0e 100644 --- a/server/jellyfin/api.go +++ b/server/jellyfin/api.go @@ -2,6 +2,8 @@ package jellyfin import ( "encoding/json" + "errors" + "io" "net/http" "github.com/go-chi/chi/v5" @@ -260,3 +262,21 @@ func (api *Router) internalError(w http.ResponseWriter, r *http.Request, err err log.Error(r.Context(), "Jellyfin API: internal error", "method", r.Method, "path", r.URL.Path, err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) } + +// decodeJSONBody decodes exactly one JSON value of at most limit bytes into v, answering 413 or 400 itself on failure. +func decodeJSONBody(w http.ResponseWriter, r *http.Request, limit int64, v any) bool { + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit)) + err := dec.Decode(v) + if err == nil { + // Decode alone would ignore anything after the first value. + if _, err = dec.Token(); errors.Is(err, io.EOF) { + return true + } + } + if errors.As(err, new(*http.MaxBytesError)) { + http.Error(w, "Request Entity Too Large", http.StatusRequestEntityTooLarge) + } else { + http.Error(w, "Bad Request", http.StatusBadRequest) + } + return false +} diff --git a/server/jellyfin/api_test.go b/server/jellyfin/api_test.go index 99f56d655..2fffe78ea 100644 --- a/server/jellyfin/api_test.go +++ b/server/jellyfin/api_test.go @@ -145,3 +145,40 @@ var _ = Describe("Router", func() { Expect(login("203.0.113.2")).To(Equal(http.StatusUnauthorized)) }) }) + +var _ = Describe("decodeJSONBody", func() { + type payload struct { + Name string `json:"Name"` + } + decode := func(body string, limit int64) (*httptest.ResponseRecorder, payload, bool) { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + var v payload + ok := decodeJSONBody(w, r, limit, &v) + return w, v, ok + } + + It("decodes one JSON value, allowing trailing whitespace", func() { + _, v, ok := decode("{\"Name\":\"Mix\"}\r\n\t ", 1024) + Expect(ok).To(BeTrue()) + Expect(v.Name).To(Equal("Mix")) + }) + + DescribeTable("answers 400 for a body that is not exactly one JSON value", + func(body string) { + w, _, ok := decode(body, 1024) + Expect(ok).To(BeFalse()) + Expect(w.Code).To(Equal(http.StatusBadRequest)) + }, + Entry("empty body", ""), + Entry("malformed JSON", `{"Name":`), + Entry("trailing garbage", `{"Name":"Mix"} x`), + Entry("a second JSON value", `{"Name":"Mix"}{"Name":"Other"}`), + ) + + It("answers 413 for a body over the limit", func() { + w, _, ok := decode(`{"Name":"`+strings.Repeat("x", 64)+`"}`, 32) + Expect(ok).To(BeFalse()) + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + }) +}) diff --git a/server/jellyfin/playlists.go b/server/jellyfin/playlists.go index 34bf895cb..259e64873 100644 --- a/server/jellyfin/playlists.go +++ b/server/jellyfin/playlists.go @@ -2,7 +2,6 @@ package jellyfin import ( "context" - "encoding/json" "errors" "math" "net/http" @@ -10,6 +9,7 @@ import ( "strings" "github.com/go-chi/chi/v5" + "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -44,6 +44,28 @@ func (api *Router) playlistError(w http.ResponseWriter, r *http.Request, err err } } +// maxPlaylistBody fits the default track limit's GUIDs (about 1.7 MiB) with room to spare. +const maxPlaylistBody = 2 << 20 + +// resolvePlaylistIDs decodes and expands client ids into track ids, answering 413 or 404 itself on failure. +func (api *Router) resolvePlaylistIDs(w http.ResponseWriter, r *http.Request, guids []string) ([]string, bool) { + // Only an empty album or artist yields no track, so too many ids fail here, before any lookup. + if playlists.TooManyTracks(len(guids)) { + http.Error(w, "Request Entity Too Large", http.StatusRequestEntityTooLarge) + return nil, false + } + decoded, ok := dto.DecodeIDs(guids) + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return nil, false + } + ids, ok := api.expandContainerIDs(r.Context(), decoded) + if !ok { + http.Error(w, "Request Entity Too Large", http.StatusRequestEntityTooLarge) + } + return ids, ok +} + type createPlaylistRequest struct { Name string `json:"Name"` Ids []string `json:"Ids"` @@ -55,16 +77,13 @@ type createPlaylistRequest struct { // replace an existing one), owned by the authenticated user. func (api *Router) createPlaylist(w http.ResponseWriter, r *http.Request) { var body createPlaylistRequest - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - http.Error(w, "Bad Request", http.StatusBadRequest) + if !decodeJSONBody(w, r, maxPlaylistBody, &body) { return } - decoded, ok := dto.DecodeIDs(body.Ids) + ids, ok := api.resolvePlaylistIDs(w, r, body.Ids) if !ok { - http.Error(w, "Not Found", http.StatusNotFound) return } - ids := api.expandContainerIDs(r.Context(), decoded) id, err := api.playlists.Create(r.Context(), "", body.Name, ids) if err != nil { api.internalError(w, r, err) @@ -95,8 +114,7 @@ func (api *Router) updatePlaylist(w http.ResponseWriter, r *http.Request) { return } var body updatePlaylistRequest - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - http.Error(w, "Bad Request", http.StatusBadRequest) + if !decodeJSONBody(w, r, maxPlaylistBody, &body) { return } @@ -109,12 +127,10 @@ func (api *Router) updatePlaylist(w http.ResponseWriter, r *http.Request) { return } } else { - decoded, ok := dto.DecodeIDs(*body.Ids) + ids, ok := api.resolvePlaylistIDs(w, r, *body.Ids) if !ok { - http.Error(w, "Not Found", http.StatusNotFound) return } - ids := api.expandContainerIDs(ctx, decoded) if _, err := api.playlists.Create(ctx, id, "", ids); err != nil { api.playlistError(w, r, err) return @@ -243,27 +259,46 @@ func queryIDs(r *http.Request, key string) []string { // expandContainerIDs expands the container ids (albums, artists, playlists) a client sends when // building a playlist into their track ids, in order, since core/playlists only understands media // file ids. Unknown ids pass through unchanged. Songs are classified with one batched query; only -// the rest pays per-id container probes. -func (api *Router) expandContainerIDs(ctx context.Context, ids []string) []string { +// the rest pays per-id container probes. ok is false once the result exceeds MaxTracksPerRequest. +func (api *Router) expandContainerIDs(ctx context.Context, ids []string) ([]string, bool) { songs := api.songsByIDs(ctx, ids) out := make([]string, 0, len(ids)) + maxTracks := playlists.MaxTracksPerRequest() for _, id := range ids { + // One past the room left, so an oversized container is detected without loading all of it. + limit := 0 + if maxTracks > 0 { + limit = maxTracks - len(out) + 1 + } if _, ok := songs[id]; ok { out = append(out, id) // already a song } else if _, err := api.ds.Album().Get(ctx, id); err == nil { - out = append(out, api.songIDs(ctx, filter.SongsByAlbum(id))...) + out = append(out, api.songIDs(ctx, filter.SongsByAlbum(id), limit)...) } else if _, err := api.ds.Artist().Get(ctx, id); err == nil { - out = append(out, api.songIDs(ctx, filter.SongsByArtistID(id))...) - } else if pl, err := api.playlists.GetWithTracks(ctx, id); err == nil { - out = append(out, slice.Map(pl.Tracks, func(t model.PlaylistTrack) string { return t.MediaFileID })...) + out = append(out, api.songIDs(ctx, filter.SongsByArtistID(id), limit)...) + } else if repo, err := api.playlists.Tracks(ctx, id); err == nil { + out = append(out, playlistSongIDs(ctx, repo, limit)...) } else { out = append(out, id) // well-formed but unresolved — left for the caller's write to handle } + if playlists.TooManyTracks(len(out)) { + return nil, false + } } - return out + return out, true } -func (api *Router) songIDs(ctx context.Context, opts model.QueryOptions) []string { +func playlistSongIDs(ctx context.Context, repo model.PlaylistTrackRepository, limit int) []string { + ids, err := repo.GetMediaFileIDs(ctx, model.QueryOptions{Sort: "id", Filters: notMissing, Max: limit}) + if err != nil { + log.Error(ctx, "Jellyfin: error expanding playlist to tracks", err) + return nil + } + return ids +} + +func (api *Router) songIDs(ctx context.Context, opts model.QueryOptions, limit int) []string { + opts.Max = limit mfs, err := api.ds.MediaFile().GetAll(ctx, opts) if err != nil { log.Error(ctx, "Jellyfin: error expanding container to tracks", err) @@ -280,12 +315,10 @@ func (api *Router) addToPlaylist(w http.ResponseWriter, r *http.Request) { if !ok { return } - decoded, ok := dto.DecodeIDs(queryIDs(r, "ids")) + ids, ok := api.resolvePlaylistIDs(w, r, queryIDs(r, "ids")) if !ok { - http.Error(w, "Not Found", http.StatusNotFound) return } - ids := api.expandContainerIDs(ctx, decoded) var err error if position, perr := req.Params(r).Int64("position"); perr == nil { _, err = api.playlists.InsertTracks(ctx, id, ids, insertPosition(position)) diff --git a/server/jellyfin/playlists_test.go b/server/jellyfin/playlists_test.go index 234453286..b9b75af86 100644 --- a/server/jellyfin/playlists_test.go +++ b/server/jellyfin/playlists_test.go @@ -1,16 +1,21 @@ package jellyfin import ( + "bytes" "context" "encoding/json" "errors" + "fmt" "io" "math" "net/http" "net/http/httptest" + "slices" + "strconv" "strings" "github.com/go-chi/chi/v5" + "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -352,6 +357,141 @@ var _ = Describe("Playlists", func() { }) }) + Describe("request limits", func() { + var ds *tests.MockDataStore + song := dto.EncodeID(testID("s1")) + artist := dto.EncodeID(testID("ar1")) + + BeforeEach(func() { + ds = &tests.MockDataStore{} + api = &Router{ds: ds, playlists: fp} + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}}) + }) + + repeat := func(id string, n int) []string { return slices.Repeat([]string{id}, n) } + // An artist whose expansion alone is just over a per-request track limit of 5. + withHugeArtist := func() { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) + ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1")}}) + songs := make(model.MediaFiles, 6) + for i := range songs { + songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("big-%d", i))} + } + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) + } + create := func(body any) *httptest.ResponseRecorder { + b, err := json.Marshal(body) + Expect(err).ToNot(HaveOccurred()) + w := httptest.NewRecorder() + invoke(api.createPlaylist, w, httptest.NewRequest(http.MethodPost, "/Playlists", bytes.NewReader(b)).WithContext(ctx)) + return w + } + update := func(body any) *httptest.ResponseRecorder { + b, err := json.Marshal(body) + Expect(err).ToNot(HaveOccurred()) + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/Playlists/"+dto.EncodeID(testID("pl1")), bytes.NewReader(b)).WithContext(ctx) + invoke(api.updatePlaylist, w, withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1")))) + return w + } + addItems := func(ids []string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/Playlists/"+dto.EncodeID(testID("pl1"))+"/Items?ids="+strings.Join(ids, ","), nil).WithContext(ctx) + invoke(api.addToPlaylist, w, withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1")))) + return w + } + + DescribeTable("creates a playlist naming up to DevMaxPlaylistTracksPerRequest ids", + func(limit, sent int) { + if limit >= 0 { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = limit }) + } + w := create(map[string]any{"Name": "Mix", "Ids": repeat(song, sent)}) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(fp.createdIds).To(HaveLen(sent)) + }, + Entry("exactly the limit", 5, 5), + Entry("any number when the limit is 0", 0, 6), + Entry("the default limit, in a body larger than 1 MiB", -1, 50_000), + ) + + It("expands without a track limit when DevMaxPlaylistTracksPerRequest is 0", func() { + withHugeArtist() + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 0 }) + w := create(map[string]any{"Name": "Mix", "Ids": []string{artist}}) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(fp.createdIds).To(HaveLen(6)) + }) + + It("asks a playlist container for at most one track past the limit", func() { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) + tracks := make(model.PlaylistTracks, 6) + for i := range tracks { + tracks[i] = model.PlaylistTrack{ID: strconv.Itoa(i + 1), MediaFileID: testID(fmt.Sprintf("pl-%d", i))} + } + fp.getPls = &model.Playlist{ID: testID("pl9"), Tracks: tracks} + + w := create(map[string]any{"Name": "Mix", "Ids": []string{dto.EncodeID(testID("pl9"))}}) + + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(fp.tracksRepo).ToNot(BeNil()) + Expect(fp.tracksRepo.Options.Max).To(Equal(6)) + }) + + It("rejects a create body with data after the JSON object with 400", func() { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/Playlists", strings.NewReader(`{"Name":"Mix"} {"Name":"Other"}`)).WithContext(ctx) + invoke(api.createPlaylist, w, r) + Expect(w.Code).To(Equal(http.StatusBadRequest)) + Expect(fp.createdName).To(BeEmpty()) + }) + + tooManyIDs := func() []string { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) + return repeat(song, 6) + } + expandsTooFar := func() []string { + withHugeArtist() + return []string{artist} + } + withIDs := func(ids func() []string) func() any { + return func() any { return map[string]any{"Name": "Mix", "Ids": ids()} } + } + bodyTooBig := func() any { return map[string]any{"Name": strings.Repeat("x", maxPlaylistBody)} } + + DescribeTable("create and update reject oversized requests with 413 without writing", + func(send func(any) *httptest.ResponseRecorder, body func() any) { + w := send(body()) + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(fp.createdIds).To(BeNil()) + Expect(fp.updatePlaylistID).To(BeEmpty()) + }, + Entry("create, more ids than DevMaxPlaylistTracksPerRequest", create, withIDs(tooManyIDs)), + Entry("create, ids that expand past DevMaxPlaylistTracksPerRequest", create, withIDs(expandsTooFar)), + Entry("create, a body over the size limit", create, bodyTooBig), + Entry("update, more ids than DevMaxPlaylistTracksPerRequest", update, withIDs(tooManyIDs)), + Entry("update, ids that expand past DevMaxPlaylistTracksPerRequest", update, withIDs(expandsTooFar)), + Entry("update, a body over the size limit", update, bodyTooBig), + ) + + It("adds items naming up to DevMaxPlaylistTracksPerRequest ids", func() { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) + w := addItems(repeat(song, 5)) + Expect(w.Code).To(Equal(http.StatusNoContent)) + Expect(fp.addIds).To(HaveLen(5)) + }) + + DescribeTable("adding items rejects oversized requests with 413 without adding", + func(ids func() []string) { + w := addItems(ids()) + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(fp.addPlaylistID).To(BeEmpty()) + }, + Entry("more ids than DevMaxPlaylistTracksPerRequest", tooManyIDs), + Entry("ids that expand past DevMaxPlaylistTracksPerRequest", expandsTooFar), + ) + }) + Describe("getPlaylist", func() { It("returns OpenAccess from Public and item ids (encoded media file ids, not entry ids)", func() { pls := &model.Playlist{ diff --git a/server/nativeapi/native_api.go b/server/nativeapi/native_api.go index 438bc23c6..b6dffc394 100644 --- a/server/nativeapi/native_api.go +++ b/server/nativeapi/native_api.go @@ -2,6 +2,7 @@ package nativeapi import ( "context" + "mime" "net/http" "strconv" "time" @@ -125,9 +126,10 @@ func (api *Router) addPlaylistRoute(r chi.Router) { r.Route("/playlist", func(r chi.Router) { r.Get("/", rest.GetAll(repo)) + createJSON := limitPlaylistJSON(rest.Post(repo)) r.Post("/", func(w http.ResponseWriter, r *http.Request) { - if r.Header.Get("Content-type") == "application/json" { - rest.Post(repo)(w, r) + if mediaType, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mediaType == "application/json" { + createJSON.ServeHTTP(w, r) return } createPlaylistFromM3U(api.playlists)(w, r) @@ -136,7 +138,7 @@ func (api *Router) addPlaylistRoute(r chi.Router) { r.Route("/{id}", func(r chi.Router) { r.Use(server.URLParamsMiddleware) r.Get("/", rest.Get(repo)) - r.Put("/", rest.Put(repo)) + r.With(limitPlaylistJSON).Put("/", rest.Put(repo)) r.Delete("/", rest.Delete(repo)) r.Post("/image", uploadPlaylistImage(api.playlists)) r.Delete("/image", deletePlaylistImage(api.playlists)) diff --git a/server/nativeapi/playlists.go b/server/nativeapi/playlists.go index 5aba07901..40f817c50 100644 --- a/server/nativeapi/playlists.go +++ b/server/nativeapi/playlists.go @@ -1,6 +1,7 @@ package nativeapi import ( + "bytes" "context" "encoding/json" "errors" @@ -35,6 +36,25 @@ func writePlaylistError(w http.ResponseWriter, err error, defaultStatus int) { } } +// maxPlaylistJSONBody fits the default track limit's ids (about 1.3 MiB) with room to spare. +const maxPlaylistJSONBody = 4 << 20 + +// maxContainerIDs keeps album, artist and disc lists under SQLite's variable and expression-depth limits. +const maxContainerIDs = 500 + +// limitPlaylistJSON buffers the body so an oversized one is a 413: deluan/rest answers any read error with 422. +func limitPlaylistJSON(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPlaylistJSONBody)) + if err != nil { + writePlaylistError(w, err, http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + next.ServeHTTP(w, r) + }) +} + func playlistTracksHandler(pls playlists.Playlists, handler func(rest.Repository[model.PlaylistTrack]) http.HandlerFunc, refreshSmartPlaylist func(*http.Request) bool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { plsId := chi.URLParam(r, "playlistId") @@ -64,7 +84,7 @@ func getPlaylistTrack(pls playlists.Playlists) http.HandlerFunc { return playlistTracksHandler(pls, rest.Get[model.PlaylistTrack], func(*http.Request) bool { return true }) } -// maxM3UUploadSize fits playlists.MaxImportM3UEntries entries with long paths and #EXTINF lines. +// maxM3UUploadSize fits the default track limit's entries with long paths and #EXTINF lines. const maxM3UUploadSize = 32 << 20 func createPlaylistFromM3U(pls playlists.Playlists) http.HandlerFunc { @@ -148,9 +168,14 @@ func addToPlaylist(pls playlists.Playlists) http.HandlerFunc { p := req.Params(r) playlistId, _ := p.String(":playlistId") var payload addTracksPayload - err := json.NewDecoder(r.Body).Decode(&payload) + err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxPlaylistJSONBody)).Decode(&payload) if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) + writePlaylistError(w, err, http.StatusBadRequest) + return + } + if playlists.TooManyTracks(len(payload.Ids)) || + len(payload.AlbumIds)+len(payload.ArtistIds)+len(payload.Discs) > maxContainerIDs { + writePlaylistError(w, playlists.ErrTooManyEntries, http.StatusBadRequest) return } count, c := 0, 0 diff --git a/server/nativeapi/playlists_test.go b/server/nativeapi/playlists_test.go index 50d4aa308..693d6c6be 100644 --- a/server/nativeapi/playlists_test.go +++ b/server/nativeapi/playlists_test.go @@ -1,12 +1,15 @@ package nativeapi import ( + "bytes" "context" "encoding/json" "fmt" "io" + "mime/multipart" "net/http" "net/http/httptest" + "path/filepath" "strings" "time" @@ -79,7 +82,7 @@ var _ = Describe("Playlist Tracks Endpoint", func() { c.SessionTimeout = time.Minute }) - plsSvc = &mockPlaylistsService{} + plsSvc = &mockPlaylistsService{repo: &mockPlaylistRestRepo{}} userRepo = tests.CreateMockUserRepo() ds := &tests.MockDataStore{ @@ -104,8 +107,11 @@ var _ = Describe("Playlist Tracks Endpoint", func() { w = httptest.NewRecorder() }) - createAuthenticatedRequest := func(method, path string) *http.Request { - req := httptest.NewRequest(method, path, nil) + createAuthenticatedRequestWithBody := func(method, path string, body io.Reader) *http.Request { + req := httptest.NewRequest(method, path, body) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } testUser := model.User{ID: "user-1", UserName: "testuser"} token, err := auth.CreateToken(&testUser) Expect(err).ToNot(HaveOccurred()) @@ -113,6 +119,115 @@ var _ = Describe("Playlist Tracks Endpoint", func() { return req } + createAuthenticatedRequest := func(method, path string) *http.Request { + return createAuthenticatedRequestWithBody(method, path, nil) + } + + jsonBody := func(v any) io.Reader { + b, err := json.Marshal(v) + Expect(err).ToNot(HaveOccurred()) + return bytes.NewReader(b) + } + + Describe("POST /playlist/{playlistId}/tracks", func() { + DescribeTable("adds ids up to DevMaxPlaylistTracksPerRequest", + func(limit, sent int) { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = limit }) + ids := make([]string, sent) + for i := range ids { + ids[i] = fmt.Sprintf("%022d", i) + } + req := createAuthenticatedRequestWithBody("POST", "/playlist/pls-1/tracks", jsonBody(map[string]any{"ids": ids})) + router.ServeHTTP(w, req) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(plsSvc.addedIds).To(HaveLen(sent)) + }, + Entry("exactly the limit", 5, 5), + Entry("any number when the limit is 0", 0, 6), + ) + + DescribeTable("rejects oversized requests with 413 without adding anything", + func(payload func() any) { + req := createAuthenticatedRequestWithBody("POST", "/playlist/pls-1/tracks", jsonBody(payload())) + router.ServeHTTP(w, req) + + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(plsSvc.addCalls).To(BeZero()) + }, + Entry("more than DevMaxPlaylistTracksPerRequest ids", func() any { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) + return map[string]any{"ids": make([]string, 6)} + }), + Entry("too many album ids", func() any { + return map[string]any{"albumIds": make([]string, maxContainerIDs+1)} + }), + Entry("too many album, artist and disc ids combined", func() any { + return map[string]any{ + "albumIds": make([]string, maxContainerIDs/2), + "artistIds": make([]string, maxContainerIDs/2), + "discs": []model.DiscID{{AlbumID: "al-1", DiscNumber: 1}}, + } + }), + Entry("a body over the size limit", func() any { + return map[string]any{"ids": []string{strings.Repeat("x", maxPlaylistJSONBody)}} + }), + ) + }) + + Describe("POST /playlist", func() { + It("treats JSON with a charset as JSON, not as an M3U upload", func() { + plsSvc.importM3UFn = func(context.Context, io.Reader) (*model.Playlist, error) { return &model.Playlist{}, nil } + req := createAuthenticatedRequestWithBody("POST", "/playlist", jsonBody(map[string]any{"name": "Mix"})) + req.Header.Set("Content-Type", "application/json; charset=utf-8") + router.ServeHTTP(w, req) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(plsSvc.repo.(*mockPlaylistRestRepo).saved).To(HaveExactElements(HaveField("Name", "Mix"))) + }) + + It("rejects a JSON body over the size limit with 413", func() { + body := jsonBody(map[string]any{"name": strings.Repeat("x", maxPlaylistJSONBody)}) + req := createAuthenticatedRequestWithBody("POST", "/playlist", body) + router.ServeHTTP(w, req) + + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(plsSvc.repo.(*mockPlaylistRestRepo).saved).To(BeEmpty()) + }) + }) + + Describe("PUT /playlist/{id}", func() { + It("rejects a JSON body over the size limit with 413", func() { + body := jsonBody(map[string]any{"comment": strings.Repeat("x", maxPlaylistJSONBody)}) + req := createAuthenticatedRequestWithBody("PUT", "/playlist/pls-1", body) + router.ServeHTTP(w, req) + + Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) + Expect(plsSvc.repo.(*mockPlaylistRestRepo).updated).To(BeZero()) + }) + }) + + Describe("POST /playlist/{id}/image", func() { + It("still reads uploads larger than the playlist JSON limit", func() { + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + part, err := mw.CreateFormFile("image", "cover.png") + Expect(err).ToNot(HaveOccurred()) + _, err = part.Write(bytes.Repeat([]byte{0}, maxPlaylistJSONBody+1)) + Expect(err).ToNot(HaveOccurred()) + Expect(mw.Close()).To(Succeed()) + + req := createAuthenticatedRequestWithBody("POST", "/playlist/pls-1/image", &buf) + req.Header.Set("Content-Type", mw.FormDataContentType()) + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = true }) + router.ServeHTTP(w, req) + + // Reaches image decoding: the zero bytes are not an image. + Expect(w.Code).To(Equal(http.StatusBadRequest)) + Expect(w.Body.String()).To(ContainSubstring("invalid image file")) + }) + }) + Describe("GET /playlist/{playlistId}/tracks", func() { It("returns 404 when playlist does not exist", func() { req := createAuthenticatedRequest("GET", "/playlist/non-existent/tracks") @@ -236,7 +351,7 @@ var _ = Describe("createPlaylistFromM3U", func() { w := upload(&mockPlaylistsService{importM3UFn: drainingImport}, strings.NewReader("/music/song.mp3\n")) Expect(w.Code).To(Equal(http.StatusCreated)) - Expect(w.Body.String()).To(ContainSubstring("/music/song.mp3")) + Expect(w.Body.String()).To(ContainSubstring(filepath.FromSlash("/music/song.mp3"))) }) It("rejects a body larger than the upload limit", func() { @@ -291,6 +406,8 @@ type mockPlaylistsService struct { repo rest.Repository[model.Playlist] tracksRepo rest.Repository[model.PlaylistTrack] playlist *model.Playlist + addCalls int + addedIds []string removeImageFn func(ctx context.Context, id string) error setImageFn func(ctx context.Context, id string, reader io.Reader, ext string) error importM3UFn func(ctx context.Context, reader io.Reader) (*model.Playlist, error) @@ -328,3 +445,56 @@ func (m *mockPlaylistsService) GetWithTracks(_ context.Context, _ string) (*mode func (m *mockPlaylistsService) TracksRepository(_ context.Context, _ string, _ bool) rest.Repository[model.PlaylistTrack] { return m.tracksRepo } + +func (m *mockPlaylistsService) AddTracks(_ context.Context, _ string, ids []string) (int, error) { + m.addCalls++ + m.addedIds = append(m.addedIds, ids...) + return len(ids), nil +} + +func (m *mockPlaylistsService) AddAlbums(_ context.Context, _ string, ids []string) (int, error) { + m.addCalls++ + return len(ids), nil +} + +func (m *mockPlaylistsService) AddArtists(_ context.Context, _ string, ids []string) (int, error) { + m.addCalls++ + return len(ids), nil +} + +func (m *mockPlaylistsService) AddDiscs(_ context.Context, _ string, discs []model.DiscID) (int, error) { + m.addCalls++ + return len(discs), nil +} + +// mockPlaylistRestRepo records what rest.Post and rest.Put hand to the playlist repository. +type mockPlaylistRestRepo struct { + saved []model.Playlist + updated int +} + +func (m *mockPlaylistRestRepo) Count(context.Context, ...rest.QueryOptions) (int64, error) { + return 0, nil +} + +func (m *mockPlaylistRestRepo) Read(_ context.Context, id string) (*model.Playlist, error) { + return &model.Playlist{ID: id}, nil +} + +func (m *mockPlaylistRestRepo) ReadAll(context.Context, ...rest.QueryOptions) ([]model.Playlist, error) { + return nil, nil +} + +func (m *mockPlaylistRestRepo) Save(_ context.Context, entity *model.Playlist) (string, error) { + m.saved = append(m.saved, *entity) + return "new-id", nil +} + +func (m *mockPlaylistRestRepo) Update(context.Context, string, model.Playlist, ...string) error { + m.updated++ + return nil +} + +func (m *mockPlaylistRestRepo) Delete(context.Context, ...string) error { + return nil +} diff --git a/server/subsonic/playlists.go b/server/subsonic/playlists.go index 9b0ddf45c..b6eaa2c7c 100644 --- a/server/subsonic/playlists.go +++ b/server/subsonic/playlists.go @@ -7,6 +7,7 @@ import ( "net/http" "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -62,6 +63,9 @@ func (api *Router) CreatePlaylist(r *http.Request) (*responses.Subsonic, error) ctx := r.Context() p := req.Params(r) songIds := p.Strings("songId") + if err := checkTrackCount(songIds); err != nil { + return nil, err + } playlistId, _ := p.String("playlistId") name, _ := p.String("name") if playlistId == "" && name == "" { @@ -99,6 +103,9 @@ func (api *Router) UpdatePlaylist(r *http.Request) (*responses.Subsonic, error) return nil, err } songsToAdd := p.Strings("songIdToAdd") + if err := checkTrackCount(songsToAdd); err != nil { + return nil, err + } songIndexesToRemove, _ := p.Ints("songIndexToRemove") var plsName *string if s, err := p.String("name"); err == nil { @@ -125,6 +132,13 @@ func (api *Router) UpdatePlaylist(r *http.Request) (*responses.Subsonic, error) return newResponse(), nil } +func checkTrackCount(ids []string) error { + if playlists.TooManyTracks(len(ids)) { + return newError(responses.ErrorGeneric, "too many songs in one request (limit is %d)", playlists.MaxTracksPerRequest()) + } + return nil +} + func (api *Router) buildPlaylist(ctx context.Context, p model.Playlist) responses.Playlist { pls := responses.Playlist{} pls.Id = p.ID diff --git a/server/subsonic/playlists_test.go b/server/subsonic/playlists_test.go index 13711ff34..808dbe897 100644 --- a/server/subsonic/playlists_test.go +++ b/server/subsonic/playlists_test.go @@ -3,6 +3,8 @@ package subsonic import ( "context" "encoding/json" + "errors" + "slices" "time" "github.com/navidrome/navidrome/conf" @@ -10,6 +12,7 @@ import ( "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/server/subsonic/responses" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -378,8 +381,51 @@ var _ = Describe("UpdatePlaylist", func() { }) }) +var _ = Describe("playlist track limit", func() { + var router *Router + var fp *fakePlaylists + + BeforeEach(func() { + fp = &fakePlaylists{} + router = New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, fp, nil, nil, nil, nil, nil, nil, nil) + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 3 }) + }) + + songParams := func(param string, n int) []string { return slices.Repeat([]string{param + "=s1"}, n) } + expectGenericError := func(err error) { + var subErr subError + Expect(errors.As(err, &subErr)).To(BeTrue()) + Expect(subErr.code).To(Equal(responses.ErrorGeneric)) + } + + DescribeTable("creates a playlist with up to DevMaxPlaylistTracksPerRequest songs", + func(limit, sent int) { + conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = limit }) + _, err := router.CreatePlaylist(newGetRequest(append([]string{"name=Mix"}, songParams("songId", sent)...)...)) + Expect(err).ToNot(HaveOccurred()) + Expect(fp.lastCreate).To(HaveLen(sent)) + }, + Entry("exactly the limit", 3, 3), + Entry("any number when the limit is 0", 0, 4), + ) + + It("rejects createPlaylist with more songs than the limit, with error code 0", func() { + _, err := router.CreatePlaylist(newGetRequest(append([]string{"name=Mix"}, songParams("songId", 4)...)...)) + expectGenericError(err) + Expect(fp.createCalled).To(BeFalse()) + }) + + It("rejects updatePlaylist adding more songs than the limit, with error code 0", func() { + _, err := router.UpdatePlaylist(newGetRequest(append([]string{"playlistId=123"}, songParams("songIdToAdd", 4)...)...)) + expectGenericError(err) + Expect(fp.lastPlaylistID).To(BeEmpty()) + }) +}) + type fakePlaylists struct { playlists.Playlists + createCalled bool + lastCreate []string lastPlaylistID string lastName *string lastComment *string @@ -388,6 +434,16 @@ type fakePlaylists struct { lastRemove []int } +func (f *fakePlaylists) Create(_ context.Context, _ string, _ string, ids []string) (string, error) { + f.createCalled = true + f.lastCreate = ids + return "new-id", nil +} + +func (f *fakePlaylists) GetWithTracks(_ context.Context, id string) (*model.Playlist, error) { + return &model.Playlist{ID: id}, nil +} + func (f *fakePlaylists) Update(ctx context.Context, playlistID string, name *string, comment *string, public *bool, idsToAdd []string, idxToRemove []int) error { f.lastPlaylistID = playlistID f.lastName = name