- 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
333 lines
12 KiB
Go
333 lines
12 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"codeberg.org/squidd/sonda/internal/auth"
|
|
)
|
|
|
|
func TestUserRepoRolesAndLookup(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewUserRepo(db)
|
|
|
|
alice, err := repo.CreateUser(ctx, "alice", "h1", true)
|
|
if err != nil || !alice.IsAdmin {
|
|
t.Fatalf("alice = %+v err=%v", alice, err)
|
|
}
|
|
bob, err := repo.CreateUser(ctx, "bob", "h2", false)
|
|
if err != nil || bob.IsAdmin {
|
|
t.Fatalf("bob = %+v err=%v", bob, err)
|
|
}
|
|
|
|
if n, _ := repo.CountAdmins(ctx); n != 1 {
|
|
t.Errorf("CountAdmins = %d, want 1", n)
|
|
}
|
|
got, hash, err := repo.UserByID(ctx, bob.ID)
|
|
if err != nil || got.Username != "bob" || hash != "h2" || got.IsAdmin {
|
|
t.Errorf("UserByID = %+v %q err=%v", got, hash, err)
|
|
}
|
|
byName, _, _ := repo.UserByUsername(ctx, "ALICE")
|
|
if !byName.IsAdmin {
|
|
t.Error("UserByUsername lost the admin flag")
|
|
}
|
|
|
|
list, err := repo.ListUsers(ctx)
|
|
if err != nil || len(list) != 2 || list[0].ID != alice.ID || list[1].ID != bob.ID {
|
|
t.Fatalf("ListUsers = %+v err=%v", list, err)
|
|
}
|
|
|
|
if err := repo.SetAdmin(ctx, bob.ID, true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n, _ := repo.CountAdmins(ctx); n != 2 {
|
|
t.Errorf("CountAdmins after promote = %d, want 2", n)
|
|
}
|
|
if err := repo.SetAdmin(ctx, bob.ID, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if u, _, _ := repo.UserByID(ctx, bob.ID); u.IsAdmin {
|
|
t.Error("demotion not stored")
|
|
}
|
|
|
|
if err := repo.SetPasswordHash(ctx, bob.ID, "h3", time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, hash, _ := repo.UserByID(ctx, bob.ID); hash != "h3" {
|
|
t.Errorf("password hash = %q", hash)
|
|
}
|
|
|
|
if err := repo.DeleteUser(ctx, bob.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, _, err := repo.UserByID(ctx, bob.ID); !errors.Is(err, auth.ErrUserNotFound) {
|
|
t.Errorf("after delete: err = %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestUserRepoUnknownIDs(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewUserRepo(db)
|
|
if _, _, err := repo.UserByID(ctx, 999); !errors.Is(err, auth.ErrUserNotFound) {
|
|
t.Errorf("UserByID: %v", err)
|
|
}
|
|
if err := repo.SetAdmin(ctx, 999, true); !errors.Is(err, auth.ErrUserNotFound) {
|
|
t.Errorf("SetAdmin: %v", err)
|
|
}
|
|
if err := repo.SetPasswordHash(ctx, 999, "x", time.Now()); !errors.Is(err, auth.ErrUserNotFound) {
|
|
t.Errorf("SetPasswordHash: %v", err)
|
|
}
|
|
if err := repo.DeleteUser(ctx, 999); !errors.Is(err, auth.ErrUserNotFound) {
|
|
t.Errorf("DeleteUser: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func newUserWithToken(t *testing.T, db *bun.DB, name, hash string, expires time.Time) int64 {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
u, err := NewUserRepo(db).CreateUser(ctx, name, "h", false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := NewRefreshRepo(db).SaveRefreshToken(ctx, auth.RefreshToken{UserID: u.ID, TokenHash: hash, ExpiresAt: expires}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u.ID
|
|
}
|
|
|
|
func TestRefreshRepoRotate(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
uid := newUserWithToken(t, db, "alice", "hash-a", now.Add(time.Hour))
|
|
|
|
got, err := repo.RotateRefreshToken(ctx, "hash-a", auth.RefreshToken{TokenHash: "hash-b", ExpiresAt: now.Add(time.Hour)}, now)
|
|
if err != nil || got != uid {
|
|
t.Fatalf("rotate: uid=%d err=%v, want %d", got, err, uid)
|
|
}
|
|
// The new token is usable, the old one is spent.
|
|
if _, err := repo.RotateRefreshToken(ctx, "hash-b", auth.RefreshToken{TokenHash: "hash-c", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
|
|
t.Fatalf("rotating the new token: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestRefreshRepoRejectsUnknownAndExpired(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
newUserWithToken(t, db, "alice", "old", now.Add(-time.Minute))
|
|
|
|
next := auth.RefreshToken{TokenHash: "next", ExpiresAt: now.Add(time.Hour)}
|
|
if _, err := repo.RotateRefreshToken(ctx, "nope", next, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Errorf("unknown: %v", err)
|
|
}
|
|
if _, err := repo.RotateRefreshToken(ctx, "old", next, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Errorf("expired: %v", err)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE token_hash = 'next'"); n != 0 {
|
|
t.Error("a failed rotation must not store the next token")
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestRefreshRepoReuseRevokesEveryTokenOfTheUser(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
uid := newUserWithToken(t, db, "alice", "a1", now.Add(time.Hour))
|
|
if err := repo.SaveRefreshToken(ctx, auth.RefreshToken{UserID: uid, TokenHash: "other-device", ExpiresAt: now.Add(time.Hour)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
bobID := newUserWithToken(t, db, "bob", "bob-token", now.Add(time.Hour))
|
|
|
|
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a2", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// Replaying a1 well after the grace window is a reuse.
|
|
later := now.Add(auth.RefreshReuseGrace + time.Minute)
|
|
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a3", ExpiresAt: later.Add(time.Hour)}, later); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Fatalf("reuse: %v", err)
|
|
}
|
|
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", uid); n != 0 {
|
|
t.Errorf("%d active tokens left for the user after a reuse, want 0", n)
|
|
}
|
|
// The revocation must survive the failed call.
|
|
if _, err := repo.RotateRefreshToken(ctx, "a2", auth.RefreshToken{TokenHash: "a4", ExpiresAt: later.Add(time.Hour)}, later); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Errorf("a2 should be revoked: %v", err)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", bobID); n != 1 {
|
|
t.Errorf("another user's token was revoked (active = %d)", n)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Two tabs refresh at once: the loser fails, the winner's new token survives.
|
|
func TestRefreshRepoReplayInsideGraceKeepsNewTokens(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
uid := newUserWithToken(t, db, "alice", "a1", now.Add(time.Hour))
|
|
|
|
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a2", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
soon := now.Add(time.Second)
|
|
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a3", ExpiresAt: soon.Add(time.Hour)}, soon); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Fatalf("the replay must still fail: %v", err)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND token_hash = 'a2' AND revoked_at IS NULL", uid); n != 1 {
|
|
t.Fatal("a replay inside the grace window revoked the new token")
|
|
}
|
|
if _, err := repo.RotateRefreshToken(ctx, "a2", auth.RefreshToken{TokenHash: "a4", ExpiresAt: soon.Add(time.Hour)}, soon); err != nil {
|
|
t.Errorf("the new token must keep working: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestRefreshRepoConcurrentRotationHasOneWinner(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
newUserWithToken(t, db, "alice", "shared", now.Add(time.Hour))
|
|
|
|
var wins atomic.Int64
|
|
var winner atomic.Value
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 8; i++ {
|
|
wg.Add(1)
|
|
go func(i int) {
|
|
defer wg.Done()
|
|
next := auth.RefreshToken{TokenHash: "next-" + string(rune('a'+i)), ExpiresAt: now.Add(time.Hour)}
|
|
if _, err := repo.RotateRefreshToken(ctx, "shared", next, now); err == nil {
|
|
wins.Add(1)
|
|
winner.Store(next.TokenHash)
|
|
}
|
|
}(i)
|
|
}
|
|
wg.Wait()
|
|
if wins.Load() != 1 {
|
|
t.Fatalf("%d concurrent rotations of the same token succeeded, want exactly 1", wins.Load())
|
|
}
|
|
// The losers must not have revoked the winner's new token.
|
|
hash, _ := winner.Load().(string)
|
|
if _, err := repo.RotateRefreshToken(ctx, hash, auth.RefreshToken{TokenHash: "after", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
|
|
t.Errorf("the winner's token is dead: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestRefreshRepoRevoke(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
repo := NewRefreshRepo(db)
|
|
now := time.Now()
|
|
uid := newUserWithToken(t, db, "alice", "t1", now.Add(time.Hour))
|
|
_ = repo.SaveRefreshToken(ctx, auth.RefreshToken{UserID: uid, TokenHash: "t2", ExpiresAt: now.Add(time.Hour)})
|
|
|
|
if err := repo.RevokeRefreshToken(ctx, "t1", now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := repo.RevokeRefreshToken(ctx, "t1", now); err != nil { // idempotent
|
|
t.Fatal(err)
|
|
}
|
|
if err := repo.RevokeRefreshToken(ctx, "unknown", now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := repo.RotateRefreshToken(ctx, "t1", auth.RefreshToken{TokenHash: "x", ExpiresAt: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
|
t.Errorf("revoked token still rotates: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestSetPasswordHashRevokesTheUsersRefreshTokens(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
now := time.Now()
|
|
alice := newUserWithToken(t, db, "alice", "a1", now.Add(time.Hour))
|
|
_ = NewRefreshRepo(db).SaveRefreshToken(ctx, auth.RefreshToken{UserID: alice, TokenHash: "a2", ExpiresAt: now.Add(time.Hour)})
|
|
bob := newUserWithToken(t, db, "bob", "b1", now.Add(time.Hour))
|
|
|
|
if err := NewUserRepo(db).SetPasswordHash(ctx, alice, "new-hash", now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", alice); n != 0 {
|
|
t.Errorf("alice has %d active tokens after a password change, want 0", n)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", bob); n != 1 {
|
|
t.Errorf("bob's token was revoked (active = %d)", n)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A password change racing with a refresh must never leave a live session
|
|
// behind: whichever order they run in, the user ends up with no active tokens.
|
|
func TestPasswordChangeRacingWithRefreshLeavesNoLiveToken(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
ctx := context.Background()
|
|
refresh, users := NewRefreshRepo(db), NewUserRepo(db)
|
|
now := time.Now()
|
|
uid := newUserWithToken(t, db, "alice", "t-0", now.Add(time.Hour))
|
|
|
|
for i := 0; i < 25; i++ {
|
|
cur := "t-" + string(rune('a'+i))
|
|
prev := "t-0"
|
|
if i > 0 {
|
|
prev = "t-" + string(rune('a'+i-1))
|
|
}
|
|
// Make sure there is one active token to fight over.
|
|
if i > 0 {
|
|
if err := refresh.SaveRefreshToken(ctx, auth.RefreshToken{UserID: uid, TokenHash: cur + "-seed", ExpiresAt: now.Add(time.Hour)}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
prev = cur + "-seed"
|
|
}
|
|
|
|
var wg sync.WaitGroup
|
|
wg.Add(2)
|
|
go func() {
|
|
defer wg.Done()
|
|
_, _ = refresh.RotateRefreshToken(ctx, prev, auth.RefreshToken{TokenHash: cur + "-next", ExpiresAt: now.Add(time.Hour)}, now)
|
|
}()
|
|
go func() {
|
|
defer wg.Done()
|
|
if err := users.SetPasswordHash(ctx, uid, "hash", now); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}()
|
|
wg.Wait()
|
|
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens WHERE user_id = ? AND revoked_at IS NULL", uid); n != 0 {
|
|
t.Fatalf("round %d: %d active tokens survived a password change", i, n)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestDeletingAUserDeletesTheirRefreshTokens(t *testing.T) {
|
|
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
|
uid := newUserWithToken(t, db, "alice", "t1", time.Now().Add(time.Hour))
|
|
if err := NewUserRepo(db).DeleteUser(context.Background(), uid); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n := count(t, db, "SELECT COUNT(*) FROM refresh_tokens"); n != 0 {
|
|
t.Errorf("refresh tokens left = %d, want 0", n)
|
|
}
|
|
})
|
|
}
|