package middleware import ( "bytes" "encoding/json" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/go-chi/chi/v5" "lincodex/backend/internal/adapter/primary/http/observe" ) type observedRequest struct { method, route, problem string status int } type recordingCollector struct { requests []observedRequest } func (collector *recordingCollector) ObserveRequest(method, route string, status int, _ time.Duration) { collector.requests = append(collector.requests, observedRequest{method: method, route: route, status: status}) } func (collector *recordingCollector) ObserveProblem(route, code string) { collector.requests = append(collector.requests, observedRequest{route: route, problem: code}) } // requestOnlyCollector has no ObserveProblem. type requestOnlyCollector struct { requests int } func (collector *requestOnlyCollector) ObserveRequest(string, string, int, time.Duration) { collector.requests++ } func problemHandler(status int, code string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { observe.RecordProblem(r.Context(), code) w.WriteHeader(status) } } func TestRequestLogAndMetricsShareTheRouteAndTheProblem(t *testing.T) { var logs bytes.Buffer collector := &recordingCollector{} router := chi.NewRouter() router.Use(RequestLog(slog.New(slog.NewJSONHandler(&logs, nil)), nil, "/skipped")) router.Use(CollectMetrics(collector, nil)) router.Get("/items/{id}", problemHandler(http.StatusInternalServerError, "internal")) router.Get("/skipped", problemHandler(http.StatusOK, "")) // A problem built for a response that finally succeeded is not counted. router.Get("/recovered", problemHandler(http.StatusOK, "not_found")) for _, request := range []*http.Request{ httptest.NewRequest(http.MethodGet, "/items/secret-value?token=x", nil), httptest.NewRequest(http.MethodGet, "/skipped", nil), httptest.NewRequest(http.MethodGet, "/recovered", nil), httptest.NewRequest("PROPFIND", "/dav", nil), } { router.ServeHTTP(httptest.NewRecorder(), request) } want := []observedRequest{ {method: http.MethodGet, route: "/items/{id}", status: 500}, {route: "/items/{id}", problem: "internal"}, {method: http.MethodGet, route: "/skipped", status: 200}, {method: http.MethodGet, route: "/recovered", status: 200}, // chi refuses a method it does not know before any route matches. {method: "PROPFIND", route: unmatchedRoute, status: 405}, } if len(collector.requests) != len(want) { t.Fatalf("observed %+v, want %+v", collector.requests, want) } for index := range want { if collector.requests[index] != want[index] { t.Fatalf("observation %d = %+v, want %+v", index, collector.requests[index], want[index]) } } lines := strings.Split(strings.TrimSpace(logs.String()), "\n") if len(lines) != 3 { t.Fatalf("logged %d lines, want 3 without the skipped path:\n%s", len(lines), logs.String()) } if strings.Contains(logs.String(), "secret-value") || strings.Contains(logs.String(), "token") { t.Fatalf("request log carries the raw path or query:\n%s", logs.String()) } var failed map[string]any if err := json.Unmarshal([]byte(lines[0]), &failed); err != nil { t.Fatalf("decode %s: %v", lines[0], err) } if failed["level"] != "ERROR" || failed["route"] != "/items/{id}" || failed["problem_code"] != "internal" || failed["query_params"] != 1.0 { t.Fatalf("5xx line = %s", lines[0]) } if strings.Contains(lines[1], "problem_code") { t.Fatalf("a successful response was logged with a problem code: %s", lines[1]) } if !strings.Contains(lines[2], `"method":"OTHER"`) { t.Fatalf("an unknown method was logged verbatim: %s", lines[2]) } } func TestCollectMetricsWithoutProblemMetricsAndOutsideChi(t *testing.T) { collector := &requestOnlyCollector{} handler := CollectMetrics(collector, nil)(problemHandler(http.StatusNotFound, "not_found")) handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/anything", nil)) if collector.requests != 1 { t.Fatalf("observed %d requests, want 1", collector.requests) } recording := &recordingCollector{} CollectMetrics(recording, nil)(problemHandler(http.StatusNotFound, "")). ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/anything", nil)) if want := (observedRequest{method: http.MethodGet, route: unmatchedRoute, status: 404}); len(recording.requests) != 1 || recording.requests[0] != want { t.Fatalf("observed %+v, want only %+v", recording.requests, want) } }