package httpadapter import ( "context" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "lincodex/backend/internal/adapter/primary/http/api" "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" metrics "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/pkg/testutil" ) // Fixture values that must never reach a metric label. const ( metricsFixtureEmail = "metrics.fixture@example.com" metricsFixtureID = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff" ) func newMetricsTestRouter(t *testing.T, apiHandler func(*v1.HealthHandler, *problem.Responder) api.Handler) (http.Handler, *metrics.Metrics) { t.Helper() logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) responder := problem.NewResponder(logger) collector := metrics.New() router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } return router, collector } func scrapeMetrics(t *testing.T, collector *metrics.Metrics) string { t.Helper() response := httptest.NewRecorder() collector.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) return response.Body.String() } // Requests under the versioned prefix are labeled with the path template of // their operation, never the raw path, and error responses are counted by // their problem code. func TestRequestMetricsUseRouteTemplatesAndProblemCodes(t *testing.T) { router, collector := newMetricsTestRouter(t, func(health *v1.HealthHandler, responder *problem.Responder) api.Handler { return v1.NewHandler(health, responder) }) for _, request := range []struct { method, target string status int }{ {method: http.MethodGet, target: "/healthz", status: http.StatusOK}, {method: http.MethodGet, target: "/api/v1/healthz", status: http.StatusOK}, // DenyAllSecurity rejects the session before the operation runs. {method: http.MethodGet, target: "/api/v1/me/invitations/" + metricsFixtureID, status: http.StatusUnauthorized}, {method: http.MethodGet, target: "/api/v1/me/assessment-attempts/" + metricsFixtureID + "?email=" + metricsFixtureEmail, status: http.StatusUnauthorized}, {method: http.MethodGet, target: "/api/v1/users/" + metricsFixtureEmail, status: http.StatusNotFound}, {method: http.MethodPost, target: "/api/v1/healthz", status: http.StatusMethodNotAllowed}, {method: http.MethodGet, target: "/api/" + metricsFixtureEmail, status: http.StatusNotFound}, {method: http.MethodGet, target: "/files/" + metricsFixtureID, status: http.StatusNotFound}, } { response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil)) if response.Code != request.status { t.Fatalf("%s %s = %d, want %d", request.method, request.target, response.Code, request.status) } } body := scrapeMetrics(t, collector) for _, want := range []string{ `lincodex_http_requests_total{method="GET",route="/healthz",status="200"} 1`, `lincodex_http_requests_total{method="GET",route="/api/v1/healthz",status="200"} 1`, `lincodex_http_requests_total{method="GET",route="/api/v1/me/invitations/{invitation_id}",status="401"} 1`, `lincodex_http_requests_total{method="GET",route="/api/v1/me/assessment-attempts/{attempt_id}",status="401"} 1`, `lincodex_http_requests_total{method="GET",route="/api/v1/*",status="404"} 1`, `lincodex_http_requests_total{method="POST",route="/api/v1/*",status="405"} 1`, `lincodex_http_requests_total{method="GET",route="/api/*",status="404"} 1`, `lincodex_http_requests_total{method="GET",route="unmatched",status="404"} 1`, `lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/healthz",status_class="2xx"} 1`, `lincodex_http_problems_total{code="unauthenticated",route="/api/v1/me/invitations/{invitation_id}"} 1`, `lincodex_http_problems_total{code="not_found",route="/api/v1/*"} 1`, `lincodex_http_problems_total{code="method_not_allowed",route="/api/v1/*"} 1`, `lincodex_http_problems_total{code="not_found",route="/api/*"} 1`, } { if !strings.Contains(body, want+"\n") { t.Fatalf("metrics output is missing %s:\n%s", want, body) } } // A plain 404 outside /api is not a problem response. if strings.Contains(body, `lincodex_http_problems_total{code="not_found",route="unmatched"}`) { t.Fatalf("a non-problem 404 was counted as a problem:\n%s", body) } if found := testutil.FindPersonalIdentifiers(body); len(found) != 0 { t.Fatalf("request metrics expose identifiers %q:\n%s", found, body) } } // An operation without an implementation is counted under its own route // with the not_implemented code. func TestRequestMetricsCountNotImplementedOperations(t *testing.T) { router, collector := newMetricsTestRouter(t, func(*v1.HealthHandler, *problem.Responder) api.Handler { return api.UnimplementedHandler{} }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) body := scrapeMetrics(t, collector) for _, want := range []string{ `lincodex_http_requests_total{method="GET",route="/api/v1/healthz",status="501"} 1`, `lincodex_http_problems_total{code="not_implemented",route="/api/v1/healthz"} 1`, } { if !strings.Contains(body, want+"\n") { t.Fatalf("metrics output is missing %s:\n%s", want, body) } } } // The metrics adapter mirrors the contract's problem codes to bound its // label; a code missing from its list would be counted as "other". func TestEveryContractProblemCodeKeepsItsMetricLabel(t *testing.T) { collector := metrics.New() for _, code := range api.ProblemCode("").AllValues() { collector.ObserveProblem("/api/v1/*", string(code)) } body := scrapeMetrics(t, collector) for _, code := range api.ProblemCode("").AllValues() { if want := `lincodex_http_problems_total{code="` + string(code) + `",route="/api/v1/*"} 1`; !strings.Contains(body, want+"\n") { t.Fatalf("metrics output is missing %s; add the code to the adapter list:\n%s", want, body) } } if strings.Contains(body, `code="other"`) { t.Fatalf("a contract problem code was counted as other:\n%s", body) } }