navidrome/server/public/handle_streams_test.go
Deluan Quintão fa138afea5
Some checks are pending
Pipeline: Test, Lint, Build / Test Go code (push) Waiting to run
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 / 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
Pipeline: Test, Lint, Build / Build (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-1 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-2 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-3 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-4 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-5 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Package/Release (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-6 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-7 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-8 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-9 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Upload Linux PKG (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build-10 (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Push to GHCR (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Push to Docker Hub (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Cleanup digest artifacts (push) Blocked by required conditions
Pipeline: Test, Lint, Build / Build Windows installers (push) Blocked by required conditions
fix(playlist/share): apply user library access to import and sharing paths (#5640)
* fix(playlist): respect the user's library access when resolving M3U paths

FindByPaths looked up paths across all libraries, so importing an M3U
could add tracks from libraries the importing user has no access to.
Apply the user's library filter to the lookup, matching every other
media_file read. Admins and the (admin-context) scanner are unaffected.

* fix(share): scope shared playlist tracks to the owner's libraries

loadMedia loaded playlist tracks with a fake-admin context, so a shared
playlist could include tracks from libraries the owner has no access to.
Load as the share owner instead, so the library filter applies.
Admin-owned shares are unchanged.

* fix(share): only serve shared tracks the owner can access

A shared stream fetched the media file by id without checking the share
owner's library access, so it could serve tracks from libraries the
owner has no access to. Gate share-scoped streams on the owner's library
access. Non-share streams are unaffected.

* test(share): tidy library-access test setup

Consolidate the repeated share-owner test fixture in handleStream into a
helper, assert on track fields with HaveField instead of building an id
slice, and delete the scratch media file through the public repository
method.

* style: trim verbose comments in library-access checks

* fix(share): guard against nil owner and clean up test users

Add a nil check after loading the share owner so a missing user yields a
clear error instead of a possible nil dereference, and delete the users
created by the new tests in their AfterEach blocks.

* fix(share): avoid panic when a shared playlist is no longer visible to its owner

Tracks() returns nil when the playlist can't be loaded under the owner's
context (e.g. a public playlist shared by a non-owner that was later made
private). Capture the result and return early instead of chaining GetAll
on a nil repository, leaving the share with no tracks.
2026-06-23 18:53:51 -04:00

232 lines
7.6 KiB
Go

package public
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"time"
"github.com/go-chi/jwtauth/v5"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type mockStreamer struct {
req stream.Request
called bool
}
func (m *mockStreamer) NewStream(_ context.Context, _ *model.MediaFile, r stream.Request) (*stream.Stream, error) {
m.called = true
m.req = r
return nil, errors.New("mock: not implemented")
}
var _ = Describe("decodeStreamInfo", func() {
BeforeEach(func() {
auth.TokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil)
})
It("decodes a valid token with all fields", func() {
claims := auth.Claims{ID: "mf-123", Format: "mp3", BitRate: 192, ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
info, err := decodeStreamInfo(token)
Expect(err).NotTo(HaveOccurred())
Expect(info.id).To(Equal("mf-123"))
Expect(info.format).To(Equal("mp3"))
Expect(info.bitrate).To(Equal(192))
Expect(info.shareID).To(Equal("share123"))
})
It("rejects an expired token", func() {
claims := auth.Claims{ID: "mf-123", ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(-time.Hour), claims)
_, err := decodeStreamInfo(token)
Expect(err).To(HaveOccurred())
})
It("accepts a token without exp (non-expiring share)", func() {
claims := auth.Claims{ID: "mf-123", ShareID: "share123"}
token, _ := auth.CreatePublicToken(claims)
info, err := decodeStreamInfo(token)
Expect(err).NotTo(HaveOccurred())
Expect(info.id).To(Equal("mf-123"))
Expect(info.shareID).To(Equal("share123"))
})
It("rejects a token without an id claim", func() {
claims := auth.Claims{ShareID: "share123"}
token, _ := auth.CreatePublicToken(claims)
_, err := decodeStreamInfo(token)
Expect(err).To(HaveOccurred())
})
It("rejects an invalid token string", func() {
_, err := decodeStreamInfo("not-a-valid-token")
Expect(err).To(HaveOccurred())
})
It("handles tokens without shareID (backward compat)", func() {
claims := auth.Claims{ID: "mf-123", Format: "opus"}
token, _ := auth.CreatePublicToken(claims)
info, err := decodeStreamInfo(token)
Expect(err).NotTo(HaveOccurred())
Expect(info.id).To(Equal("mf-123"))
Expect(info.format).To(Equal("opus"))
Expect(info.shareID).To(BeEmpty())
})
})
var _ = Describe("encodeMediafileShare", func() {
BeforeEach(func() {
auth.TokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil)
})
It("includes the share ID in the token", func() {
exp := new(time.Now().Add(time.Hour))
s := model.Share{ID: "shareABC", Format: "mp3", MaxBitRate: 320, ExpiresAt: exp}
token := encodeMediafileShare(s, "mf-999")
info, err := decodeStreamInfo(token)
Expect(err).NotTo(HaveOccurred())
Expect(info.shareID).To(Equal("shareABC"))
Expect(info.id).To(Equal("mf-999"))
Expect(info.format).To(Equal("mp3"))
Expect(info.bitrate).To(Equal(320))
})
It("creates a non-expiring token when share has no expiry", func() {
s := model.Share{ID: "shareXYZ", ExpiresAt: nil}
token := encodeMediafileShare(s, "mf-111")
info, err := decodeStreamInfo(token)
Expect(err).NotTo(HaveOccurred())
Expect(info.shareID).To(Equal("shareXYZ"))
Expect(info.id).To(Equal("mf-111"))
})
})
var _ = Describe("handleStream", func() {
var ds *tests.MockDataStore
var shareRepo *tests.MockShareRepo
var streamer *mockStreamer
var pub *Router
BeforeEach(func() {
auth.TokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil)
ds = &tests.MockDataStore{}
shareRepo = &tests.MockShareRepo{}
ds.MockedShare = shareRepo
streamer = &mockStreamer{}
pub = &Router{ds: ds, streamer: streamer}
})
makeRequest := func(token string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/public/s/token?%3Aid="+token, nil)
w := httptest.NewRecorder()
pub.handleStream(w, r)
return w
}
shareOwnedBy := func(owner model.User, mf model.MediaFile) {
shareRepo.ID = "share123"
shareRepo.Entity = &model.Share{ID: "share123", UserID: owner.ID}
userRepo := tests.CreateMockUserRepo()
Expect(userRepo.Put(&owner)).To(Succeed())
ds.MockedUser = userRepo
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{mf})
ds.MockedMediaFile = mfRepo
}
It("passes all validation and reaches the streamer for a valid token", func() {
shareOwnedBy(
model.User{ID: "owner1", UserName: "owner1", IsAdmin: true},
model.MediaFile{ID: "mf-123", Title: "Test Song"},
)
claims := auth.Claims{ID: "mf-123", Format: "mp3", BitRate: 192, ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
makeRequest(token)
Expect(streamer.called).To(BeTrue())
Expect(streamer.req.Format).To(Equal("mp3"))
Expect(streamer.req.BitRate).To(Equal(192))
})
It("returns 404 when the track is outside the share owner's libraries", func() {
shareOwnedBy(
model.User{ID: "owner1", UserName: "owner1", Libraries: model.Libraries{{ID: 1}}},
model.MediaFile{ID: "mf-restricted", Title: "Other Lib Track", LibraryID: 2},
)
claims := auth.Claims{ID: "mf-restricted", ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
w := makeRequest(token)
Expect(w.Code).To(Equal(http.StatusNotFound))
Expect(streamer.called).To(BeFalse())
})
It("streams a track inside the share owner's libraries", func() {
shareOwnedBy(
model.User{ID: "owner1", UserName: "owner1", Libraries: model.Libraries{{ID: 1}}},
model.MediaFile{ID: "mf-ok", Title: "OK", LibraryID: 1},
)
claims := auth.Claims{ID: "mf-ok", Format: "mp3", ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
makeRequest(token)
Expect(streamer.called).To(BeTrue())
})
It("returns 400 for an expired token", func() {
claims := auth.Claims{ID: "mf-123", ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(-time.Hour), claims)
w := makeRequest(token)
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
It("returns 404 when share has been deleted", func() {
shareRepo.ID = "other-share"
claims := auth.Claims{ID: "mf-123", ShareID: "deleted-share"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
w := makeRequest(token)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
It("returns 410 when share has been set to expired", func() {
shareRepo.ID = "share123"
shareRepo.Entity = &model.Share{ID: "share123", ExpiresAt: new(time.Now().Add(-time.Hour))}
claims := auth.Claims{ID: "mf-123", ShareID: "share123"}
token, _ := auth.CreatePublicToken(claims)
w := makeRequest(token)
Expect(w.Code).To(Equal(http.StatusGone))
})
It("returns 500 when share lookup fails", func() {
shareRepo.Error = errors.New("db error")
claims := auth.Claims{ID: "mf-123", ShareID: "share123"}
token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims)
w := makeRequest(token)
Expect(w.Code).To(Equal(http.StatusInternalServerError))
})
It("skips share check for tokens without shareID (backward compat)", func() {
claims := auth.Claims{ID: "mf-123"}
token, _ := auth.CreatePublicToken(claims)
w := makeRequest(token)
// Should get past share check, then fail on media file lookup (no mock data)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
It("returns 400 for an invalid token", func() {
w := makeRequest("not-a-valid-token")
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
})