navidrome/server/jellyfin/socket_test.go
Deluan Quintão b76ae14286
feat(jellyfin): add Quick Connect sign-in (#6174)
* feat(jellyfin): add Quick Connect sign-in

Jellyfin clients can now sign in without a password: the client shows a
6-digit code, a signed-in user approves it, and the client redeems a secret
for its access token.

- core/quickconnect: in-memory store shared by both routers through wire.
  Codes expire after 10 minutes; a secret redeems only once (Jellyfin
  allows repeats for 10 minutes); at most 1000 pending requests.
- Jellyfin API: Initiate, Connect, Authorize and AuthenticateWithQuickConnect.
  Admins may approve for another user via UserId, like Swiftfin's admin page.
  Initiate and redeem share the login rate limiter; Connect does not, since
  Finamp and Streamyfin poll it every second.
- Web UI: a Quick Connect item in the user menu looks up the code and shows
  the app and device before approving, so a user can't be tricked into
  approving an unknown device blindly.
- Jellyfin.QuickConnect option, on by default like Jellyfin. It only matters
  when the Jellyfin API is enabled.

* refactor(jellyfin): tidy Quick Connect naming and route guards

Group the Quick Connect routes under one requireQuickConnect guard, make the
request's device a named field so req.Device.ID can't be mistaken for a
request id, and rename the web API response type to quickConnectDevice.

* refactor(jellyfin): remove duplicated Jellyfin date formatting function

* test(jellyfin): set play count and starred in the song fixture literal

* refactor(jellyfin): inline the Quick Connect redeem body and use the shared date helper

* fix(jellyfin): bound the client fields Quick Connect keeps in memory

Initiate is unauthenticated and keeps the Client, Device, DeviceId and Version
header fields for up to ten minutes. With no header size limit, each pending
request could hold about 1 MB, and even a short field kept the whole header
alive because the parsed values are substrings of it. Reject fields over 512
bytes and copy the stored values.

Also answer 500 instead of 401 when the redeem user lookup fails for a reason
other than the user being gone.

* fix(jellyfin): rate-limit Quick Connect code approval

Any signed-in user could try codes without limit on the Jellyfin Authorize
endpoint and the web UI lookup/authorize endpoints, and so could approve
another person's pending device for their own account. Apply the same per-IP
limiter as the login (AuthRequestLimit/AuthWindowLength) to both surfaces.
2026-09-19 14:57:01 -04:00

125 lines
4.1 KiB
Go

package jellyfin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("handleSocket", func() {
var api *Router
BeforeEach(func() {
api = &Router{}
})
// Jellyfin's real-time clients (e.g. Finamp) open a WebSocket right after login; without
// a working handshake here they 404-loop-reconnect instead of settling into a session.
It("upgrades the connection and sends ForceKeepAlive", func() {
srv := httptest.NewServer(http.HandlerFunc(api.handleSocket))
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
Expect(err).ToNot(HaveOccurred())
defer conn.Close()
Expect(conn.SetReadDeadline(time.Now().Add(2 * time.Second))).To(Succeed())
var msg map[string]any
Expect(conn.ReadJSON(&msg)).To(Succeed())
Expect(msg["MessageType"]).To(Equal("ForceKeepAlive"))
Expect(msg["Data"]).To(BeNumerically("==", 60))
})
It("replies to a KeepAlive message with a KeepAlive of its own", func() {
srv := httptest.NewServer(http.HandlerFunc(api.handleSocket))
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
Expect(err).ToNot(HaveOccurred())
defer conn.Close()
Expect(conn.SetReadDeadline(time.Now().Add(2 * time.Second))).To(Succeed())
var handshake map[string]any
Expect(conn.ReadJSON(&handshake)).To(Succeed())
Expect(handshake["MessageType"]).To(Equal("ForceKeepAlive"))
Expect(conn.WriteJSON(map[string]any{"MessageType": "KeepAlive"})).To(Succeed())
Expect(conn.SetReadDeadline(time.Now().Add(2 * time.Second))).To(Succeed())
var reply map[string]any
Expect(conn.ReadJSON(&reply)).To(Succeed())
Expect(reply["MessageType"]).To(Equal("KeepAlive"))
})
It("closes the connection when the client disconnects, without leaving the handler hanging", func() {
srv := httptest.NewServer(http.HandlerFunc(api.handleSocket))
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
Expect(err).ToNot(HaveOccurred())
Expect(conn.SetReadDeadline(time.Now().Add(2 * time.Second))).To(Succeed())
var handshake map[string]any
Expect(conn.ReadJSON(&handshake)).To(Succeed())
Expect(conn.Close()).To(Succeed())
})
// End-to-end: proves /socket is reachable through the full router (case-insensitive
// wrapper + chi mux + auth middleware) with a real network listener, exactly as Finamp
// hits it in production with ?api_key=<jwt>.
Context("mounted behind the full router and auth middleware", func() {
var ds *tests.MockDataStore
var token string
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())
t, err := auth.CreateToken(&model.User{ID: testID("u1"), UserName: "alice"})
Expect(err).ToNot(HaveOccurred())
token = t
api = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
})
It("upgrades when authenticated via the api_key query parameter", func() {
srv := httptest.NewServer(api)
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/socket?api_key=" + token
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
Expect(err).ToNot(HaveOccurred())
defer conn.Close()
Expect(conn.SetReadDeadline(time.Now().Add(2 * time.Second))).To(Succeed())
var msg map[string]any
Expect(conn.ReadJSON(&msg)).To(Succeed())
Expect(msg["MessageType"]).To(Equal("ForceKeepAlive"))
})
It("rejects the upgrade with no api_key", func() {
srv := httptest.NewServer(api)
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/socket"
_, resp, err := websocket.DefaultDialer.Dial(wsURL, nil)
Expect(err).To(HaveOccurred())
Expect(resp.StatusCode).To(Equal(http.StatusUnauthorized))
})
})
})