Files
mtusi2026lab7/internal/middleware/login_limit.go
T
sxdees 2f2047909f
Skeleton contracts / contracts (pull_request) Blocked by required conditions
ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
2026-12-02 23:08:27 +03:00

68 lines
1.5 KiB
Go

package middleware
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"gavrilenko-sxdees/lab7/internal/dto"
"gavrilenko-sxdees/lab7/internal/httpx"
)
const (
loginLimitKeyPrefix = "login:attempt:"
loginLimitWindow = time.Minute
loginLimitMax = 20
)
type LoginLimiter struct {
rdb *redis.Client
}
func NewLoginLimiter(rdb *redis.Client) *LoginLimiter {
return &LoginLimiter{rdb: rdb}
}
func (l *LoginLimiter) Limit(next http.Handler) http.Handler {
if l == nil || l.rdb == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/api/v1/auth/sessions" {
next.ServeHTTP(w, r)
return
}
username, _, ok := r.BasicAuth()
if !ok {
next.ServeHTTP(w, r)
return
}
key := loginLimitKeyPrefix + username
ctx, cancel := context.WithTimeout(r.Context(), 200*time.Millisecond)
defer cancel()
n, err := l.rdb.Incr(ctx, key).Result()
if err != nil {
next.ServeHTTP(w, r)
return
}
if n == 1 {
_ = l.rdb.Expire(ctx, key, loginLimitWindow).Err()
}
if n > loginLimitMax {
ttl, _ := l.rdb.TTL(ctx, key).Result()
if ttl < 0 {
ttl = loginLimitWindow
}
w.Header().Set("Retry-After", strconv.Itoa(int(ttl.Seconds())))
httpx.WriteError(w, http.StatusTooManyRequests, dto.ErrorCodeRateLimited,
fmt.Sprintf("too many login attempts; retry in %ds", int(ttl.Seconds())),
GetRequestID(r.Context()))
return
}
next.ServeHTTP(w, r)
})
}