Deluan Quintão 59810c3d59
feat(jellyfin): non-expiring, audience-scoped tokens revocable by password change (#6013)
* feat(auth): add per-user token_epoch column and bump method

* feat(auth): add aud and ep claims, omitted when zero

* feat(auth): add CreateAPIToken for non-expiring, audience-scoped tokens

* feat(auth): add CheckClaims for epoch and audience validation

* feat(jellyfin): issue non-expiring, jellyfin-scoped access tokens

* fix(subsonic): reject API-scoped and revoked tokens on the jwt path

* fix(server): reject API-scoped and revoked tokens on the native API

* fix(server): pin the token-subject guard and stop leaking test config

Adds a regression spec for the DevAutoLogin/ExtAuth guard in
tokenAllowed, switches its comparison to case-insensitive to match
the user lookup's own COLLATE NOCASE semantics, and restores Subsonic
JWT test config after each spec instead of leaking SessionTimeout.

* feat(request): add a token epoch holder for handler-to-middleware signalling

* refactor(server): write the refreshed JWT header after the handler runs

* feat(auth): revoke all tokens for a user when their password changes

* fix(server): restore Unwrap on the JWT refresh writer so SSE write deadlines apply

* test(auth): pin that non-session tokens reject API access tokens

* test(jellyfin): pin token scoping and epoch revocation end to end

Exercises auth.CreateAPIToken and CheckClaims against the real Jellyfin
router and SQLite DB: the minted token has no exp and is aud-scoped to
jellyfin, and bumping token_epoch through the real UserRepository revokes
an already-issued token on the next protected request.

* test(nativeapi): pin the token-epoch handoff through a real password-change request

Drive a self password change through the real Authenticator/JWTRefresher
chain and a real SQLite-backed userRepository, so the epoch handoff between
Put and the refreshed-token writer is verified end to end, not as two
separately-tested halves. Also fix tokenAllowed to read the enriched ctx it
was given instead of r.Context(), so its warning log carries the username.

* refactor(server): drop tokenAllowed's now-unused request parameter

Finding-2 already moved every use to ctx; r was dead weight. Also note
in the new nativeapi test why it must stay the package's only real-DB
spec: db.Db() is a process-wide singleton its cleanup closes for good.

* refactor(auth): remove duplication in claim decoding and token minting

* refactor(auth): group aud with the standard JWT claims

* refactor(auth): read aud with the standard-claim accessor pattern

* fix(log): redact every api_key spelling the Jellyfin API accepts

* fix(auth): bind session tokens to the user id, not just the username

* fix(auth): return the token epoch from the same atomic increment

* fix(auth): bump the token epoch in the same statement as the password write

* chore(auth): trim comments to the why-only budget
2026-08-22 20:36:24 -04:00

135 lines
4.9 KiB
Go

package jellyfin
import (
"encoding/json"
"net/http"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/jellyfin/dto"
)
type authenticateByNameRequest struct {
Username string `json:"Username"`
Pw string `json:"Pw"`
}
func (api *Router) authenticateByName(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var body authenticateByNameRequest
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// Navidrome stores recoverable passwords; this mirrors Subsonic's validateCredentials plaintext path.
usr, err := api.ds.User(ctx).FindByUsernameWithPassword(body.Username)
if body.Pw == "" || err != nil || usr == nil || usr.Password != body.Pw {
log.Warn(ctx, "Jellyfin API: invalid login", "username", body.Username, "remoteAddr", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Best-effort, like the web UI's validateLogin: without it, Jellyfin-only users show a
// never/stale "Last Login" in the admin UI.
if err := api.ds.User(ctx).UpdateLastLoginAt(usr.ID); err != nil {
log.Error(ctx, "Jellyfin API: could not update last login date", "username", body.Username, err)
}
token, err := auth.CreateAPIToken(usr, auth.AudienceJellyfin)
if err != nil {
api.internalError(w, r, err)
return
}
// SessionInfo is omitted, not partially filled: a stub {Id, UserId} could fail a strict client's
// parse, and Finamp's login doesn't need it (its AuthenticationResult.sessionInfo is nullable).
api.ok(w, r, dto.AuthenticationResult{
User: userToDto(usr, api.serverName(), api.serverID(ctx)),
AccessToken: token,
ServerId: api.serverID(ctx),
})
}
// userToDto builds the User object clients expect. Finamp reads Policy and Configuration right after
// login and null-crashes if absent, so both are filled with Navidrome-appropriate defaults.
func userToDto(u *model.User, serverName, serverID string) *dto.UserDto {
return &dto.UserDto{
Name: u.UserName,
Id: dto.EncodeID(u.ID), // hex like every other id, so lowercased paths stay valid
ServerId: serverID,
ServerName: serverName,
HasPassword: true,
HasConfiguredPassword: true,
Policy: userPolicy(u),
Configuration: userConfiguration(),
}
}
func userPolicy(u *model.User) *dto.UserPolicy {
return &dto.UserPolicy{
IsAdministrator: u.IsAdmin,
IsHidden: false,
EnableCollectionManagement: false,
EnableSubtitleManagement: false,
EnableLyricManagement: false,
IsDisabled: false,
BlockedTags: []string{},
AllowedTags: []string{},
EnableUserPreferenceAccess: true,
AccessSchedules: []string{},
BlockUnratedItems: []string{},
EnableRemoteControlOfOtherUsers: false,
EnableSharedDeviceControl: false,
EnableRemoteAccess: true,
EnableLiveTvManagement: false,
EnableLiveTvAccess: false,
EnableMediaPlayback: true,
EnableAudioPlaybackTranscoding: true,
EnableVideoPlaybackTranscoding: true,
EnablePlaybackRemuxing: true,
ForceRemoteSourceTranscoding: false,
EnableContentDeletion: false,
EnableContentDeletionFromFolders: []string{},
EnableContentDownloading: true,
EnableSyncTranscoding: true,
EnableMediaConversion: true,
EnabledDevices: []string{},
EnableAllDevices: true,
EnabledChannels: []string{},
EnableAllChannels: false,
EnabledFolders: []string{},
EnableAllFolders: true,
InvalidLoginAttemptCount: 0,
LoginAttemptsBeforeLockout: -1,
MaxActiveSessions: 0,
EnablePublicSharing: true,
BlockedMediaFolders: []string{},
BlockedChannels: []string{},
RemoteClientBitrateLimit: 0,
AuthenticationProviderId: "",
PasswordResetProviderId: "",
SyncPlayAccess: "CreateAndJoinGroups",
}
}
func userConfiguration() *dto.UserConfiguration {
return &dto.UserConfiguration{
PlayDefaultAudioTrack: true,
SubtitleLanguagePreference: "",
DisplayMissingEpisodes: false,
GroupedFolders: []string{},
SubtitleMode: "Default",
DisplayCollectionsView: false,
EnableLocalPassword: false,
OrderedViews: []string{},
LatestItemsExcludes: []string{},
MyMediaExcludes: []string{},
HidePlayedInLatest: true,
RememberAudioSelections: true,
RememberSubtitleSelections: true,
EnableNextEpisodeAutoPlay: true,
CastReceiverId: "",
}
}