forked from mtusi2026/mtusi2026lab7
feat: secure messenger ingress and rate-limit logins
This commit is contained in:
@@ -3,7 +3,9 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -57,6 +59,24 @@ func sessionHandler(sessions *services.SessionService) http.HandlerFunc {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
// HAProxy overwrites this header and is the only mTLS identity allowed to reach the API.
|
||||
if r.TLS != nil {
|
||||
source := net.ParseIP(r.Header.Get("X-Forwarded-For"))
|
||||
if source == nil {
|
||||
writeError(w, 503, "unavailable", "missing ingress client address", requestID)
|
||||
return
|
||||
}
|
||||
retryAfter, err := sessions.LoginRetryAfter(r.Context(), source.String())
|
||||
if err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
writeError(w, 429, "rate_limited", "too many login attempts", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || r.ContentLength > 0 {
|
||||
unauthorized(w, "Basic", requestID)
|
||||
|
||||
Reference in New Issue
Block a user