navidrome/server/jellyfin/auth_test.go
Deluan Quintão 16567f147b
fix(jellyfin): match Jellyfin on login SessionInfo, item types and universal streams (#6161)
* fix(jellyfin): send SessionInfo on login so JellyBox gets past sign-in

JellyBox parses AuthenticateByName's SessionInfo as a required object and
fails silently when it is missing, leaving the user on the login screen.
Real Jellyfin always sends it (SessionManager.AuthenticateNewSessionInternal,
10.10.7 and master), so the login response now carries a full SessionInfo
built from the user and the MediaBrowser auth header. It includes every field
JellyBox (Id, PlayState) and Finamp (UserId, LastActivityDate, the activity
and control bools, PlayState's CanSeek/IsPaused/IsMuted) require once the
object is present. The session Id is derived from client and device id, so
repeated logins from one install share it.

* fix(jellyfin): ignore IncludeItemTypes names that aren't Jellyfin kinds

JellyBox opens an album with ParentId=<album>&IncludeItemTypes=music. Music
is not a BaseItemKind, and Jellyfin's comma-delimited binder drops values it
cannot parse, so real Jellyfin treats the request as having no type filter and
lists the album's tracks. Navidrome returned an empty list, so every album
opened empty. Entries that aren't BaseItemKind names are now dropped before
type resolution, so an all-unknown list behaves like an absent one. Real kinds
Navidrome doesn't serve, such as Boxset, still return nothing.

* fix(jellyfin): treat universal Container as the direct-play list

On /Audio/{id}/universal, Container lists the "container|codec" entries the
client can direct play, and TranscodingContainer/AudioCodec name the target
when it can't (UniversalAudioController builds DirectPlayProfiles from it).
Navidrome passed the whole list to the decider as one target format, which
matched nothing and fell back to DefaultDownsamplingFormat, so JellyBox got
every MP3 transcoded to Opus. /universal now has its own handler: a source
matching an entry keeps its format (still downsampled under a bitrate cap),
anything else is transcoded to TranscodingContainer, then AudioCodec. The
/stream routes keep treating Container as the target format.

* refactor(jellyfin): let the stream decider resolve universal requests

streamUniversal matched the Container list itself with plain string equality
and then asked the legacy resolver for the source format. That skipped the
decider's container and codec aliases (mp4 vs m4a, ogg vs opus), and a
direct-playable source over the bitrate cap was transcoded to its own format
instead of the client's TranscodingContainer.

The shared part of ResolveRequest (server-side player override, player
MaxBitRate cap, decision to Request mapping) moves to a resolve helper, and a
new ResolveClientRequest exposes it for callers that build their own
ClientInfo. streamUniversal now turns Container into DirectPlayProfiles and
TranscodingContainer/AudioCodec into a transcoding profile, so the decision
uses the same rules as the Subsonic getTranscodeDecision path. streamFile and
the /stream routes share a serveStream helper, NewSessionInfo reads the clock
itself, and duplicate comments and tests are trimmed.
2026-09-17 23:48:39 -04:00

160 lines
6.1 KiB
Go

package jellyfin
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/server/jellyfin/dto"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("AuthenticateByName", func() {
var api *Router
var ds *tests.MockDataStore
BeforeEach(func() {
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
api = &Router{ds: ds}
})
It("issues a token for valid credentials", func() {
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"alice","Pw":"secret"}`))
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.AuthenticationResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.AccessToken).ToNot(BeEmpty())
Expect(res.User.Name).To(Equal("alice"))
claims, err := auth.Validate(res.AccessToken)
Expect(err).ToNot(HaveOccurred())
Expect(claims.Subject).To(Equal("alice"))
// Finamp reads Policy/Configuration right after login and null-crashes if they're absent.
Expect(res.User.Policy).ToNot(BeNil())
Expect(res.User.Policy.IsAdministrator).To(BeFalse())
Expect(res.User.Policy.EnableAllFolders).To(BeTrue())
Expect(res.User.Policy.EnableMediaPlayback).To(BeTrue())
Expect(res.User.Configuration).ToNot(BeNil())
})
Describe("SessionInfo", func() {
login := func(authHeader string) map[string]any {
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"alice","Pw":"secret"}`))
r.Header.Set("Authorization", authHeader)
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var raw map[string]any
Expect(json.Unmarshal(w.Body.Bytes(), &raw)).To(Succeed())
Expect(raw).To(HaveKey("SessionInfo"))
return raw["SessionInfo"].(map[string]any)
}
const jellybox = `MediaBrowser Client="JellyBox", Device="Mac", DeviceId="dev-1", Version="2.1"`
It("has the fields strict clients require", func() {
s := login(jellybox)
Expect(s["Id"]).To(And(BeAssignableToTypeOf(""), Not(BeEmpty())))
Expect(s["UserId"]).To(Equal(dto.EncodeID(testID("u1"))))
Expect(s["LastActivityDate"]).To(And(BeAssignableToTypeOf(""), Not(BeEmpty())))
for _, k := range []string{"SupportsRemoteControl", "SupportsMediaControl", "HasCustomDeviceName"} {
Expect(s[k]).To(BeAssignableToTypeOf(false), k)
}
ps, ok := s["PlayState"].(map[string]any)
Expect(ok).To(BeTrue())
for _, k := range []string{"CanSeek", "IsPaused", "IsMuted"} {
Expect(ps[k]).To(BeAssignableToTypeOf(false), k)
}
})
It("describes the calling client", func() {
s := login(jellybox)
Expect(s).To(HaveKeyWithValue("UserName", "alice"))
Expect(s).To(HaveKeyWithValue("Client", "JellyBox"))
Expect(s).To(HaveKeyWithValue("DeviceName", "Mac"))
Expect(s).To(HaveKeyWithValue("DeviceId", "dev-1"))
Expect(s).To(HaveKeyWithValue("ApplicationVersion", "2.1"))
Expect(s).To(HaveKeyWithValue("IsActive", true))
})
It("keeps the same Id for the same device, and a new one for another device", func() {
first := login(jellybox)["Id"]
Expect(login(jellybox)["Id"]).To(Equal(first))
other := login(`MediaBrowser Client="JellyBox", Device="Mac", DeviceId="dev-2", Version="2.1"`)
Expect(other["Id"]).ToNot(Equal(first))
})
})
It("records the login time, like the web UI login does", func() {
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"alice","Pw":"secret"}`))
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusOK))
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
usr, err := ur.FindByUsername("alice")
Expect(err).ToNot(HaveOccurred())
Expect(usr.LastLoginAt).ToNot(BeNil())
})
It("reflects an administrator in the User.Policy", func() {
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("admin1"), UserName: "root", NewPassword: "secret", IsAdmin: true})).To(Succeed())
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"root","Pw":"secret"}`))
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.AuthenticationResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.User.Policy).ToNot(BeNil())
Expect(res.User.Policy.IsAdministrator).To(BeTrue())
})
It("rejects invalid credentials with 401", func() {
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"alice","Pw":"wrong"}`))
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusUnauthorized))
})
It("rejects an empty password even for a user with an empty stored password with 401", func() {
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("e"), UserName: "empty", NewPassword: ""})).To(Succeed())
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
strings.NewReader(`{"Username":"empty","Pw":""}`))
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusUnauthorized))
})
})
var _ = Describe("AuthenticateByName body limit", func() {
It("rejects a request body larger than the limit", func() {
ds := &tests.MockDataStore{}
api := &Router{ds: ds}
w := httptest.NewRecorder()
body := `{"Username":"alice","Pw":"secret","Padding":"` + strings.Repeat("x", server.MaxLoginBodySize) + `"}`
r := httptest.NewRequest("POST", "/Users/AuthenticateByName", strings.NewReader(body))
server.LimitLoginBody(http.HandlerFunc(api.authenticateByName)).ServeHTTP(w, r)
Expect(w.Code).To(Equal(http.StatusBadRequest))
})
})