fix(auth): close session races found in review
- 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
This commit is contained in:
parent
dbe9338af3
commit
7e59bd26af
6 changed files with 225 additions and 83 deletions
|
|
@ -78,7 +78,7 @@ func TestMe(t *testing.T) {
|
|||
|
||||
// ---- refresh, logout ----
|
||||
|
||||
func TestRefreshRotatesAndOldTokenIsDead(t *testing.T) {
|
||||
func TestRefreshRotatesAndOldTokenCannotBeReplayed(t *testing.T) {
|
||||
h := newTestAPI(t)
|
||||
registerAndLogin(t, h)
|
||||
first := loginSession(t, h, "alice", "longenough")
|
||||
|
|
@ -96,14 +96,16 @@ func TestRefreshRotatesAndOldTokenIsDead(t *testing.T) {
|
|||
t.Errorf("new access token: %d", r.Code)
|
||||
}
|
||||
|
||||
// Replaying the spent token fails and kills the newer one too.
|
||||
// Replaying the spent token fails. Right after a rotation that is treated as
|
||||
// a race (two tabs), so the newer token keeps working; reuse long after the
|
||||
// rotation revoking every session is covered in the auth and storage tests.
|
||||
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": str(first, "refresh_token")})
|
||||
if r.Code != http.StatusUnauthorized || errCode(r) != "invalid_refresh_token" {
|
||||
t.Fatalf("reuse: %d %v", r.Code, r.Body)
|
||||
t.Fatalf("replay: %d %v", r.Code, r.Body)
|
||||
}
|
||||
r = do(t, h, "POST", "/api/v1/auth/refresh", "", map[string]string{"refresh_token": second})
|
||||
if r.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("after reuse the newer token must be dead: %d", r.Code)
|
||||
if r.Code != http.StatusOK {
|
||||
t.Fatalf("the newer token must survive a replay inside the grace window: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -33,6 +33,11 @@ const (
|
|||
maxPasswordLen = 256 // caps the work an attacker can force on the KDF
|
||||
)
|
||||
|
||||
// RefreshReuseGrace is how long after a rotation the old refresh token is
|
||||
// treated as a harmless race (two tabs, a client retrying) instead of theft.
|
||||
// Inside the window the replay fails but the user's other sessions survive.
|
||||
const RefreshReuseGrace = 10 * time.Second
|
||||
|
||||
// User is a local account. The password hash never leaves the store layer.
|
||||
type User struct {
|
||||
ID int64
|
||||
|
|
@ -60,8 +65,11 @@ type UserStore interface {
|
|||
ListUsers(ctx context.Context) ([]User, error)
|
||||
// The three below return ErrUserNotFound for an unknown id.
|
||||
SetAdmin(ctx context.Context, id int64, isAdmin bool) error
|
||||
SetPasswordHash(ctx context.Context, id int64, passwordHash string) error
|
||||
DeleteUser(ctx context.Context, id int64) error
|
||||
// SetPasswordHash replaces the hash and, in the same transaction, revokes
|
||||
// every refresh token of the user: a password change signs them out
|
||||
// everywhere, with no window where the password changed but sessions live.
|
||||
SetPasswordHash(ctx context.Context, id int64, passwordHash string, now time.Time) error
|
||||
}
|
||||
|
||||
// RefreshStore is what the service needs to persist refresh tokens.
|
||||
|
|
@ -70,12 +78,12 @@ type RefreshStore interface {
|
|||
// RotateRefreshToken atomically revokes the active, unexpired token with
|
||||
// hash oldHash and stores next for the same user, returning that user.
|
||||
// An unknown or expired token gives ErrInvalidRefreshToken. A token that
|
||||
// was already revoked is a reuse: every token of its user is revoked and
|
||||
// was already revoked is a reuse: unless it was revoked less than
|
||||
// RefreshReuseGrace ago, every token of its user is revoked. Either way
|
||||
// ErrInvalidRefreshToken is returned.
|
||||
RotateRefreshToken(ctx context.Context, oldHash string, next RefreshToken, now time.Time) (userID int64, err error)
|
||||
// RevokeRefreshToken is idempotent and ignores unknown tokens.
|
||||
RevokeRefreshToken(ctx context.Context, hash string, now time.Time) error
|
||||
RevokeUserRefreshTokens(ctx context.Context, userID int64, now time.Time) error
|
||||
}
|
||||
|
||||
// Session is what a client receives after logging in or refreshing.
|
||||
|
|
@ -95,7 +103,11 @@ type Service struct {
|
|||
refreshTTL time.Duration
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex // serialises registration and admin changes (last-admin rule)
|
||||
// mu serialises registration and admin changes inside this process, which
|
||||
// is what keeps the last-admin rule. Sonda is a single-instance server: two
|
||||
// instances on one PostgreSQL database could still demote the last two
|
||||
// admins at the same time.
|
||||
mu sync.Mutex
|
||||
dummyOnce sync.Once
|
||||
dummyHash string
|
||||
}
|
||||
|
|
@ -279,10 +291,7 @@ func (s *Service) setPassword(ctx context.Context, userID int64, password string
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.users.SetPasswordHash(ctx, userID, hash); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.refresh.RevokeUserRefreshTokens(ctx, userID, s.now())
|
||||
return s.users.SetPasswordHash(ctx, userID, hash, s.now())
|
||||
}
|
||||
|
||||
// ---- admin ----
|
||||
|
|
|
|||
|
|
@ -16,18 +16,18 @@ type fakeUserRow struct {
|
|||
}
|
||||
|
||||
type fakeRefreshRow struct {
|
||||
userID int64
|
||||
expires time.Time
|
||||
revoked bool
|
||||
userID int64
|
||||
expires time.Time
|
||||
revoked bool
|
||||
revokedAt time.Time
|
||||
}
|
||||
|
||||
// fakeStore implements UserStore and RefreshStore in memory, following the
|
||||
// same rules as the real repositories.
|
||||
type fakeStore struct {
|
||||
users map[int64]*fakeUserRow
|
||||
tokens map[string]*fakeRefreshRow // by hash
|
||||
nextID int64
|
||||
revokes int
|
||||
users map[int64]*fakeUserRow
|
||||
tokens map[string]*fakeRefreshRow // by hash
|
||||
nextID int64
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
|
|
@ -100,12 +100,13 @@ func (f *fakeStore) SetAdmin(_ context.Context, id int64, isAdmin bool) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) SetPasswordHash(_ context.Context, id int64, hash string) error {
|
||||
func (f *fakeStore) SetPasswordHash(_ context.Context, id int64, hash string, now time.Time) error {
|
||||
r, ok := f.users[id]
|
||||
if !ok {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
r.hash = hash
|
||||
f.revokeUser(id, now) // same transaction in the real store
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -127,36 +128,36 @@ func (f *fakeStore) SaveRefreshToken(_ context.Context, t RefreshToken) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RotateRefreshToken(ctx context.Context, oldHash string, next RefreshToken, now time.Time) (int64, error) {
|
||||
func (f *fakeStore) revokeUser(userID int64, now time.Time) {
|
||||
for _, t := range f.tokens {
|
||||
if t.userID == userID && !t.revoked {
|
||||
t.revoked, t.revokedAt = true, now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeStore) RotateRefreshToken(_ context.Context, oldHash string, next RefreshToken, now time.Time) (int64, error) {
|
||||
t, ok := f.tokens[oldHash]
|
||||
if !ok {
|
||||
return 0, ErrInvalidRefreshToken
|
||||
}
|
||||
if t.revoked {
|
||||
_ = f.RevokeUserRefreshTokens(ctx, t.userID, now) // reuse: kill every session
|
||||
if now.Sub(t.revokedAt) > RefreshReuseGrace {
|
||||
f.revokeUser(t.userID, now) // reuse after the grace window: assume theft
|
||||
}
|
||||
return 0, ErrInvalidRefreshToken
|
||||
}
|
||||
if !now.Before(t.expires) {
|
||||
return 0, ErrInvalidRefreshToken
|
||||
}
|
||||
t.revoked = true
|
||||
t.revoked, t.revokedAt = true, now
|
||||
f.tokens[next.TokenHash] = &fakeRefreshRow{userID: t.userID, expires: next.ExpiresAt}
|
||||
return t.userID, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RevokeRefreshToken(_ context.Context, hash string, _ time.Time) error {
|
||||
if t, ok := f.tokens[hash]; ok {
|
||||
t.revoked = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RevokeUserRefreshTokens(_ context.Context, userID int64, _ time.Time) error {
|
||||
f.revokes++
|
||||
for _, t := range f.tokens {
|
||||
if t.userID == userID {
|
||||
t.revoked = true
|
||||
}
|
||||
func (f *fakeStore) RevokeRefreshToken(_ context.Context, hash string, now time.Time) error {
|
||||
if t, ok := f.tokens[hash]; ok && !t.revoked {
|
||||
t.revoked, t.revokedAt = true, now
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -272,7 +273,8 @@ func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
|
|||
first, _ := s.Login(ctx, "alice", "longenough")
|
||||
second, _ := s.Refresh(ctx, first.RefreshToken)
|
||||
|
||||
// Presenting the already-rotated token looks like theft.
|
||||
// Well after the grace window, presenting the rotated token looks like theft.
|
||||
s.now = func() time.Time { return time.Now().Add(RefreshReuseGrace + time.Minute) }
|
||||
if _, err := s.Refresh(ctx, first.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
||||
t.Fatalf("reuse: err = %v, want ErrInvalidRefreshToken", err)
|
||||
}
|
||||
|
|
@ -282,6 +284,25 @@ func TestReusedRefreshTokenRevokesEverySession(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// Two tabs, or a client retrying in parallel, present the same token almost
|
||||
// at once. The loser fails but must not log the winner out.
|
||||
func TestReplayInsideTheGraceWindowKeepsTheNewToken(t *testing.T) {
|
||||
s, _, _ := bootstrap(t)
|
||||
ctx := context.Background()
|
||||
first, _ := s.Login(ctx, "alice", "longenough")
|
||||
second, err := s.Refresh(ctx, first.RefreshToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := s.Refresh(ctx, first.RefreshToken); !errors.Is(err, ErrInvalidRefreshToken) {
|
||||
t.Fatalf("the replay itself must still fail: err = %v", err)
|
||||
}
|
||||
if _, err := s.Refresh(ctx, second.RefreshToken); err != nil {
|
||||
t.Fatalf("a replay inside the grace window must not revoke the new token: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshRejectsExpiredUnknownAndEmpty(t *testing.T) {
|
||||
s, _, _ := bootstrap(t)
|
||||
ctx := context.Background()
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ func TestUserRepoRolesAndLookup(t *testing.T) {
|
|||
t.Error("demotion not stored")
|
||||
}
|
||||
|
||||
if err := repo.SetPasswordHash(ctx, bob.ID, "h3"); err != nil {
|
||||
if err := repo.SetPasswordHash(ctx, bob.ID, "h3", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, hash, _ := repo.UserByID(ctx, bob.ID); hash != "h3" {
|
||||
|
|
@ -83,7 +83,7 @@ func TestUserRepoUnknownIDs(t *testing.T) {
|
|||
if err := repo.SetAdmin(ctx, 999, true); !errors.Is(err, auth.ErrUserNotFound) {
|
||||
t.Errorf("SetAdmin: %v", err)
|
||||
}
|
||||
if err := repo.SetPasswordHash(ctx, 999, "x"); !errors.Is(err, auth.ErrUserNotFound) {
|
||||
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) {
|
||||
|
|
@ -157,8 +157,9 @@ func TestRefreshRepoReuseRevokesEveryTokenOfTheUser(t *testing.T) {
|
|||
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a2", ExpiresAt: now.Add(time.Hour)}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Replaying a1 is a reuse.
|
||||
if _, err := repo.RotateRefreshToken(ctx, "a1", auth.RefreshToken{TokenHash: "a3", ExpiresAt: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
||||
// 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)
|
||||
}
|
||||
|
||||
|
|
@ -166,7 +167,7 @@ func TestRefreshRepoReuseRevokesEveryTokenOfTheUser(t *testing.T) {
|
|||
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: now.Add(time.Hour)}, now); !errors.Is(err, auth.ErrInvalidRefreshToken) {
|
||||
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 {
|
||||
|
|
@ -175,6 +176,30 @@ func TestRefreshRepoReuseRevokesEveryTokenOfTheUser(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
|
@ -183,6 +208,7 @@ func TestRefreshRepoConcurrentRotationHasOneWinner(t *testing.T) {
|
|||
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)
|
||||
|
|
@ -191,6 +217,7 @@ func TestRefreshRepoConcurrentRotationHasOneWinner(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
|
|
@ -198,6 +225,11 @@ func TestRefreshRepoConcurrentRotationHasOneWinner(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -221,14 +253,69 @@ func TestRefreshRepoRevoke(t *testing.T) {
|
|||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// t1 above was a reuse and revoked t2 as well; start again to test RevokeUser alone.
|
||||
uid2 := newUserWithToken(t, db, "bob", "b1", now.Add(time.Hour))
|
||||
if err := repo.RevokeUserRefreshTokens(ctx, uid2, now); err != nil {
|
||||
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", uid2); n != 0 {
|
||||
t.Errorf("active tokens = %d, want 0", n)
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,11 +44,26 @@ func (r *RefreshRepo) SaveRefreshToken(ctx context.Context, t auth.RefreshToken)
|
|||
// 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
|
||||
var reused bool
|
||||
|
||||
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).
|
||||
|
|
@ -63,26 +78,18 @@ func (r *RefreshRepo) RotateRefreshToken(ctx context.Context, oldHash string, ne
|
|||
return err
|
||||
}
|
||||
|
||||
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: nothing to do, reported below
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("select refresh token: %w", err)
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
// Known token that is revoked or expired. Revoked means somebody
|
||||
// presented a spent token: assume theft and end every session.
|
||||
if old.RevokedAt.Valid {
|
||||
reused = true
|
||||
_, err := tx.NewUpdate().Model((*refreshRow)(nil)).
|
||||
Set("revoked_at = ?", now.Unix()).
|
||||
Where("user_id = ?", old.UserID).Where("revoked_at IS NULL").Exec(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke user tokens: %w", err)
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
|
@ -100,12 +107,32 @@ func (r *RefreshRepo) RotateRefreshToken(ctx context.Context, oldHash string, ne
|
|||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if userID == 0 || reused {
|
||||
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)).
|
||||
|
|
@ -116,14 +143,3 @@ func (r *RefreshRepo) RevokeRefreshToken(ctx context.Context, hash string, now t
|
|||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeUserRefreshTokens revokes every active token of a user.
|
||||
func (r *RefreshRepo) RevokeUserRefreshTokens(ctx context.Context, userID int64, now time.Time) error {
|
||||
_, err := r.db.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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,11 +110,18 @@ func (r *UserRepo) SetAdmin(ctx context.Context, id int64, isAdmin bool) error {
|
|||
return affectedOrNotFound(res, err, "set admin")
|
||||
}
|
||||
|
||||
// SetPasswordHash replaces the stored password hash.
|
||||
func (r *UserRepo) SetPasswordHash(ctx context.Context, id int64, passwordHash string) error {
|
||||
res, err := r.db.NewUpdate().Model((*userRow)(nil)).
|
||||
Set("password_hash = ?", passwordHash).Where("id = ?", id).Exec(ctx)
|
||||
return affectedOrNotFound(res, err, "set password")
|
||||
// SetPasswordHash replaces the password hash and revokes every refresh token of
|
||||
// the user in the same transaction. Updating the user row first also takes its
|
||||
// lock, so the change is serialised with any refresh in flight for that user.
|
||||
func (r *UserRepo) SetPasswordHash(ctx context.Context, id int64, passwordHash string, now time.Time) error {
|
||||
return r.db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {
|
||||
res, err := tx.NewUpdate().Model((*userRow)(nil)).
|
||||
Set("password_hash = ?", passwordHash).Where("id = ?", id).Exec(ctx)
|
||||
if err := affectedOrNotFound(res, err, "set password"); err != nil {
|
||||
return err
|
||||
}
|
||||
return revokeUserTokens(ctx, tx, id, now)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteUser removes a user; their refresh tokens and listening events go with them.
|
||||
|
|
|
|||
Loading…
Reference in a new issue