fix client IP handling behind proxies
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/geo-platform/tenant-api/internal/shared/config"
|
||||
)
|
||||
|
||||
func TestNewEngineUsesForwardedClientIPFromTrustedProxy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
engine, err := NewEngine(config.ServerConfig{
|
||||
TrustedProxies: []string{"10.42.0.0/16"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
engine.GET("/ip", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, c.ClientIP())
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/ip", nil)
|
||||
req.RemoteAddr = "10.42.0.128:51234"
|
||||
req.Header.Set("X-Forwarded-For", "106.14.89.27")
|
||||
resp := httptest.NewRecorder()
|
||||
|
||||
engine.ServeHTTP(resp, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.Code)
|
||||
require.Equal(t, "106.14.89.27", resp.Body.String())
|
||||
}
|
||||
|
||||
func TestNewEngineRejectsInvalidTrustedProxy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
_, err := NewEngine(config.ServerConfig{
|
||||
TrustedProxies: []string{"not-a-cidr"},
|
||||
})
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user