package messenger import ( "crypto/sha256" "fmt" "net/http" ) // A global atomic Redis budget across API replicas bounds expensive login work. // No attacker-controlled IP or username can bypass the global ceiling. func (a *API) loginLimit(r *http.Request) *apiError { ctx, cancel := a.dbContext(r.Context()) defer cancel() username, _, _ := r.BasicAuth() sum := sha256.Sum256([]byte(username)) script := `local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],60) end; local u=redis.call('INCR',KEYS[2]); if u==1 then redis.call('EXPIRE',KEYS[2],60) end; if n>120 or u>10 then return 0 end; return 1` n, e := a.sessions.Eval(ctx, script, []string{"login:global", fmt.Sprintf("login:credential:%x", sum)}).Int() if e != nil { return unavailable() } if n == 0 { return &apiError{status: 429, code: "rate_limited", message: "Слишком много попыток входа"} } return nil } func (a *API) registrationLimit(r *http.Request) *apiError { ctx, cancel := a.dbContext(r.Context()) defer cancel() script := `local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],60) end; return n` n, e := a.sessions.Eval(ctx, script, []string{"login:global"}).Int() if e != nil { return unavailable() } if n > 120 { return &apiError{status: 429, code: "rate_limited", message: "Слишком много запросов"} } return nil }