sonda/internal/auth/token.go
tgiachi 52d1828b46 fix(auth): a token stops working when its account is deleted
SQLite gives the highest user id again after that user is deleted, and an access
token lives for minutes, so the token of a deleted user worked as whoever got the
id next (settings, taste, listens, account).

requireAuth now looks the account up after checking the token and refuses it when
the account is gone, has another name, or was created after the token was signed.
The token carries its issue time for this.

Tests: a unit test of every case, and the real scenario on SQLite (delete the
highest id, create another user, the old token gets 401, the new one works).

Closes #30
2026-11-11 19:25:09 +01:00

78 lines
2.1 KiB
Go

package auth
import (
"fmt"
"strconv"
"time"
"github.com/golang-jwt/jwt/v5"
)
const tokenIssuerName = "sonda"
// Claims is what a valid access token tells us about the caller.
type Claims struct {
UserID int64
Username string
// IssuedAt is when the token was signed. An account created after that moment
// cannot be the one the token was issued for.
IssuedAt time.Time
}
type tokenClaims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
// TokenIssuer creates and verifies HS256 JWT access tokens.
type TokenIssuer struct {
secret []byte
ttl time.Duration
now func() time.Time
}
// NewTokenIssuer builds an issuer. The secret must be long and random.
func NewTokenIssuer(secret string, ttl time.Duration) *TokenIssuer {
return &TokenIssuer{secret: []byte(secret), ttl: ttl, now: time.Now}
}
// Issue signs a token for user and returns it with its expiry time.
func (i *TokenIssuer) Issue(user User) (string, time.Time, error) {
now := i.now()
exp := now.Add(i.ttl)
claims := tokenClaims{Username: user.Username,
Issuer: tokenIssuerName,
Subject: strconv.FormatInt(user.ID, 10),
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(exp)}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(i.secret)
if err != nil {
return "", time.Time{}, fmt.Errorf("sign token: %w", err)
}
return signed, exp, nil
}
// Parse verifies the signature, algorithm, issuer and expiry of token.
func (i *TokenIssuer) Parse(token string) (Claims, error) {
var tc tokenClaims
_, err := jwt.ParseWithClaims(token, &tc,
func(*jwt.Token) (any, error) { return i.secret, nil },
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithIssuer(tokenIssuerName),
jwt.WithExpirationRequired(),
jwt.WithTimeFunc(i.now),
)
if err != nil {
return Claims{}, fmt.Errorf("invalid token: %w", err)
}
id, err := strconv.ParseInt(tc.Subject, 10, 64)
if err != nil || id <= 0 {
return Claims{}, fmt.Errorf("invalid token: bad subject")
}
var issued time.Time
if tc.IssuedAt != nil {
issued = tc.IssuedAt.Time
}
return Claims{UserID: id, Username: tc.Username, IssuedAt: issued}, nil
}