package httpx_test import ( "bytes" "encoding/json" "errors" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/gin-gonic/gin" "github.com/google/uuid" "messenger/internal/platform/apperr" "messenger/internal/platform/httpx" ) type errorBody struct { Error struct { Code string `json:"code"` Message string `json:"message"` RequestID string `json:"request_id"` } `json:"error"` } type payload struct { Text string `json:"text"` Count int `json:"count"` } func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine { t.Helper() return newEngineAt(t, logs, slog.LevelDebug) } func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine { t.Helper() if logs == nil { logs = &bytes.Buffer{} } log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level})) e := httpx.NewEngine(log, 64) e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": ""}) }) e.GET("/panic", func(c *gin.Context) { panic("secret detail") }) e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) }) e.GET("/notfound", func(c *gin.Context) { httpx.Error(c, apperr.NotFound("chat not found")) }) e.GET("/who", func(c *gin.Context) { httpx.SetUserID(c, uuid.MustParse("11111111-1111-4111-8111-111111111111")) id, ok := httpx.UserID(c) httpx.JSON(c, http.StatusOK, gin.H{"id": id.String(), "ok": ok}) }) e.POST("/decode", func(c *gin.Context) { var p payload if err := httpx.DecodeJSON(c, &p); err != nil { httpx.Error(c, err) return } httpx.JSON(c, http.StatusOK, p) }) return e } func do(t *testing.T, e *gin.Engine, method, path string, body string, headers map[string]string) (*httptest.ResponseRecorder, errorBody) { t.Helper() var reader io.Reader if body != "" { reader = strings.NewReader(body) } req := httptest.NewRequest(method, path, reader) for k, v := range headers { req.Header.Set(k, v) } rec := httptest.NewRecorder() e.ServeHTTP(rec, req) var eb errorBody if rec.Code >= 400 { if err := json.Unmarshal(rec.Body.Bytes(), &eb); err != nil { t.Fatalf("%s %s: error body is not JSON: %v: %s", method, path, err, rec.Body.String()) } } return rec, eb } func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, status int, code string) { t.Helper() if rec.Code != status { t.Fatalf("status = %d, want %d (body %s)", rec.Code, status, rec.Body.String()) } if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { t.Fatalf("Content-Type = %q", ct) } rid := rec.Header().Get("X-Request-Id") if rid == "" { t.Fatal("missing X-Request-Id header") } if eb.Error.RequestID != rid { t.Fatalf("body request_id %q != header %q", eb.Error.RequestID, rid) } if eb.Error.Code != code || eb.Error.Message == "" { t.Fatalf("error = %+v, want code %q with a message", eb.Error, code) } } func TestUnknownRouteIsJSON404(t *testing.T) { rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil) assertError(t, rec, eb, http.StatusNotFound, "not_found") } func TestTrailingSlashIsNotRedirected(t *testing.T) { rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/ok/", "", nil) assertError(t, rec, eb, http.StatusNotFound, "not_found") } func TestWrongMethodIsJSON405WithAllow(t *testing.T) { rec, eb := do(t, newEngine(t, nil), http.MethodDelete, "/ok", "", nil) assertError(t, rec, eb, http.StatusMethodNotAllowed, "invalid_request") if !strings.Contains(rec.Header().Get("Allow"), "GET") { t.Fatalf("Allow = %q, want GET", rec.Header().Get("Allow")) } } func TestPanicBecomesJSON500WithoutDetails(t *testing.T) { logs := &bytes.Buffer{} rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/panic", "", nil) assertError(t, rec, eb, http.StatusInternalServerError, "internal_error") if strings.Contains(rec.Body.String(), "secret detail") { t.Fatal("panic value leaked to the client") } if !strings.Contains(logs.String(), "secret detail") { t.Fatal("panic must be logged for operators") } } func TestForeignErrorBecomesJSON500WithoutDetails(t *testing.T) { logs := &bytes.Buffer{} rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/fail", "", nil) assertError(t, rec, eb, http.StatusInternalServerError, "internal_error") if strings.Contains(rec.Body.String(), "password") { t.Fatal("internal error text leaked to the client") } if !strings.Contains(logs.String(), "db password leaked") { t.Fatal("cause must be logged for operators") } } func TestApplicationErrorMapping(t *testing.T) { rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/notfound", "", nil) assertError(t, rec, eb, http.StatusNotFound, "not_found") if eb.Error.Message != "chat not found" { t.Fatalf("message = %q", eb.Error.Message) } } func TestSuccessResponseHeadersAndEscaping(t *testing.T) { rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", nil) if rec.Code != http.StatusOK { t.Fatalf("status = %d", rec.Code) } if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" { t.Fatalf("Content-Type = %q", ct) } if rec.Header().Get("X-Request-Id") == "" { t.Fatal("missing X-Request-Id on success") } if !strings.Contains(rec.Body.String(), `""`) { t.Fatalf("HTML escaping must be off, body %s", rec.Body.String()) } } func TestRequestIDIsGeneratedNotEchoed(t *testing.T) { rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"}) if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" { t.Fatalf("X-Request-Id = %q, want a server generated value", got) } } func TestDecodeJSONHappyPath(t *testing.T) { rec, _ := do(t, newEngine(t, nil), http.MethodPost, "/decode", `{"text":"Привет","count":2}`, map[string]string{"Content-Type": "application/json; charset=utf-8"}) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Привет"`) { t.Fatalf("status %d body %s", rec.Code, rec.Body.String()) } } func TestDecodeJSONFailures(t *testing.T) { jsonCT := map[string]string{"Content-Type": "application/json"} cases := []struct { name string body string headers map[string]string status int code string contain string }{ {"no content type", `{"text":"x"}`, nil, http.StatusUnsupportedMediaType, "unsupported_media_type", ""}, {"wrong content type", `{"text":"x"}`, map[string]string{"Content-Type": "text/plain"}, http.StatusUnsupportedMediaType, "unsupported_media_type", ""}, {"empty body", "", jsonCT, http.StatusBadRequest, "invalid_request", "body"}, {"malformed", `{"text":`, jsonCT, http.StatusBadRequest, "invalid_request", "malformed"}, {"invalid utf-8", "{\"text\":\"bad \xff byte\"}", jsonCT, http.StatusBadRequest, "invalid_request", "UTF-8"}, {"unknown field", `{"text":"x","extra":1}`, jsonCT, http.StatusBadRequest, "invalid_request", "extra"}, {"wrong type", `{"text":123}`, jsonCT, http.StatusBadRequest, "invalid_request", "text"}, {"trailing data", `{"text":"x"} {"text":"y"}`, jsonCT, http.StatusBadRequest, "invalid_request", "after"}, {"array instead of object", `[1,2]`, jsonCT, http.StatusBadRequest, "invalid_request", ""}, {"too large", `{"text":"` + strings.Repeat("x", 100) + `"}`, jsonCT, http.StatusRequestEntityTooLarge, "payload_too_large", ""}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { rec, eb := do(t, newEngine(t, nil), http.MethodPost, "/decode", tc.body, tc.headers) assertError(t, rec, eb, tc.status, tc.code) if tc.contain != "" && !strings.Contains(eb.Error.Message, tc.contain) { t.Fatalf("message %q must mention %q", eb.Error.Message, tc.contain) } if strings.Contains(eb.Error.Message, "httpx_test") || strings.Contains(eb.Error.Message, "payload") { t.Fatalf("message must not leak Go type names: %q", eb.Error.Message) } }) } } func TestAccessLogHasRequestFieldsButNoBody(t *testing.T) { logs := &bytes.Buffer{} e := newEngine(t, logs) rec, _ := do(t, e, http.MethodPost, "/decode", `{"text":"confidential"}`, map[string]string{"Content-Type": "application/json"}) var entry map[string]any line := lastLine(logs.String()) if err := json.Unmarshal([]byte(line), &entry); err != nil { t.Fatalf("log line is not JSON: %v: %s", err, line) } for _, key := range []string{"request_id", "method", "path", "status", "duration_ms"} { if _, ok := entry[key]; !ok { t.Errorf("log entry missing %q: %s", key, line) } } if entry["request_id"] != rec.Header().Get("X-Request-Id") { t.Errorf("log request_id %v != header %q", entry["request_id"], rec.Header().Get("X-Request-Id")) } if strings.Contains(logs.String(), "confidential") { t.Fatal("request body must never be logged") } } func TestAccessLogLevelFollowsStatus(t *testing.T) { logs := &bytes.Buffer{} e := newEngineAt(t, logs, slog.LevelInfo) do(t, e, http.MethodGet, "/ok", "", nil) if strings.Contains(logs.String(), `"msg":"request"`) { t.Fatalf("successful requests must be logged at debug level only, got %s", logs.String()) } do(t, e, http.MethodGet, "/notfound", "", nil) if entry := logEntry(t, logs); entry["level"] != "INFO" || entry["status"] != float64(404) { t.Fatalf("client error must be logged at info level with its status, got %v", entry) } do(t, e, http.MethodGet, "/fail", "", nil) if entry := logEntry(t, logs); entry["level"] != "ERROR" || entry["status"] != float64(500) { t.Fatalf("server error must be logged at error level with its status, got %v", entry) } verbose := &bytes.Buffer{} do(t, newEngineAt(t, verbose, slog.LevelDebug), http.MethodGet, "/ok", "", nil) if entry := logEntry(t, verbose); entry["level"] != "DEBUG" || entry["status"] != float64(200) { t.Fatalf("at debug level successful requests must be logged, got %v", entry) } } func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) { logs := &bytes.Buffer{} rec, _ := do(t, newEngine(t, logs), http.MethodGet, "/who", "", nil) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) { t.Fatalf("UserID must return what SetUserID stored: %d %s", rec.Code, rec.Body.String()) } if entry := logEntry(t, logs); entry["user_id"] != "11111111-1111-4111-8111-111111111111" { t.Fatalf("access log must attribute the request to the user, got %v", entry) } anonymous := &bytes.Buffer{} do(t, newEngine(t, anonymous), http.MethodGet, "/ok", "", nil) if _, present := logEntry(t, anonymous)["user_id"]; present { t.Fatal("anonymous requests must not carry user_id") } } func TestWithUserPassesTheIdentifiedCaller(t *testing.T) { actor := uuid.MustParse("22222222-2222-4222-8222-222222222222") e := newEngine(t, nil) e.GET("/actor", func(c *gin.Context) { httpx.SetUserID(c, actor) }, httpx.WithUser(func(c *gin.Context, got uuid.UUID) { httpx.JSON(c, http.StatusOK, gin.H{"id": got.String()}) })) rec, _ := do(t, e, http.MethodGet, "/actor", "", nil) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), actor.String()) { t.Fatalf("handler did not receive the caller: %d %s", rec.Code, rec.Body.String()) } } // Reaching WithUser without an authentication middleware in front is a // wiring mistake, so it must not be blamed on the client with a 401. func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) { e := newEngine(t, nil) e.GET("/actor", httpx.WithUser(func(c *gin.Context, _ uuid.UUID) { httpx.JSON(c, http.StatusOK, gin.H{}) })) rec, eb := do(t, e, http.MethodGet, "/actor", "", nil) assertError(t, rec, eb, http.StatusInternalServerError, "internal_error") } func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any { t.Helper() var entry map[string]any line := lastLine(logs.String()) if err := json.Unmarshal([]byte(line), &entry); err != nil { t.Fatalf("log line is not JSON: %v: %s", err, line) } return entry } func TestTimestampFormat(t *testing.T) { ts := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("MSK", 3*3600)) if got := httpx.Timestamp(ts); got != "2026-09-01T09:00:00.000Z" { t.Fatalf("Timestamp = %q", got) } ts = time.Date(2026, 9, 1, 12, 0, 0, 7_000_000, time.UTC) if got := httpx.Timestamp(ts); got != "2026-09-01T12:00:00.007Z" { t.Fatalf("Timestamp = %q", got) } } func lastLine(s string) string { lines := strings.Split(strings.TrimSpace(s), "\n") return lines[len(lines)-1] }