410 lines
15 KiB
Go
410 lines
15 KiB
Go
package httpx_test
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"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"`
|
|
}
|
|
|
|
const testInstance = "0123456789abcdef"
|
|
|
|
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, testInstance)
|
|
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
|
|
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)
|
|
}
|
|
}
|
|
|
|
// The balancer spreads one client's requests over the replicas; the header
|
|
// is how a client tells which process answered, so no response may lack it.
|
|
func TestEveryResponseCarriesInstanceID(t *testing.T) {
|
|
e := newEngine(t, nil)
|
|
for _, r := range []struct{ method, path string }{
|
|
{http.MethodGet, "/ok"},
|
|
{http.MethodGet, "/missing"},
|
|
{http.MethodDelete, "/ok"},
|
|
{http.MethodGet, "/panic"},
|
|
{http.MethodGet, "/fail"},
|
|
{http.MethodPost, "/decode"},
|
|
} {
|
|
rec, _ := do(t, e, r.method, r.path, "", nil)
|
|
if got := rec.Header().Get("X-Instance-Id"); got != testInstance {
|
|
t.Errorf("%s %s (status %d): X-Instance-Id = %q, want %q", r.method, r.path, rec.Code, got, testInstance)
|
|
}
|
|
}
|
|
}
|
|
|
|
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(), `"<a&b>"`) {
|
|
t.Fatalf("HTML escaping must be off, body %s", rec.Body.String())
|
|
}
|
|
}
|
|
|
|
// The balancer sets X-Request-Id on every request, overwriting what the
|
|
// client sent; the API keeps it so that one id spans both logs.
|
|
func TestRequestIDFromTheBalancerIsKept(t *testing.T) {
|
|
const fromLB = "0123456789abcdef0123456789abcdef"
|
|
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": fromLB})
|
|
if got := rec.Header().Get("X-Request-Id"); got != fromLB {
|
|
t.Fatalf("X-Request-Id = %q, want %q", got, fromLB)
|
|
}
|
|
}
|
|
|
|
func TestMalformedRequestIDIsReplaced(t *testing.T) {
|
|
for _, bad := range []string{"has space", "semi;colon", "tab\there", strings.Repeat("a", 65)} {
|
|
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": bad})
|
|
if got := rec.Header().Get("X-Request-Id"); got == "" || got == bad {
|
|
t.Errorf("X-Request-Id for %q = %q, want a generated value", bad, 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")
|
|
}
|
|
|
|
// A 5xx tells the client only the safe message; the operator must still see
|
|
// why the dependency failed, so the cause goes to the log.
|
|
func TestUnavailableCauseIsLoggedButNotReturned(t *testing.T) {
|
|
logs := &bytes.Buffer{}
|
|
e := newEngine(t, logs)
|
|
e.GET("/down", func(c *gin.Context) {
|
|
cause := errors.New("dial tcp 10.0.0.7:5432: connect: connection refused")
|
|
httpx.Error(c, fmt.Errorf("select user: %w", apperr.Wrap(apperr.KindUnavailable, "database unavailable", cause)))
|
|
})
|
|
rec, eb := do(t, e, http.MethodGet, "/down", "", nil)
|
|
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
|
// Neither the cause nor the wrapping context of internal operations
|
|
// ("select user: ...") may reach the client.
|
|
if eb.Error.Message != "database unavailable" {
|
|
t.Fatalf("client message = %q, want only the application message", eb.Error.Message)
|
|
}
|
|
if !strings.Contains(logs.String(), "connection refused") || !strings.Contains(logs.String(), eb.Error.RequestID) {
|
|
t.Fatalf("log must carry the cause and the request id, got:\n%s", logs.String())
|
|
}
|
|
}
|
|
|
|
// Everything below Timeout sees one deadline, so waiting on a dependency
|
|
// ends with the request instead of holding the client.
|
|
func TestTimeoutBoundsTheRequestContext(t *testing.T) {
|
|
e := newEngine(t, nil)
|
|
e.GET("/slow", httpx.Timeout(50*time.Millisecond), func(c *gin.Context) {
|
|
select {
|
|
case <-c.Request.Context().Done():
|
|
httpx.Error(c, apperr.Wrap(apperr.KindUnavailable, "gave up", c.Request.Context().Err()))
|
|
case <-time.After(5 * time.Second):
|
|
httpx.JSON(c, http.StatusOK, gin.H{})
|
|
}
|
|
})
|
|
start := time.Now()
|
|
rec, eb := do(t, e, http.MethodGet, "/slow", "", nil)
|
|
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
|
if elapsed := time.Since(start); elapsed > time.Second {
|
|
t.Fatalf("request took %v, want it cut at the 50ms deadline", elapsed)
|
|
}
|
|
}
|
|
|
|
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]
|
|
}
|