Build and Deploy / lint-frontend (push) Canceled after 0s
Build and Deploy / build-backend (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 0s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / test-backend (push) Canceled after 10s
103 lines
2.3 KiB
Go
103 lines
2.3 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type RateLimitConfig struct {
|
|
Max int
|
|
Window time.Duration
|
|
BlockFor time.Duration
|
|
}
|
|
|
|
var (
|
|
LoginRateLimit = RateLimitConfig{
|
|
Max: 10,
|
|
Window: 15 * time.Minute,
|
|
BlockFor: 15 * time.Minute,
|
|
}
|
|
|
|
RegisterRateLimit = RateLimitConfig{
|
|
Max: 5,
|
|
Window: time.Hour,
|
|
}
|
|
|
|
TokenRateLimit = RateLimitConfig{
|
|
Max: 20,
|
|
Window: time.Minute,
|
|
BlockFor: 5 * time.Minute,
|
|
}
|
|
|
|
RevokeRateLimit = RateLimitConfig{
|
|
Max: 30,
|
|
Window: time.Minute,
|
|
}
|
|
|
|
RefreshRateLimit = RateLimitConfig{
|
|
Max: 30,
|
|
Window: time.Minute,
|
|
BlockFor: 5 * time.Minute,
|
|
}
|
|
)
|
|
|
|
type RateLimiter struct {
|
|
redis *redis.Client
|
|
}
|
|
|
|
func NewRateLimiter(rdb *redis.Client) *RateLimiter {
|
|
return &RateLimiter{redis: rdb}
|
|
}
|
|
|
|
func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig) (bool, int, error) {
|
|
blockKey := fmt.Sprintf("rl_block:%s", key)
|
|
counterKey := fmt.Sprintf("rl_count:%s", key)
|
|
|
|
if cfg.BlockFor > 0 {
|
|
blocked, err := r.redis.Exists(ctx, blockKey).Result()
|
|
if err != nil {
|
|
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
if blocked > 0 {
|
|
return false, 0, nil
|
|
}
|
|
}
|
|
|
|
// Fixed-window counter: only the request that brings the counter to 1
|
|
// sets the TTL, so a burst never extends the window and the counter is
|
|
// guaranteed to reset after cfg.Window even under sustained traffic.
|
|
count64, err := r.redis.Incr(ctx, counterKey).Result()
|
|
if err != nil {
|
|
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
if count64 == 1 {
|
|
if err := r.redis.Expire(ctx, counterKey, cfg.Window).Err(); err != nil {
|
|
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
}
|
|
|
|
count := int(count64)
|
|
|
|
if count > cfg.Max {
|
|
if cfg.BlockFor > 0 {
|
|
// Reset the counter when blocking so that once the block expires
|
|
// the client is not instantly re-blocked by the stale count.
|
|
_ = r.redis.Del(ctx, counterKey).Err()
|
|
if err := r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err(); err != nil {
|
|
return false, 0, fmt.Errorf("rate limiter: %w", err)
|
|
}
|
|
}
|
|
return false, 0, nil
|
|
}
|
|
|
|
remaining := max(cfg.Max-count, 0)
|
|
return true, remaining, nil
|
|
}
|
|
|
|
func (r *RateLimiter) Reset(ctx context.Context, key string) {
|
|
_ = r.redis.Del(ctx, fmt.Sprintf("rl_count:%s", key), fmt.Sprintf("rl_block:%s", key))
|
|
}
|