package middleware import ( "net/http" "net/http/httptest" "os" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "go.uber.org/zap" ) func TestMetricsProtection_DeniesWithoutAuth(t *testing.T) { // Clear metrics env so access is denied (no bearer, no IP whitelist) defer func() { os.Unsetenv("METRICS_BEARER_TOKEN") os.Unsetenv("METRICS_ALLOWED_IPS") os.Unsetenv("METRICS_PUBLIC_IN_DEV") os.Unsetenv("APP_ENV") }() os.Unsetenv("METRICS_BEARER_TOKEN") os.Unsetenv("METRICS_ALLOWED_IPS") os.Unsetenv("METRICS_PUBLIC_IN_DEV") os.Setenv("APP_ENV", "production") gin.SetMode(gin.TestMode) router := gin.New() logger := zap.NewNop() router.Use(MetricsProtection(logger)) router.GET("/metrics", func(c *gin.Context) { c.String(200, "metrics") }) w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/metrics", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusForbidden, w.Code) assert.Contains(t, w.Body.String(), "Access denied") } func TestMetricsProtection_AllowsWithBearerToken(t *testing.T) { defer func() { os.Unsetenv("METRICS_BEARER_TOKEN") os.Unsetenv("METRICS_ALLOWED_IPS") os.Unsetenv("APP_ENV") }() os.Setenv("METRICS_BEARER_TOKEN", "secret-token") os.Unsetenv("METRICS_ALLOWED_IPS") os.Setenv("APP_ENV", "production") gin.SetMode(gin.TestMode) router := gin.New() logger := zap.NewNop() router.Use(MetricsProtection(logger)) router.GET("/metrics", func(c *gin.Context) { c.String(200, "metrics") }) w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/metrics", nil) req.Header.Set("Authorization", "Bearer secret-token") router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "metrics") } func TestMetricsProtection_AllowsWithWhitelistedIP(t *testing.T) { defer func() { os.Unsetenv("METRICS_BEARER_TOKEN") os.Unsetenv("METRICS_ALLOWED_IPS") os.Unsetenv("APP_ENV") }() os.Unsetenv("METRICS_BEARER_TOKEN") os.Setenv("METRICS_ALLOWED_IPS", "127.0.0.1") os.Setenv("APP_ENV", "production") gin.SetMode(gin.TestMode) router := gin.New() logger := zap.NewNop() router.Use(MetricsProtection(logger)) router.GET("/metrics", func(c *gin.Context) { c.String(200, "metrics") }) w := httptest.NewRecorder() req := httptest.NewRequest("GET", "/metrics", nil) req.RemoteAddr = "127.0.0.1:12345" router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) assert.Contains(t, w.Body.String(), "metrics") }