Files
mtusi2026lab7/internal/transport/rest/ratelimit.go
T
Vladislav Kunetskiy 1b6e96ccc0
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
2026-11-10 14:39:57 +03:00

126 lines
3.4 KiB
Go

package rest
import (
"crypto/sha256"
"encoding/hex"
"log/slog"
"net"
"net/http"
"net/netip"
"strconv"
"strings"
"time"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/ratelimit"
)
type LoginLimits struct {
Account ratelimit.Limit
Source ratelimit.Limit
Global ratelimit.Limit
}
func DefaultLoginLimits() LoginLimits {
return LoginLimits{
Account: ratelimit.Limit{Count: 8, Window: time.Minute},
Source: ratelimit.Limit{Count: 120, Window: time.Minute},
Global: ratelimit.Limit{Count: 16, Window: time.Second},
}
}
// WithLoginLimits must wrap the router so admission precedes generated Basic
// authentication. Registration shares the source and global derivation budgets.
func WithLoginLimits(
next http.Handler, limiter ratelimit.Limiter, limits LoginLimits, log *slog.Logger,
) http.Handler {
id := InstanceID()
return requestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isLogin := r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/sessions"
isRegister := r.Method == http.MethodPost && r.URL.Path == "/api/v1/users"
if !isLogin && !isRegister {
next.ServeHTTP(w, r)
return
}
w.Header().Set(instanceIDHeader, id)
if limiter == nil {
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
return
}
reservations := make([]ratelimit.Limit, 0, 3)
source, global := limits.Source, limits.Global
source.Key = loginLimitKey("source", loginSourceIP(r))
global.Key = loginLimitKey("global", "login-register")
reservations = append(reservations, source, global)
if isLogin {
username, _, _ := r.BasicAuth()
account := limits.Account
account.Key = loginLimitKey("account", username)
reservations = append(reservations, account)
}
retryAfter, err := limiter.Reserve(r.Context(), reservations)
if err != nil {
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
return
}
if retryAfter > 0 {
w.Header().Set("Retry-After", retryAfterSeconds(retryAfter))
logRejected(r.Context(), log, r, http.StatusTooManyRequests, domain.ErrRateLimited)
writeError(r.Context(), log, w, r, http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
}))
}
func loginLimitKey(scope, value string) string {
digest := sha256.Sum256([]byte(scope + "\x00" + value))
return hex.EncodeToString(digest[:])
}
func loginSourceIP(r *http.Request) string {
if authenticatedLB(r) {
values := r.Header.Values("X-Forwarded-For")
if len(values) == 1 {
if ip, err := netip.ParseAddr(strings.TrimSpace(values[0])); err == nil {
return ip.Unmap().String()
}
}
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
if ip, err := netip.ParseAddr(host); err == nil {
return ip.Unmap().String()
}
return "unknown"
}
func authenticatedLB(r *http.Request) bool {
if r.TLS == nil {
return false
}
for _, chain := range r.TLS.VerifiedChains {
if len(chain) == 0 {
continue
}
for _, uri := range chain[0].URIs {
if uri.String() == "spiffe://mtusi/lb" {
return true
}
}
}
return false
}
func retryAfterSeconds(duration time.Duration) string {
seconds := duration / time.Second
if duration%time.Second != 0 {
seconds++
}
return strconv.FormatInt(max(1, int64(seconds)), 10)
}