ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions

Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
2026-12-02 23:08:27 +03:00
parent 20afc2c790
commit 2f2047909f
182 changed files with 15169 additions and 90 deletions
+68
View File
@@ -0,0 +1,68 @@
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)
})
}