mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-10 19:37:08 +02:00
feat(subsonic): OpenSubsonic API key authentication (#6219)
* feat(persistence): store hashed API keys on players * feat(core): refresh key-bound players without renaming them Add Players.Touch, which records usage for a player already identified by an API key without guessing its identity or overwriting its name. Register also stops renaming players that have an API key. Register no longer returns player save errors (or a stale FindMatch ErrNotFound when the save is rate-limited); save failures are only logged, and only the transcoding lookup error is returned, same as Touch. * feat(subsonic): authenticate with OpenSubsonic API keys Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com> * feat(subsonic): add tokenInfo and advertise apiKeyAuthentication * feat(server): add endpoints to generate and revoke player API keys * feat(ui): manage player API keys Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com> * fix(subsonic): throttle API keys per key and IP A stale key on one device exhausted the shared per-IP bucket and locked out every valid key from the same IP. The limiter only stores a hash of the bucket string, so the key is not retained. Also adds e2e coverage of API key auth through the real repository, and clarifies the player resolution log message. * fix(ui): keep the new API key dialog open until closed The key is shown only once, so Escape and backdrop clicks no longer dismiss it. Also clarifies when the key can be used as a password. * refactor: simplify API key code paths Share the player refresh tail between Register and Touch, fold the ownership-filtered write tail into execOwned, parse the query once for apiKey conflicts, derive HasAPIKey in the player mock, share the player form inputs between create and edit, and pick the delete button by key state instead of spreading conditional props. * feat(players): set API keys through the player record The key is a write-only apiKey field applied on save: required and owner-only on create, optional on edit, empty to revoke. Replaces the generate/revoke endpoints. * fix(players): reject API keys already in use Creating or editing a player with a key another player already has now returns a validation error instead of a 500, and a create that loses the race no longer leaves a keyless player behind. Ownership is checked before the key on create. * feat(ui): edit player API keys as a form field Replaces the show-once dialog, whose icon-less Close button was invisible on mobile. The key is generated in the browser, required and pre-filled on create. * fix(ui): keep new player API keys out of the record cache The json-server create response echoes the request body, and undoable edits merge the payload into the cache, so the key could reappear on the edit page. Strip it from the create result and save player edits pessimistically. Also fall back to a prompt when the clipboard write fails. * fix(ui): polish player API key field Set userId on the created player record so owner actions show immediately, and show a neutral no-key message to non-owners. * refactor: simplify player API key create and field Write the key hash in the create INSERT so the unique index settles races, re-read the created player instead of hand-building the cached record, reuse isWritable for the revoke check, and collapse the key field's derived state and generate/regenerate buttons. * fix(ui): let the API key field size like other inputs fullWidth is now opt-in instead of forced. * fix(ui): align the API key field with other player inputs Apply react-admin's input className, move the actions (now including Copy) below the field, and use a monospace font so the whole key fits. * fix(ui): redirect to the player list after create Matches the other create pages. * refactor(persistence): name the write-access rule for owned rows Owned-row writes now say which row they target and who may write it: ownedRow(rowID, ownerOrAdmin|ownerOnly) builds the WHERE, updateOwnedRow applies it, and SetAPIKey uses ownerOnly instead of a hand-built user_id filter. updateOwned/deleteOwned keep their signatures. * fix(players): apply an edit's key change and fields atomically Update now runs SetAPIKey and the column update in one transaction. Also shares the key format check, drops FindByAPIKey's unneeded empty-key guard, and sets the context username only on the apiKey path. * fix(subsonic): treat any credential param sent with apiKey as a conflict The spec requires error 43 when u, p, t or s is present with apiKey, even with an empty value. * refactor(subsonic): leave the player cookie code unchanged for key-bound requests Return early instead of wrapping the cookie block, so the diff (and CodeQL's view of it) matches master. * fix(subsonic): don't count key lookup errors as failed logins A database error while checking a key sent as the password now surfaces as a server error instead of a bad password, so it no longer feeds the failed-login limiter. * feat(players): use nds_ as the API key prefix Part of a Navidrome secret prefix family (nd + a letter for the kind), alongside ndg_ for API v1 grants. * feat(ui): make player API keys easier to find Label the Settings menu entry "Players & API keys", add an API key filter to the player list, show the key icon in the mobile list, and add Brazilian Portuguese translations for the new player strings. Signed-off-by: Deluan <deluan@navidrome.org> * feat(ui): always show the player API key filter Signed-off-by: Deluan <deluan@navidrome.org> * fix(ui): hide the unset Last Seen date in the player list Players created by hand have no last_seen yet, which showed as 12/31/1. Signed-off-by: Deluan <deluan@navidrome.org> --------- Signed-off-by: Deluan <deluan@navidrome.org> Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com>
This commit is contained in:
parent
ce484083bf
commit
4cdffd5633
42 changed files with 1582 additions and 100 deletions
|
|
@ -107,6 +107,7 @@ func (api *Router) routes() http.Handler {
|
|||
r.Use(getPlayer(api.players))
|
||||
h(r, "ping", api.Ping)
|
||||
h(r, "getLicense", api.GetLicense)
|
||||
h(r, "tokenInfo", api.TokenInfo)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(getPlayer(api.players))
|
||||
|
|
|
|||
54
server/subsonic/e2e/subsonic_apikey_test.go
Normal file
54
server/subsonic/e2e/subsonic_apikey_test.go
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
package e2e
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/model/request"
|
||||
"github.com/navidrome/navidrome/server/subsonic/responses"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("API key authentication", func() {
|
||||
var key string
|
||||
|
||||
BeforeEach(func() {
|
||||
setupTestDB()
|
||||
userCtx := request.WithUser(ctx, regularUser)
|
||||
player := &model.Player{ID: "apikey-player", Name: "Phone", UserId: regularUser.ID, Client: "test-client"}
|
||||
Expect(ds.Player().Put(userCtx, player)).To(Succeed())
|
||||
key = "nds_0123456789abcdefghijkl"
|
||||
Expect(ds.Player().SetAPIKey(userCtx, player.ID, key)).To(Succeed())
|
||||
})
|
||||
|
||||
doKeyReq := func(endpoint, apiKey string) *responses.Subsonic {
|
||||
q := url.Values{"apiKey": {apiKey}, "v": {"1.16.1"}, "c": {"test-client"}, "f": {"json"}}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("GET", "/"+endpoint+"?"+q.Encode(), nil))
|
||||
return parseJSONResponse(w)
|
||||
}
|
||||
|
||||
It("authenticates ping with only the key", func() {
|
||||
resp := doKeyReq("ping", key)
|
||||
|
||||
Expect(resp.Status).To(Equal(responses.StatusOK))
|
||||
})
|
||||
|
||||
It("reports the key owner in tokenInfo", func() {
|
||||
resp := doKeyReq("tokenInfo", key)
|
||||
|
||||
Expect(resp.Status).To(Equal(responses.StatusOK))
|
||||
Expect(resp.TokenInfo).ToNot(BeNil())
|
||||
Expect(resp.TokenInfo.Username).To(Equal(regularUser.UserName))
|
||||
})
|
||||
|
||||
It("rejects an unknown key with error 44", func() {
|
||||
resp := doKeyReq("ping", "nds_unknown")
|
||||
|
||||
Expect(resp.Status).To(Equal(responses.StatusFailed))
|
||||
Expect(resp.Error).ToNot(BeNil())
|
||||
Expect(resp.Error.Code).To(Equal(int32(44)))
|
||||
})
|
||||
})
|
||||
|
|
@ -65,14 +65,15 @@ func checkRequiredParameters(next http.Handler) http.Handler {
|
|||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var requiredParameters []string
|
||||
|
||||
p := req.Params(r)
|
||||
username, _ := fromInternalOrProxyAuth(r)
|
||||
if username != "" {
|
||||
apiKey, _ := p.String("apiKey")
|
||||
if username != "" || apiKey != "" {
|
||||
requiredParameters = []string{"v", "c"}
|
||||
} else {
|
||||
requiredParameters = []string{"u", "v", "c"}
|
||||
}
|
||||
|
||||
p := req.Params(r)
|
||||
for _, param := range requiredParameters {
|
||||
if _, err := p.String(param); err != nil {
|
||||
log.Warn(r, err)
|
||||
|
|
@ -104,10 +105,14 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
|
|||
ctx := r.Context()
|
||||
|
||||
var usr *model.User
|
||||
var keyPlayer *model.Player
|
||||
var err error
|
||||
|
||||
p := req.Params(r)
|
||||
apiKey, _ := p.String("apiKey")
|
||||
username, isInternalAuth := fromInternalOrProxyAuth(r)
|
||||
if username != "" {
|
||||
switch {
|
||||
case username != "":
|
||||
authType := If(isInternalAuth, "internal", "reverse-proxy")
|
||||
usr, err = ds.User().FindByUsername(ctx, username)
|
||||
if errors.Is(err, context.Canceled) {
|
||||
|
|
@ -119,8 +124,16 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
|
|||
} else if err != nil {
|
||||
log.Error(ctx, "API: Error authenticating username", "auth", authType, "username", username, "remoteAddr", r.RemoteAddr, err)
|
||||
}
|
||||
} else {
|
||||
p := req.Params(r)
|
||||
case apiKey != "":
|
||||
usr, keyPlayer, err = authenticateAPIKey(ctx, ds, limiter, r, apiKey)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
sendError(w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx = request.WithUsername(ctx, usr.UserName)
|
||||
default:
|
||||
username, _ := p.String("u")
|
||||
pass, _ := p.String("p")
|
||||
token, _ := p.String("t")
|
||||
|
|
@ -142,6 +155,9 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
|
|||
usr, err = ds.User().FindByUsernameWithPassword(ctx, username)
|
||||
if err == nil {
|
||||
err = validateCredentials(usr, pass, token, salt, jwt)
|
||||
if errors.Is(err, model.ErrInvalidAuth) && pass != "" && jwt == "" {
|
||||
keyPlayer, err = playerFromPasswordKey(ctx, ds, usr, pass)
|
||||
}
|
||||
}
|
||||
invalidLogin := errors.Is(err, model.ErrNotFound) || errors.Is(err, model.ErrInvalidAuth)
|
||||
slot.release(invalidLogin)
|
||||
|
|
@ -162,11 +178,77 @@ func authenticate(ds model.DataStore) func(next http.Handler) http.Handler {
|
|||
}
|
||||
|
||||
ctx = request.WithUser(ctx, *usr)
|
||||
if keyPlayer != nil {
|
||||
ctx = request.WithPlayer(ctx, *keyPlayer)
|
||||
}
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var apiKeyConflicts = []string{"u", "p", "t", "s", "jwt"}
|
||||
|
||||
func authenticateAPIKey(ctx context.Context, ds model.DataStore, limiter *authLimiter, r *http.Request, key string) (*model.User, *model.Player, error) {
|
||||
query := r.URL.Query()
|
||||
for _, param := range apiKeyConflicts {
|
||||
if query.Has(param) {
|
||||
log.Warn(ctx, "API: apiKey sent with other credentials", "auth", "apikey", "param", param, "remoteAddr", r.RemoteAddr)
|
||||
return nil, nil, newError(responses.ErrorMultipleAuthMechanismsProvided)
|
||||
}
|
||||
}
|
||||
|
||||
// Per key, so a stale key on one device cannot lock out valid keys sharing the IP
|
||||
slot, allowed := limiter.acquire(ctx, "apikey\x00"+server.ClientIP(r)+"\x00"+key)
|
||||
if !allowed {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
log.Warn(ctx, "API: Too many failed API key attempts", "auth", "apikey", "remoteAddr", r.RemoteAddr)
|
||||
return nil, nil, newError(responses.ErrorInvalidAPIKey)
|
||||
}
|
||||
|
||||
player, err := ds.Player().FindByAPIKey(ctx, key)
|
||||
var usr *model.User
|
||||
if err == nil {
|
||||
usr, err = ds.User().Get(ctx, player.UserId)
|
||||
}
|
||||
slot.release(errors.Is(err, model.ErrNotFound))
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
return nil, nil, err
|
||||
case errors.Is(err, model.ErrNotFound):
|
||||
log.Warn(ctx, "API: Invalid API key", "auth", "apikey", "remoteAddr", r.RemoteAddr)
|
||||
return nil, nil, newError(responses.ErrorInvalidAPIKey)
|
||||
case err != nil:
|
||||
log.Error(ctx, "API: Error authenticating API key", "auth", "apikey", "remoteAddr", r.RemoteAddr, err)
|
||||
return nil, nil, newError(responses.ErrorAuthenticationFail)
|
||||
}
|
||||
return usr, player, nil
|
||||
}
|
||||
|
||||
// playerFromPasswordKey lets clients that only have a password field log in with an API key.
|
||||
// It returns ErrInvalidAuth when pass is not a key of usr, so only real failures skip the limiter count.
|
||||
func playerFromPasswordKey(ctx context.Context, ds model.DataStore, usr *model.User, pass string) (*model.Player, error) {
|
||||
key := decodePassword(pass)
|
||||
if !strings.HasPrefix(key, consts.APIKeyPrefix) {
|
||||
return nil, model.ErrInvalidAuth
|
||||
}
|
||||
plr, err := ds.Player().FindByAPIKey(ctx, key)
|
||||
if errors.Is(err, model.ErrNotFound) || (err == nil && plr.UserId != usr.ID) {
|
||||
return nil, model.ErrInvalidAuth
|
||||
}
|
||||
return plr, err
|
||||
}
|
||||
|
||||
func decodePassword(pass string) string {
|
||||
if strings.HasPrefix(pass, "enc:") {
|
||||
if dec, err := hex.DecodeString(pass[4:]); err == nil {
|
||||
return string(dec)
|
||||
}
|
||||
}
|
||||
return pass
|
||||
}
|
||||
|
||||
func adminOnly(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
loggedUser, ok := request.UserFrom(r.Context())
|
||||
|
|
@ -194,12 +276,7 @@ func validateCredentials(user *model.User, pass, token, salt, jwt string) error
|
|||
claims.Subject == user.UserName &&
|
||||
auth.CheckClaims(claims, *user, auth.AudienceSubsonic) == nil
|
||||
case pass != "":
|
||||
if strings.HasPrefix(pass, "enc:") {
|
||||
if dec, err := hex.DecodeString(pass[4:]); err == nil {
|
||||
pass = string(dec)
|
||||
}
|
||||
}
|
||||
valid = pass == user.Password
|
||||
valid = decodePassword(pass) == user.Password
|
||||
case token != "":
|
||||
t := fmt.Sprintf("%x", md5.Sum([]byte(user.Password+salt)))
|
||||
valid = t == token
|
||||
|
|
@ -217,12 +294,20 @@ func getPlayer(players core.Players) func(next http.Handler) http.Handler {
|
|||
ctx := r.Context()
|
||||
userName, _ := request.UsernameFrom(ctx)
|
||||
client, _ := request.ClientFrom(ctx)
|
||||
playerId := playerIDFromCookie(r, userName)
|
||||
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
userAgent := canonicalUserAgent(r)
|
||||
player, trc, err := players.Register(ctx, playerId, client, userAgent, ip)
|
||||
|
||||
var player *model.Player
|
||||
var trc *model.Transcoding
|
||||
var err error
|
||||
keyPlayer, boundByKey := request.PlayerFrom(ctx)
|
||||
if boundByKey {
|
||||
player, trc, err = players.Touch(ctx, keyPlayer, client, userAgent, ip)
|
||||
} else {
|
||||
player, trc, err = players.Register(ctx, playerIDFromCookie(r, userName), client, userAgent, ip)
|
||||
}
|
||||
if err != nil {
|
||||
log.Error(ctx, "Could not register player", "username", userName, "client", client, err)
|
||||
log.Error(ctx, "Could not resolve player", "username", userName, "client", client, err)
|
||||
} else {
|
||||
ctx = request.WithPlayer(ctx, *player)
|
||||
if trc != nil {
|
||||
|
|
@ -230,6 +315,11 @@ func getPlayer(players core.Players) func(next http.Handler) http.Handler {
|
|||
}
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
// A key already identifies the player, so the cookie would only add a second, weaker signal
|
||||
if boundByKey {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
cookie := &http.Cookie{ //nolint:gosec // Secure omitted: Navidrome may run over plain HTTP
|
||||
Name: playerIDCookieName(userName),
|
||||
Value: player.ID,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package subsonic
|
|||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
|
@ -119,6 +120,14 @@ var _ = Describe("Middlewares", func() {
|
|||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("does not require u when apiKey is present", func() {
|
||||
r := newGetRequest("apiKey=nds_abc", "v=1.15", "c=test")
|
||||
cp := checkRequiredParameters(next)
|
||||
cp.ServeHTTP(w, r)
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("fails when user is missing", func() {
|
||||
r := newGetRequest("v=1.15", "c=test")
|
||||
cp := checkRequiredParameters(next)
|
||||
|
|
@ -311,6 +320,101 @@ var _ = Describe("Middlewares", func() {
|
|||
})
|
||||
})
|
||||
|
||||
When("using API key authentication", func() {
|
||||
var key string
|
||||
serve := func(params ...string) {
|
||||
authenticate(ds)(next).ServeHTTP(w, newGetRequest(params...))
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
usr, err := ds.User().FindByUsername(ctx, "admin")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ds.Player().Put(ctx, &model.Player{ID: "player-1", Name: "My Phone", UserId: usr.ID, Client: "Symfonium"})).To(Succeed())
|
||||
key = "nds_0123456789abcdefghijkl"
|
||||
Expect(ds.Player().SetAPIKey(ctx, "player-1", key)).To(Succeed())
|
||||
})
|
||||
|
||||
It("authenticates the owner and binds the key's player", func() {
|
||||
serve("apiKey=" + key)
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
user, _ := request.UserFrom(next.req.Context())
|
||||
Expect(user.UserName).To(Equal("admin"))
|
||||
username, _ := request.UsernameFrom(next.req.Context())
|
||||
Expect(username).To(Equal("admin"))
|
||||
player, ok := request.PlayerFrom(next.req.Context())
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(player.ID).To(Equal("player-1"))
|
||||
})
|
||||
|
||||
It("accepts the key in a POST form body", func() {
|
||||
r := newPostRequest("", "apiKey="+key)
|
||||
cp := postFormToQueryParams(authenticate(ds)(next))
|
||||
cp.ServeHTTP(w, r)
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
player, _ := request.PlayerFrom(next.req.Context())
|
||||
Expect(player.ID).To(Equal("player-1"))
|
||||
})
|
||||
|
||||
It("rejects an unknown key with error 44", func() {
|
||||
serve("apiKey=nds_unknown")
|
||||
|
||||
Expect(w.Body.String()).To(ContainSubstring(`code="44"`))
|
||||
Expect(next.called).To(BeFalse())
|
||||
})
|
||||
|
||||
DescribeTable("rejects apiKey mixed with other credentials with error 43",
|
||||
func(extra string) {
|
||||
serve("apiKey="+key, extra)
|
||||
|
||||
Expect(w.Body.String()).To(ContainSubstring(`code="43"`))
|
||||
Expect(next.called).To(BeFalse())
|
||||
},
|
||||
Entry("u", "u=admin"),
|
||||
Entry("p", "p=wordpass"),
|
||||
Entry("t", "t=abc"),
|
||||
Entry("s", "s=abc"),
|
||||
Entry("jwt", "jwt=abc"),
|
||||
Entry("empty u", "u="),
|
||||
Entry("empty p", "p="),
|
||||
)
|
||||
|
||||
Context("key sent as the password", func() {
|
||||
It("authenticates and binds the key's player", func() {
|
||||
serve("u=admin", "p="+key)
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
player, ok := request.PlayerFrom(next.req.Context())
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(player.ID).To(Equal("player-1"))
|
||||
})
|
||||
|
||||
It("accepts the hex-encoded form", func() {
|
||||
serve("u=admin", "p=enc:"+hex.EncodeToString([]byte(key)))
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("still accepts a real password that starts with the key prefix", func() {
|
||||
Expect(ds.User().Put(ctx, &model.User{UserName: "prefixed", NewPassword: "nds_secret"})).To(Succeed())
|
||||
serve("u=prefixed", "p=nds_secret")
|
||||
|
||||
Expect(next.called).To(BeTrue())
|
||||
_, ok := request.PlayerFrom(next.req.Context())
|
||||
Expect(ok).To(BeFalse())
|
||||
})
|
||||
|
||||
It("rejects another user's key with error 40", func() {
|
||||
Expect(ds.User().Put(ctx, &model.User{UserName: "other", NewPassword: "pw"})).To(Succeed())
|
||||
serve("u=other", "p="+key)
|
||||
|
||||
Expect(w.Body.String()).To(ContainSubstring(`code="40"`))
|
||||
Expect(next.called).To(BeFalse())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("failed attempts reach AuthRequestLimit", func() {
|
||||
var cp http.Handler
|
||||
|
||||
|
|
@ -376,6 +480,21 @@ var _ = Describe("Middlewares", func() {
|
|||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("does not count server errors when a key is sent as the password", func() {
|
||||
usr, _ := ds.User().FindByUsername(ctx, "admin")
|
||||
playerRepo := ds.Player().(*tests.MockPlayerRepo)
|
||||
Expect(playerRepo.Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed())
|
||||
key := "nds_0123456789abcdefghijkl"
|
||||
Expect(playerRepo.SetAPIKey(ctx, "player-1", key)).To(Succeed())
|
||||
|
||||
playerRepo.Error = errors.New("db down")
|
||||
failTimes(5, "u=admin", "p="+key)
|
||||
playerRepo.Error = nil
|
||||
|
||||
serve(newGetRequest("u=admin", "p="+key))
|
||||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("does not block other usernames from the same IP", func() {
|
||||
_ = ds.User().Put(ctx, &model.User{UserName: "other", NewPassword: "otherpass"})
|
||||
failTimes(3, "u=admin", "p=WRONG")
|
||||
|
|
@ -405,6 +524,25 @@ var _ = Describe("Middlewares", func() {
|
|||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("throttles a repeated bad key without locking out valid keys from the same IP", func() {
|
||||
usr, _ := ds.User().FindByUsername(ctx, "admin")
|
||||
playerRepo := ds.Player().(*tests.MockPlayerRepo)
|
||||
Expect(playerRepo.Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed())
|
||||
key := "nds_0123456789abcdefghijkl"
|
||||
Expect(playerRepo.SetAPIKey(ctx, "player-1", key)).To(Succeed())
|
||||
|
||||
for range 3 {
|
||||
Expect(serve(newGetRequest("apiKey=nds_bad")).Body.String()).To(ContainSubstring(`code="44"`))
|
||||
}
|
||||
playerRepo.APIKeys["nds_bad"] = "player-1"
|
||||
rec := serve(newGetRequest("apiKey=nds_bad"))
|
||||
Expect(next.called).To(BeFalse())
|
||||
Expect(rec.Body.String()).To(ContainSubstring(`code="44"`))
|
||||
|
||||
serve(newGetRequest("apiKey=" + key))
|
||||
Expect(next.called).To(BeTrue())
|
||||
})
|
||||
|
||||
It("is disabled when AuthRequestLimit is 0", func() {
|
||||
conf.Server.AuthRequestLimit = 0
|
||||
cp = authenticate(ds)(next)
|
||||
|
|
@ -532,6 +670,24 @@ var _ = Describe("Middlewares", func() {
|
|||
Expect(cookieStr).To(BeEmpty())
|
||||
})
|
||||
|
||||
Context("player bound by an API key", func() {
|
||||
BeforeEach(func() {
|
||||
r = r.WithContext(request.WithPlayer(r.Context(), model.Player{ID: "keyed"}))
|
||||
gp := getPlayer(mockedPlayers)(next)
|
||||
gp.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
It("uses the key's player", func() {
|
||||
Expect(mockedPlayers.touched).To(BeTrue())
|
||||
player, _ := request.PlayerFrom(next.req.Context())
|
||||
Expect(player.ID).To(Equal("keyed"))
|
||||
})
|
||||
|
||||
It("does not set the player cookie", func() {
|
||||
Expect(w.Header().Get("Set-Cookie")).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
Context("PlayerId specified in Cookies", func() {
|
||||
BeforeEach(func() {
|
||||
cookie := &http.Cookie{
|
||||
|
|
@ -712,6 +868,12 @@ func (mh *mockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
type mockPlayers struct {
|
||||
core.Players
|
||||
transcoding *model.Transcoding
|
||||
touched bool
|
||||
}
|
||||
|
||||
func (mp *mockPlayers) Touch(_ context.Context, plr model.Player, _, _, _ string) (*model.Player, *model.Transcoding, error) {
|
||||
mp.touched = true
|
||||
return &plr, mp.transcoding, nil
|
||||
}
|
||||
|
||||
func (mp *mockPlayers) Get(ctx context.Context, playerId string) (*model.Player, error) {
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ func (api *Router) GetOpenSubsonicExtensions(_ *http.Request) (*responses.Subson
|
|||
{Name: "transcoding", Versions: []int32{1}},
|
||||
{Name: "playbackReport", Versions: []int32{1}},
|
||||
{Name: "topSongsByArtistId", Versions: []int32{1}},
|
||||
{Name: "apiKeyAuthentication", Versions: []int32{1}},
|
||||
}
|
||||
if api.sonic != nil && api.sonic.HasProvider() {
|
||||
extensions = append(extensions, responses.OpenSubsonicExtension{
|
||||
|
|
|
|||
|
|
@ -44,44 +44,13 @@ var _ = Describe("GetOpenSubsonicExtensions", func() {
|
|||
router = subsonic.New(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
})
|
||||
|
||||
It("should return the base 6 OpenSubsonicExtensions without sonicSimilarity", func() {
|
||||
It("should return the base 8 OpenSubsonicExtensions without sonicSimilarity", func() {
|
||||
router.ServeHTTP(w, r)
|
||||
|
||||
// Make sure the endpoint is public, by not passing any authentication
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
Expect(w.Header().Get("Content-Type")).To(Equal("application/json"))
|
||||
|
||||
var response responses.JsonWrapper
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(*response.Subsonic.OpenSubsonicExtensions).To(SatisfyAll(
|
||||
HaveLen(7),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "transcodeOffset", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "formPost", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "songLyrics", Versions: []int32{1, 2}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "indexBasedQueue", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "transcoding", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "playbackReport", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "topSongsByArtistId", Versions: []int32{1}}),
|
||||
))
|
||||
Expect(*response.Subsonic.OpenSubsonicExtensions).NotTo(
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "sonicSimilarity", Versions: []int32{1}}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
Context("with sonic similarity plugin", func() {
|
||||
BeforeEach(func() {
|
||||
sonicService := sonicsvc.New(nil, &mockSonicPluginLoader{names: []string{"test-plugin"}}, nil)
|
||||
router = subsonic.New(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, sonicService)
|
||||
})
|
||||
|
||||
It("should return 7 extensions including sonicSimilarity", func() {
|
||||
router.ServeHTTP(w, r)
|
||||
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
Expect(w.Header().Get("Content-Type")).To(Equal("application/json"))
|
||||
|
||||
var response responses.JsonWrapper
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
|
@ -93,8 +62,41 @@ var _ = Describe("GetOpenSubsonicExtensions", func() {
|
|||
ContainElement(responses.OpenSubsonicExtension{Name: "indexBasedQueue", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "transcoding", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "playbackReport", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "topSongsByArtistId", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "apiKeyAuthentication", Versions: []int32{1}}),
|
||||
))
|
||||
Expect(*response.Subsonic.OpenSubsonicExtensions).NotTo(
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "sonicSimilarity", Versions: []int32{1}}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
Context("with sonic similarity plugin", func() {
|
||||
BeforeEach(func() {
|
||||
sonicService := sonicsvc.New(nil, &mockSonicPluginLoader{names: []string{"test-plugin"}}, nil)
|
||||
router = subsonic.New(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, sonicService)
|
||||
})
|
||||
|
||||
It("should return 9 extensions including sonicSimilarity", func() {
|
||||
router.ServeHTTP(w, r)
|
||||
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
Expect(w.Header().Get("Content-Type")).To(Equal("application/json"))
|
||||
|
||||
var response responses.JsonWrapper
|
||||
err := json.Unmarshal(w.Body.Bytes(), &response)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(*response.Subsonic.OpenSubsonicExtensions).To(SatisfyAll(
|
||||
HaveLen(9),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "transcodeOffset", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "formPost", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "songLyrics", Versions: []int32{1, 2}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "indexBasedQueue", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "transcoding", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "playbackReport", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "sonicSimilarity", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "topSongsByArtistId", Versions: []int32{1}}),
|
||||
ContainElement(responses.OpenSubsonicExtension{Name: "apiKeyAuthentication", Versions: []int32{1}}),
|
||||
))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"status": "ok",
|
||||
"version": "1.16.1",
|
||||
"type": "navidrome",
|
||||
"serverVersion": "v0.55.0",
|
||||
"openSubsonic": true,
|
||||
"tokenInfo": {
|
||||
"username": "deluan"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.16.1" type="navidrome" serverVersion="v0.55.0" openSubsonic="true">
|
||||
<tokenInfo username="deluan"></tokenInfo>
|
||||
</subsonic-response>
|
||||
|
|
@ -1,25 +1,29 @@
|
|||
package responses
|
||||
|
||||
const (
|
||||
ErrorGeneric int32 = 0
|
||||
ErrorMissingParameter int32 = 10
|
||||
ErrorClientTooOld int32 = 20
|
||||
ErrorServerTooOld int32 = 30
|
||||
ErrorAuthenticationFail int32 = 40
|
||||
ErrorAuthorizationFail int32 = 50
|
||||
ErrorTrialExpired int32 = 60
|
||||
ErrorDataNotFound int32 = 70
|
||||
ErrorGeneric int32 = 0
|
||||
ErrorMissingParameter int32 = 10
|
||||
ErrorClientTooOld int32 = 20
|
||||
ErrorServerTooOld int32 = 30
|
||||
ErrorAuthenticationFail int32 = 40
|
||||
ErrorMultipleAuthMechanismsProvided int32 = 43
|
||||
ErrorInvalidAPIKey int32 = 44
|
||||
ErrorAuthorizationFail int32 = 50
|
||||
ErrorTrialExpired int32 = 60
|
||||
ErrorDataNotFound int32 = 70
|
||||
)
|
||||
|
||||
var errors = map[int32]string{
|
||||
ErrorGeneric: "A generic error",
|
||||
ErrorMissingParameter: "Required parameter is missing",
|
||||
ErrorClientTooOld: "Incompatible Subsonic REST protocol version. Client must upgrade",
|
||||
ErrorServerTooOld: "Incompatible Subsonic REST protocol version. Server must upgrade",
|
||||
ErrorAuthenticationFail: "Wrong username or password",
|
||||
ErrorAuthorizationFail: "User is not authorized for the given operation",
|
||||
ErrorTrialExpired: "The trial period for the Subsonic server is over. Please upgrade to Subsonic Premium. Visit subsonic.org for details",
|
||||
ErrorDataNotFound: "The requested data was not found",
|
||||
var errors = map[int32]string{ //nolint:gosec // G101 false positive: error messages, not credentials
|
||||
ErrorGeneric: "A generic error",
|
||||
ErrorMissingParameter: "Required parameter is missing",
|
||||
ErrorClientTooOld: "Incompatible Subsonic REST protocol version. Client must upgrade",
|
||||
ErrorServerTooOld: "Incompatible Subsonic REST protocol version. Server must upgrade",
|
||||
ErrorAuthenticationFail: "Wrong username or password",
|
||||
ErrorMultipleAuthMechanismsProvided: "Multiple conflicting authentication mechanisms provided",
|
||||
ErrorInvalidAPIKey: "Invalid API key",
|
||||
ErrorAuthorizationFail: "User is not authorized for the given operation",
|
||||
ErrorTrialExpired: "The trial period for the Subsonic server is over. Please upgrade to Subsonic Premium. Visit subsonic.org for details",
|
||||
ErrorDataNotFound: "The requested data was not found",
|
||||
}
|
||||
|
||||
func ErrorMsg(code int32) string {
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ type Subsonic struct {
|
|||
PlayQueueByIndex *PlayQueueByIndex `xml:"playQueueByIndex,omitempty" json:"playQueueByIndex,omitempty"`
|
||||
TranscodeDecision *TranscodeDecision `xml:"transcodeDecision,omitempty" json:"transcodeDecision,omitempty"`
|
||||
SonicMatches *Array[SonicMatch] `xml:"sonicMatch,omitempty" json:"sonicMatch,omitempty"`
|
||||
TokenInfo *TokenInfo `xml:"tokenInfo,omitempty" json:"tokenInfo,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
|
|
@ -596,6 +597,10 @@ type OpenSubsonicExtension struct {
|
|||
|
||||
type OpenSubsonicExtensions []OpenSubsonicExtension
|
||||
|
||||
type TokenInfo struct {
|
||||
Username string `xml:"username,attr" json:"username"`
|
||||
}
|
||||
|
||||
type ItemGenre struct {
|
||||
Name string `xml:"name,attr" json:"name"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1015,6 +1015,20 @@ var _ = Describe("Responses", func() {
|
|||
})
|
||||
})
|
||||
|
||||
Describe("TokenInfo", func() {
|
||||
BeforeEach(func() {
|
||||
response.OpenSubsonic = true
|
||||
response.TokenInfo = &TokenInfo{Username: "deluan"}
|
||||
})
|
||||
|
||||
It("should match .XML", func() {
|
||||
Expect(xml.MarshalIndent(response, "", " ")).To(MatchSnapshot())
|
||||
})
|
||||
It("should match .JSON", func() {
|
||||
Expect(json.MarshalIndent(response, "", " ")).To(MatchSnapshot())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("InternetRadioStations", func() {
|
||||
BeforeEach(func() {
|
||||
response.InternetRadioStations = &InternetRadioStations{}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package subsonic
|
|||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/navidrome/navidrome/model/request"
|
||||
"github.com/navidrome/navidrome/server/subsonic/responses"
|
||||
)
|
||||
|
||||
|
|
@ -15,3 +16,10 @@ func (api *Router) GetLicense(_ *http.Request) (*responses.Subsonic, error) {
|
|||
response.License = &responses.License{Valid: true}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (api *Router) TokenInfo(r *http.Request) (*responses.Subsonic, error) {
|
||||
user, _ := request.UserFrom(r.Context())
|
||||
response := newResponse()
|
||||
response.TokenInfo = &responses.TokenInfo{Username: user.UserName}
|
||||
return response, nil
|
||||
}
|
||||
|
|
|
|||
23
server/subsonic/system_test.go
Normal file
23
server/subsonic/system_test.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package subsonic
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/model/request"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("TokenInfo", func() {
|
||||
It("returns the authenticated username", func() {
|
||||
api := &Router{}
|
||||
r := httptest.NewRequest("GET", "/tokenInfo", nil)
|
||||
r = r.WithContext(request.WithUser(r.Context(), model.User{UserName: "deluan"}))
|
||||
|
||||
resp, err := api.TokenInfo(r)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(resp.TokenInfo.Username).To(Equal("deluan"))
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue