Files
wonderwall/pkg/session/lock.go
Trong Huu Nguyen c0138f4b49 feat(session): use locks for refreshing
One of the changes in OAuth 2.1 addresses attacks with refresh token
replays by recommending the use of one-time use tokens. A refresh token
is thus rotated and invalid after exactly one use, returning a new token
for each successful grant. Any further attempts must thus use the most
recently acquired refresh token. Reusing a refresh token may also
cause the authorization server to invalidate the current active refresh
token, requiring a refresh authorization grant to be reacquired for
further refresh token usage.

The use of locks prevents multiple refresh grant attempts for a given
session from happening across concurrent requests.
2022-09-04 17:14:35 +02:00

77 lines
1.3 KiB
Go

package session
import (
"context"
"errors"
"fmt"
"time"
"github.com/bsm/redislock"
"github.com/go-redis/redis/v8"
)
const (
KeyTemplate = "%s.lock"
)
var (
AcquireLockError = errors.New("could not acquire lock")
)
type Lock interface {
Acquire(ctx context.Context, duration time.Duration) error
Release(ctx context.Context) error
}
var _ Lock = &RedisLock{}
type RedisLock struct {
locker *redislock.Client
lock *redislock.Lock
key string
}
func NewRedisLock(client redis.Cmdable, key string) *RedisLock {
return &RedisLock{
locker: redislock.New(client),
key: key,
}
}
func (r *RedisLock) Acquire(ctx context.Context, duration time.Duration) error {
lock, err := r.locker.Obtain(ctx, lockKey(r.key), duration, nil)
if errors.Is(err, redislock.ErrNotObtained) {
return AcquireLockError
}
if err != nil {
return err
}
r.lock = lock
return nil
}
func (r *RedisLock) Release(ctx context.Context) error {
return r.lock.Release(ctx)
}
var _ Lock = &NoOpLock{}
type NoOpLock struct{}
func NewNoOpLock() *NoOpLock {
return new(NoOpLock)
}
func (n *NoOpLock) Acquire(_ context.Context, _ time.Duration) error {
return nil
}
func (n *NoOpLock) Release(_ context.Context) error {
return nil
}
func lockKey(key string) string {
return fmt.Sprintf(KeyTemplate, key)
}