fix(backend): pass METRICS_BEARER_TOKEN in TestPublicCoreRoutes

Commit 7b2f87373 wrapped /metrics, /metrics/aggregated and /system/metrics
behind a new MetricsProtection middleware. Without auth they return 403,
which broke the 6 metrics sub-tests. The middleware reads
METRICS_BEARER_TOKEN at construction time, so set it via t.Setenv before
calling setupTestRouter, and add a needsMetricsAuth flag on the test
case so the request carries the matching Authorization header.
This commit is contained in:
senke 2026-04-14 11:44:53 +02:00
parent 87e1e0a5ab
commit f5b2e68c3e

View file

@ -67,6 +67,13 @@ func setupTestRouter(t *testing.T) (*gin.Engine, func()) {
}
func TestPublicCoreRoutes(t *testing.T) {
// MetricsProtection middleware (added in 7b2f87373) reads METRICS_BEARER_TOKEN
// at construction time. Set it before setupTestRouter so the protected
// /metrics, /metrics/aggregated, /system/metrics routes are reachable in tests
// when the request carries the matching bearer header.
const metricsToken = "test-metrics-token"
t.Setenv("METRICS_BEARER_TOKEN", metricsToken)
router, cleanup := setupTestRouter(t)
defer cleanup()
@ -78,6 +85,7 @@ func TestPublicCoreRoutes(t *testing.T) {
modernPath string
expectedStatus int
expectDeprecatedHeader bool
needsMetricsAuth bool
}{
{
name: "Health Check",
@ -103,8 +111,8 @@ func TestPublicCoreRoutes(t *testing.T) {
expectedStatus: http.StatusOK,
expectDeprecatedHeader: true,
},
// Metrics endpoints might return different body content due to dynamic nature,
// so we primarily check status code.
// Metrics endpoints are protected by MetricsProtection middleware.
// We pass a bearer token to verify they're reachable when authenticated.
{
name: "Metrics",
method: http.MethodGet,
@ -112,6 +120,7 @@ func TestPublicCoreRoutes(t *testing.T) {
modernPath: "/api/v1/metrics",
expectedStatus: http.StatusOK,
expectDeprecatedHeader: true,
needsMetricsAuth: true,
},
{
name: "Aggregated Metrics",
@ -120,6 +129,7 @@ func TestPublicCoreRoutes(t *testing.T) {
modernPath: "/api/v1/metrics/aggregated",
expectedStatus: http.StatusOK,
expectDeprecatedHeader: true,
needsMetricsAuth: true,
},
{
name: "System Metrics",
@ -128,12 +138,16 @@ func TestPublicCoreRoutes(t *testing.T) {
modernPath: "/api/v1/system/metrics",
expectedStatus: http.StatusOK,
expectDeprecatedHeader: true,
needsMetricsAuth: true,
},
}
for _, tc := range testCases {
t.Run("Legacy "+tc.name, func(t *testing.T) {
req, _ := http.NewRequest(tc.method, tc.legacyPath, nil)
if tc.needsMetricsAuth {
req.Header.Set("Authorization", "Bearer "+metricsToken)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
@ -145,6 +159,9 @@ func TestPublicCoreRoutes(t *testing.T) {
t.Run("Modern "+tc.name, func(t *testing.T) {
req, _ := http.NewRequest(tc.method, tc.modernPath, nil)
if tc.needsMetricsAuth {
req.Header.Set("Authorization", "Bearer "+metricsToken)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)