- fix(storage): lock the user row when rotating a refresh token or changing a password, so on PostgreSQL a token minted during a password change can no longer survive the revoke-everything that runs at the same time - fix(auth): a replay of a just-rotated refresh token (two tabs, a retrying client) now fails without revoking the winner's new token; only a replay after RefreshReuseGrace is treated as theft and revokes every session - fix(auth): changing or resetting a password and revoking the user's refresh tokens now happen in one transaction - docs(auth): note that the last-admin rule relies on a single instance - test: password change racing with a refresh (25 rounds, both databases), grace window, winner's token still valid after concurrent rotation
145 lines
4.7 KiB
Go
145 lines
4.7 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
)
|
|
|
|
type refreshRow struct {
|
|
bun.BaseModel `bun:"table:refresh_tokens"`
|
|
|
|
ID int64 `bun:"id,pk,autoincrement"`
|
|
UserID int64 `bun:"user_id,notnull"`
|
|
TokenHash string `bun:"token_hash,notnull"`
|
|
CreatedAt int64 `bun:"created_at,notnull"`
|
|
ExpiresAt int64 `bun:"expires_at,notnull"`
|
|
RevokedAt sql.NullInt64 `bun:"revoked_at"`
|
|
}
|
|
|
|
// RefreshRepo stores refresh token hashes. It implements auth.RefreshStore.
|
|
type RefreshRepo struct{ db *bun.DB }
|
|
|
|
// NewRefreshRepo builds a RefreshRepo.
|
|
func NewRefreshRepo(db *bun.DB) *RefreshRepo { return &RefreshRepo{db: db} }
|
|
|
|
// SaveRefreshToken stores a new active token.
|
|
func (r *RefreshRepo) SaveRefreshToken(ctx context.Context, t auth.RefreshToken) error {
|
|
row := &refreshRow{
|
|
UserID: t.UserID, TokenHash: t.TokenHash,
|
|
CreatedAt: time.Now().Unix(), ExpiresAt: t.ExpiresAt.Unix(),
|
|
}
|
|
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
return fmt.Errorf("insert refresh token: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RotateRefreshToken revokes an active token and stores its successor in one
|
|
// transaction. The revoke is a single conditional UPDATE, so of any number of
|
|
// concurrent calls with the same token exactly one succeeds.
|
|
//
|
|
// The user row is locked first. That serialises the rotation with a password
|
|
// change (which also touches the user row) so a token minted here can never
|
|
// slip past a "revoke everything" running at the same time.
|
|
func (r *RefreshRepo) RotateRefreshToken(ctx context.Context, oldHash string, next auth.RefreshToken, now time.Time) (int64, error) {
|
|
var userID int64
|
|
|
|
err := r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
|
|
var old refreshRow
|
|
err := tx.NewSelect().Model(&old).Where("token_hash = ?", oldHash).Limit(1).Scan(ctx)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil // unknown token: reported below
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("select refresh token: %w", err)
|
|
}
|
|
if err := lockUser(ctx, tx, old.UserID); err != nil {
|
|
return err
|
|
}
|
|
|
|
res, err := tx.NewUpdate().Model((*refreshRow)(nil)).
|
|
Set("revoked_at = ?", now.Unix()).
|
|
Where("token_hash = ?", oldHash).
|
|
Where("revoked_at IS NULL").
|
|
Where("expires_at > ?", now.Unix()).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("revoke refresh token: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if n == 0 {
|
|
// Revoked or expired. Read the row again: it may have changed while
|
|
// we waited for the user lock.
|
|
var cur refreshRow
|
|
if err := tx.NewSelect().Model(&cur).Where("token_hash = ?", oldHash).Limit(1).Scan(ctx); err != nil {
|
|
return fmt.Errorf("reload refresh token: %w", err)
|
|
}
|
|
// Revoked long ago: somebody presented a spent token, assume theft
|
|
// and end every session. Revoked moments ago it is just two
|
|
// requests racing (two tabs, a retry), so only this call fails.
|
|
if cur.RevokedAt.Valid && now.Unix()-cur.RevokedAt.Int64 > int64(auth.RefreshReuseGrace/time.Second) {
|
|
return revokeUserTokens(ctx, tx, cur.UserID, now)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
userID = old.UserID
|
|
row := &refreshRow{
|
|
UserID: userID, TokenHash: next.TokenHash,
|
|
CreatedAt: now.Unix(), ExpiresAt: next.ExpiresAt.Unix(),
|
|
}
|
|
if _, err := tx.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
return fmt.Errorf("insert next refresh token: %w", err)
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if userID == 0 {
|
|
return 0, auth.ErrInvalidRefreshToken
|
|
}
|
|
return userID, nil
|
|
}
|
|
|
|
// lockUser takes the row lock of a user for the rest of the transaction.
|
|
func lockUser(ctx context.Context, tx bun.Tx, userID int64) error {
|
|
if _, err := tx.NewUpdate().Model((*userRow)(nil)).
|
|
Set("id = id").Where("id = ?", userID).Exec(ctx); err != nil {
|
|
return fmt.Errorf("lock user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// revokeUserTokens revokes every active refresh token of a user.
|
|
func revokeUserTokens(ctx context.Context, tx bun.Tx, userID int64, now time.Time) error {
|
|
_, err := tx.NewUpdate().Model((*refreshRow)(nil)).
|
|
Set("revoked_at = ?", now.Unix()).
|
|
Where("user_id = ?", userID).Where("revoked_at IS NULL").Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("revoke user refresh tokens: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RevokeRefreshToken revokes one token. Unknown or already revoked tokens are ignored.
|
|
func (r *RefreshRepo) RevokeRefreshToken(ctx context.Context, hash string, now time.Time) error {
|
|
_, err := r.db.NewUpdate().Model((*refreshRow)(nil)).
|
|
Set("revoked_at = ?", now.Unix()).
|
|
Where("token_hash = ?", hash).Where("revoked_at IS NULL").Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("revoke refresh token: %w", err)
|
|
}
|
|
return nil
|
|
}
|