fix: rate limiting X-Real-IP from the real peer

This commit is contained in:
fsylvain committed 2026-09-25 06:49:55 +02:00
1 parent 9b47685002
commit 0e050c36ff
11 files changed
+439 -8

No files matched your search

+31
View File
@@ -134,6 +134,37 @@ func TestNewSettingsFromEnvInvalidAuthRateLimitWindowSecondsReturnsError(t *test
}
}
func TestNewSettingsFromEnvEmptyTrustedProxiesIsNil(t *testing.T) {
setBaseSettingsEnv(t)
settings, err := config.NewSettingsFromEnv()
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if settings.TrustedProxies != nil {
t.Errorf("expected nil TrustedProxies, got %v", settings.TrustedProxies)
}
}
func TestNewSettingsFromEnvParsesMultipleTrustedProxies(t *testing.T) {
setBaseSettingsEnv(t)
t.Setenv("TRUSTED_PROXIES", "10.0.0.1;127.0.0.1")
settings, err := config.NewSettingsFromEnv()
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
expected := []string{"10.0.0.1", "127.0.0.1"}
if len(settings.TrustedProxies) != len(expected) {
t.Fatalf("expected %d trusted proxies, got %v", len(expected), settings.TrustedProxies)
}
for i, proxy := range expected {
if settings.TrustedProxies[i] != proxy {
t.Errorf("expected trusted proxy %d to be %q, got %q", i, proxy, settings.TrustedProxies[i])
}
}
}
func TestSettingsIsProductionFalseForNonProductionEnvironment(t *testing.T) {
settings := config.Settings{Environment: "development"}
if settings.IsProduction() {
@@ -0,0 +1,179 @@
package test
import (
"RenewCMS/api/handlers/auth"
"RenewCMS/api/middleware"
validator "RenewCMS/api/pkg/validator"
"RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/hashing"
"RenewCMS/internal/infrastructure/useCases"
"bytes"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
func newTrustedProxyAuthRouter(t *testing.T, userRepo user.Repository, mailRepo *mockMailRepo, trustedProxies []string) *chi.Mux {
t.Helper()
hasher := hashing.NewBcryptHasher()
token := jwtauth.New("HS256", []byte("test-secret"), nil)
loginHandler := auth.NewLoginHandler(
token,
useCases.NewCreateUserUseCase(userRepo, hasher, mailRepo, "https://cms.example.com"),
useCases.NewAuthenticateUserUseCase(userRepo, hasher),
true,
)
passwordResetHandler := auth.NewPasswordResetHandler(
useCases.NewRequestPasswordResetUseCase(userRepo, hasher, mailRepo, "https://cms.example.com"),
useCases.NewResetPasswordUseCase(userRepo, hasher),
)
r := chi.NewRouter()
r.Route("/v1", func(r chi.Router) {
r.Route("/auth", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(1, time.Hour))
r.Post("/login", loginHandler.Login)
})
r.Group(func(r chi.Router) {
r.Use(middleware.TrustedProxyRealIP(trustedProxies))
r.Use(middleware.NewRateLimiter(1, time.Hour))
r.Post("/password-reset", passwordResetHandler.RequestPasswordReset)
})
})
})
return r
}
func sendTrustedProxyRequest(router *chi.Mux, remoteAddr string, headerName string, headerValue string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/v1/auth/login", bytes.NewBufferString(`{"username": "alice", "password": "correctpassword1"}`))
req.Header.Set("Content-Type", "application/json")
req.RemoteAddr = remoteAddr
if headerName != "" {
req.Header.Set(headerName, headerValue)
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec
}
func TestTrustedProxyClientIpForRateLimitingHttp(t *testing.T) {
validator.InitValidator()
t.Run("With no trusted proxies configured, a forwarded header changes nothing", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, nil)
first := sendTrustedProxyRequest(router, "203.0.113.5:1", "X-Real-IP", "198.51.100.1")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "203.0.113.5:1", "X-Real-IP", "198.51.100.1")
if second.Code != http.StatusTooManyRequests {
t.Fatalf("expected the second request to be 429, got %d", second.Code)
}
})
t.Run("An untrusted connection address cannot use the header to dodge its own limit", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, []string{"10.0.0.1"})
first := sendTrustedProxyRequest(router, "203.0.113.5:1", "X-Real-IP", "1.1.1.1")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "203.0.113.5:1", "X-Real-IP", "2.2.2.2")
if second.Code != http.StatusTooManyRequests {
t.Fatalf("expected the second request to be 429, got %d", second.Code)
}
})
t.Run("A configured trusted proxy's forwarded header is honored", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, []string{"10.0.0.1"})
first := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Real-IP", "198.51.100.9")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Real-IP", "198.51.100.9")
if second.Code != http.StatusTooManyRequests {
t.Fatalf("expected the second request to be 429, got %d", second.Code)
}
})
t.Run("Two real clients behind the same trusted proxy get independent counters", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, []string{"10.0.0.1"})
first := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Real-IP", "198.51.100.9")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Real-IP", "198.51.100.10")
if second.Code == http.StatusTooManyRequests {
t.Fatalf("expected a different forwarded client to not be rate-limited, got %d", second.Code)
}
})
t.Run("A trusted proxy's own X-Forwarded-For header is never consulted", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, []string{"10.0.0.1"})
first := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Forwarded-For", "198.51.100.9")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "10.0.0.1:1", "X-Forwarded-For", "198.51.100.9")
if second.Code != http.StatusTooManyRequests {
t.Fatalf("expected the second request to be 429, got %d", second.Code)
}
})
t.Run("A trusted proxy with no forwarded header falls back to its own address", func(t *testing.T) {
userRepo := newRateLimitAliceRepo()
mailRepo := newMockMailRepo()
router := newTrustedProxyAuthRouter(t, userRepo, mailRepo, []string{"10.0.0.1"})
first := sendTrustedProxyRequest(router, "10.0.0.1:1", "", "")
if first.Code == http.StatusTooManyRequests {
t.Fatalf("expected the first request to not be rate-limited, got %d", first.Code)
}
second := sendTrustedProxyRequest(router, "10.0.0.1:1", "", "")
if second.Code != http.StatusTooManyRequests {
t.Fatalf("expected the second request to be 429, got %d", second.Code)
}
})
t.Run("A trusted connection address with no port rewrites RemoteAddr to the bare forwarded host", func(t *testing.T) {
var capturedRemoteAddr string
handler := middleware.TrustedProxyRealIP([]string{"10.0.0.1"})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedRemoteAddr = r.RemoteAddr
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "10.0.0.1"
req.Header.Set("X-Real-IP", "198.51.100.9")
handler.ServeHTTP(httptest.NewRecorder(), req)
if capturedRemoteAddr != "198.51.100.9" {
t.Fatalf("expected RemoteAddr to be rewritten to the bare forwarded host %q, got %q", "198.51.100.9", capturedRemoteAddr)
}
})
}