mirror of
https://github.com/navidrome/navidrome.git
synced 2026-08-31 07:30:32 +00:00
* refactor(model): extract canonical 128-bit base62 id codec * feat(model): generate random ids as canonical 128-bit base62 values * feat(scanner): emit legacy PIDs in canonical base62 encoding * feat(db): add id canonicalization transform for the uniform-ids migration * feat(db): migrate all ids to canonical 128-bit base62 encoding * fix(db): canonicalize ids in junction tables and JSON columns * chore(jellyfin): update id-family notes for uniform canonical ids * test(ids): harden codec input contract and migration edge coverage * refactor(model): use log.Fatal for Encode128 contract guard per project convention * fix(db): force full rescan after id migration for legacy PID configs * test(db): guard id-column inventory against schema drift * refactor(ids): compile-time Encode128 contract and unified column rewrite helper * refactor(db): apply review feedback to id migration Filter empty strings in collectColumn's SQL, reuse a prepared statement for rewriteColumn updates, and clarify the legacy ID functions' comment now that they emit the canonical encoding. * feat(auth): split session and public-link JWT secrets, rotating sessions on id migration * test(subsonic): initialize public token secret in helpers suite The suite sets auth.TokenAuth directly instead of calling auth.Init, so the new PublicTokenAuth was nil whenever Ginkgo's spec order ran a helpers spec before any spec that calls auth.Init, panicking in publicurl.ImageURL. * refactor(db): inline canonicalID into its only consumer, the uniform-ids migration * refactor(model): rename Encode128/Decode128 to Encode/Decode With every id now exactly 128 bits, the width suffix is redundant; the package-qualified id.Encode/id.Decode carries the same information. * test(db): make the id-columns guard classify JSON columns too The guard only inspected columns named id/pid/*_id, so it could not see ids embedded in JSON. Widen it to *_ids and to every JSON column, and drive the "covered" set from a new embeddedIDColumns list instead of the inline calls in the migration. Every JSON column the schema has now carries a verdict. The four denormalized caches -- media_file/album.participants, media_file/album.tags, album.folder_ids and artist.similar_artists -- hold only artist, tag and folder ids. Those all come from id.NewHash, whose 22-char base62 encoding of a 128-bit MD5 is already in canonical range, so canonicalID is the identity on them and the migration correctly leaves them alone. A new codec test pins that invariant, since the exemptions depend on it. Verified on a copy of a 727MB/96k-track production database: canonicalizing those four columns changed zero rows, and artist, tag and folder ids were themselves unchanged by the migration (only media_file ids moved, 95108 of 96666).
159 lines
4.5 KiB
Go
159 lines
4.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"crypto/sha256"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/go-chi/jwtauth/v5"
|
|
"github.com/lestrrat-go/jwx/v3/jwt"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/consts"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/model/id"
|
|
"github.com/navidrome/navidrome/model/request"
|
|
"github.com/navidrome/navidrome/utils"
|
|
)
|
|
|
|
var (
|
|
once sync.Once
|
|
// TokenAuth signs UI/API session tokens. Rotated by the id migration so stale sessions die.
|
|
TokenAuth *jwtauth.JWTAuth
|
|
// PublicTokenAuth signs public-link tokens (artwork, share streams), on a separate secret that survives the rotation.
|
|
PublicTokenAuth *jwtauth.JWTAuth
|
|
)
|
|
|
|
// Init creates the JWTAuth objects from the secrets stored in the DB.
|
|
// Missing or undecryptable secrets are regenerated and stored.
|
|
func Init(ds model.DataStore) {
|
|
once.Do(func() {
|
|
ctx := context.TODO()
|
|
log.Info("Setting Session Timeout", "value", conf.Server.SessionTimeout)
|
|
|
|
TokenAuth = jwtauth.New("HS256", []byte(loadOrCreateSecret(ctx, ds, consts.JWTSecretKey)), nil)
|
|
PublicTokenAuth = jwtauth.New("HS256", []byte(loadOrCreateSecret(ctx, ds, consts.JWTPublicSecretKey)), nil)
|
|
})
|
|
}
|
|
|
|
func loadOrCreateSecret(ctx context.Context, ds model.DataStore, key string) string {
|
|
secret, err := ds.Property(ctx).Get(key)
|
|
if err != nil || secret == "" {
|
|
log.Info(ctx, "Creating new JWT secret", "key", key)
|
|
return createNewSecret(ctx, ds, key)
|
|
}
|
|
if secret, err = utils.Decrypt(ctx, getEncKey(), secret); err != nil {
|
|
log.Error(ctx, "Could not decrypt JWT secret, creating a new one", "key", key, err)
|
|
return createNewSecret(ctx, ds, key)
|
|
}
|
|
return secret
|
|
}
|
|
|
|
func CreatePublicToken(claims Claims) (string, error) {
|
|
claims.Issuer = consts.JWTIssuer
|
|
_, token, err := PublicTokenAuth.Encode(claims.ToMap())
|
|
return token, err
|
|
}
|
|
|
|
func CreateExpiringPublicToken(exp time.Time, claims Claims) (string, error) {
|
|
claims.Issuer = consts.JWTIssuer
|
|
if !exp.IsZero() {
|
|
claims.ExpiresAt = exp
|
|
}
|
|
_, token, err := PublicTokenAuth.Encode(claims.ToMap())
|
|
return token, err
|
|
}
|
|
|
|
func CreateToken(u *model.User) (string, error) {
|
|
claims := Claims{
|
|
Issuer: consts.JWTIssuer,
|
|
Subject: u.UserName,
|
|
IssuedAt: time.Now(),
|
|
UserID: u.ID,
|
|
IsAdmin: u.IsAdmin,
|
|
}
|
|
token, _, err := TokenAuth.Encode(claims.ToMap())
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return TouchToken(token)
|
|
}
|
|
|
|
func TouchToken(token jwt.Token) (string, error) {
|
|
claims := ClaimsFromToken(token).
|
|
WithExpiresAt(time.Now().UTC().Add(conf.Server.SessionTimeout))
|
|
_, newToken, err := TokenAuth.Encode(claims.ToMap())
|
|
return newToken, err
|
|
}
|
|
|
|
func Validate(tokenStr string) (Claims, error) {
|
|
token, err := jwtauth.VerifyToken(TokenAuth, tokenStr)
|
|
if err != nil {
|
|
return Claims{}, err
|
|
}
|
|
return ClaimsFromToken(token), nil
|
|
}
|
|
|
|
// ValidatePublic verifies a public-link token against the public secret.
|
|
func ValidatePublic(tokenStr string) (Claims, error) {
|
|
token, err := jwtauth.VerifyToken(PublicTokenAuth, tokenStr)
|
|
if err != nil {
|
|
return Claims{}, err
|
|
}
|
|
return ClaimsFromToken(token), nil
|
|
}
|
|
|
|
func WithAdminUser(ctx context.Context, ds model.DataStore) context.Context {
|
|
u, err := ds.User(ctx).FindFirstAdmin()
|
|
if err != nil {
|
|
c, err := ds.User(ctx).CountAll()
|
|
if c == 0 && err == nil {
|
|
log.Debug(ctx, "No admin user yet!", err)
|
|
} else {
|
|
log.Error(ctx, "No admin user found!", err)
|
|
}
|
|
u = &model.User{IsAdmin: true, UserName: "admin"}
|
|
}
|
|
|
|
ctx = request.WithUsername(ctx, u.UserName)
|
|
return request.WithUser(ctx, *u)
|
|
}
|
|
|
|
func createNewSecret(ctx context.Context, ds model.DataStore, key string) string {
|
|
secret := id.NewRandom()
|
|
encSecret, err := utils.Encrypt(ctx, getEncKey(), secret)
|
|
if err != nil {
|
|
log.Error(ctx, "Could not encrypt JWT secret", err)
|
|
return secret
|
|
}
|
|
if err := ds.Property(ctx).Put(key, encSecret); err != nil {
|
|
log.Error(ctx, "Could not save JWT secret in DB", err)
|
|
}
|
|
return secret
|
|
}
|
|
|
|
// EncodeToken creates a signed JWT from an arbitrary claims map.
|
|
// It sets the issuer claim automatically.
|
|
func EncodeToken(claims map[string]any) (string, error) {
|
|
claims[jwt.IssuerKey] = consts.JWTIssuer
|
|
_, token, err := TokenAuth.Encode(claims)
|
|
return token, err
|
|
}
|
|
|
|
// DecodeAndVerifyToken verifies a JWT string and returns the parsed token.
|
|
func DecodeAndVerifyToken(tokenStr string) (jwt.Token, error) {
|
|
return jwtauth.VerifyToken(TokenAuth, tokenStr)
|
|
}
|
|
|
|
func getEncKey() []byte {
|
|
key := cmp.Or(
|
|
conf.Server.PasswordEncryptionKey,
|
|
consts.DefaultEncryptionKey,
|
|
)
|
|
sum := sha256.Sum256([]byte(key))
|
|
return sum[:]
|
|
}
|