352 lines
14 KiB
Go
352 lines
14 KiB
Go
package httpadapter
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"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/internal/usecase/health"
|
|
)
|
|
|
|
// internalFailureText stands for internal error text that must stay in logs.
|
|
const internalFailureText = "dial tcp 10.0.0.5:5432: connection refused"
|
|
|
|
type readinessFunc func(context.Context) error
|
|
|
|
func (check readinessFunc) Check(ctx context.Context) error {
|
|
return check(ctx)
|
|
}
|
|
|
|
// healthzOverride replaces GetHealthz of the production composite handler,
|
|
// keeping its NewError, so a test can drive operation error handling without
|
|
// adding operations to the public contract.
|
|
type healthzOverride struct {
|
|
*v1.Handler
|
|
|
|
getHealthz func(context.Context) (*api.HealthResponse, error)
|
|
}
|
|
|
|
func (handler healthzOverride) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
|
|
return handler.getHealthz(ctx)
|
|
}
|
|
|
|
func TestOperationalHealthRoutes(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
check readinessFunc
|
|
path string
|
|
statusCode int
|
|
bodyStatus string
|
|
}{
|
|
{name: "live", check: func(context.Context) error { return nil }, path: "/healthz", statusCode: http.StatusOK, bodyStatus: "ok"},
|
|
{name: "ready", check: func(context.Context) error { return nil }, path: "/readyz", statusCode: http.StatusOK, bodyStatus: "ready"},
|
|
{name: "not ready", check: func(context.Context) error { return context.DeadlineExceeded }, path: "/readyz", statusCode: http.StatusServiceUnavailable, bodyStatus: "not_ready"},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
router := newTestRouter(t, test.check)
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
|
|
if response.Code != test.statusCode {
|
|
t.Fatalf("status code = %d, want %d", response.Code, test.statusCode)
|
|
}
|
|
var body struct {
|
|
Status string `json:"status"`
|
|
}
|
|
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
|
t.Fatalf("decode response: %v", err)
|
|
}
|
|
if body.Status != test.bodyStatus {
|
|
t.Fatalf("status = %q, want %q", body.Status, test.bodyStatus)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
|
|
router := newTestRouter(t, func(context.Context) error { return context.DeadlineExceeded })
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
|
|
}
|
|
var body api.HealthResponse
|
|
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
|
|
t.Fatalf("decode response %s: %v", response.Body.String(), err)
|
|
}
|
|
if body.Status != api.HealthResponseStatusOk {
|
|
t.Fatalf("status = %q, want %q", body.Status, api.HealthResponseStatusOk)
|
|
}
|
|
}
|
|
|
|
// An operation without a business implementation must answer 501 through the
|
|
// router instead of a successful stub or a generic 500. GetHealthz served by
|
|
// api.UnimplementedHandler stands in for any such operation, so the check needs
|
|
// no extra contract operation.
|
|
func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T) {
|
|
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
|
router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}, slog.New(slog.DiscardHandler))
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
|
|
body := requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
|
|
if body.Errors != nil {
|
|
t.Fatalf("errors = %v, want none", body.Errors)
|
|
}
|
|
}
|
|
|
|
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
|
|
var logs bytes.Buffer
|
|
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
|
router := newOverrideRouter(t, logger, func(context.Context) (*api.HealthResponse, error) {
|
|
return nil, fmt.Errorf("HealthHandler.GetHealthz - check database: %w", errors.New(internalFailureText))
|
|
})
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
|
|
body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
|
|
if body.Title != "Internal server error" {
|
|
t.Fatalf("title = %q, want the fixed internal title", body.Title)
|
|
}
|
|
if strings.Contains(response.Body.String(), "connection refused") || strings.Contains(response.Body.String(), "HealthHandler") {
|
|
t.Fatalf("response exposes internal error text: %s", response.Body.String())
|
|
}
|
|
if !strings.Contains(logs.String(), internalFailureText) {
|
|
t.Fatalf("internal error was not logged at the HTTP boundary: %s", logs.String())
|
|
}
|
|
if requestID := response.Header().Get("X-Request-ID"); !strings.Contains(logs.String(), requestID) {
|
|
t.Fatalf("log entry has no request ID %q: %s", requestID, logs.String())
|
|
}
|
|
}
|
|
|
|
// recordedRequest is one observation passed to the metrics middleware.
|
|
type recordedRequest struct {
|
|
route string
|
|
status int
|
|
}
|
|
|
|
type requestRecorder struct {
|
|
requests []recordedRequest
|
|
}
|
|
|
|
func (recorder *requestRecorder) ObserveRequest(_, route string, status int, _ time.Duration) {
|
|
recorder.requests = append(recorder.requests, recordedRequest{route: route, status: status})
|
|
}
|
|
|
|
func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
|
|
const panicText = "nil map write for candidate jane@example.com"
|
|
var logs bytes.Buffer
|
|
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
|
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
|
handler := healthzOverride{
|
|
Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)),
|
|
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
|
|
}
|
|
recorder := &requestRecorder{}
|
|
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger)
|
|
if err != nil {
|
|
t.Fatalf("NewRouter() error = %v", err)
|
|
}
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
|
|
body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
|
|
if body.Title != "Internal server error" {
|
|
t.Fatalf("title = %q, want the fixed internal title", body.Title)
|
|
}
|
|
if strings.Contains(response.Body.String(), "jane") || strings.Contains(response.Body.String(), "nil map") {
|
|
t.Fatalf("response exposes the panic: %s", response.Body.String())
|
|
}
|
|
if count := strings.Count(logs.String(), "public API request panicked"); count != 1 {
|
|
t.Fatalf("panic logged %d times, want once: %s", count, logs.String())
|
|
}
|
|
if !strings.Contains(logs.String(), response.Header().Get("X-Request-ID")) {
|
|
t.Fatalf("panic log has no request ID: %s", logs.String())
|
|
}
|
|
if strings.Contains(logs.String(), "jane@example.com") {
|
|
t.Fatalf("panic value with personal data reached the logs: %s", logs.String())
|
|
}
|
|
want := []recordedRequest{{route: "/api/v1/*", status: http.StatusInternalServerError}}
|
|
if fmt.Sprint(recorder.requests) != fmt.Sprint(want) {
|
|
t.Fatalf("metrics observed %v, want %v", recorder.requests, want)
|
|
}
|
|
}
|
|
|
|
// http.ErrAbortHandler must reach net/http, which then aborts the response
|
|
// instead of sending a problem or a success.
|
|
func TestPublicOperationAbortPropagatesToTheServer(t *testing.T) {
|
|
recorder := &requestRecorder{}
|
|
router := newOverrideRouterWithMetrics(t, recorder, func(context.Context) (*api.HealthResponse, error) {
|
|
panic(http.ErrAbortHandler)
|
|
})
|
|
|
|
func() {
|
|
defer func() {
|
|
if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity
|
|
t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered)
|
|
}
|
|
}()
|
|
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler")
|
|
}()
|
|
|
|
server := httptest.NewServer(router)
|
|
defer server.Close()
|
|
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+"/api/v1/healthz", nil)
|
|
if err != nil {
|
|
t.Fatalf("build request: %v", err)
|
|
}
|
|
response, err := server.Client().Do(request)
|
|
if err == nil {
|
|
_ = response.Body.Close()
|
|
t.Fatalf("server answered %d, want an aborted connection", response.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestUnknownAPIPathsOutsideTheVersionReturnNotFoundProblem(t *testing.T) {
|
|
router := newTestRouter(t, func(context.Context) error { return nil })
|
|
for _, path := range []string{"/api", "/api/", "/api/v2/healthz", "/api/v1"} {
|
|
t.Run(path, func(t *testing.T) {
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
|
|
|
|
requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound)
|
|
})
|
|
}
|
|
}
|
|
|
|
// Operations report expected failures as typed problems, which the generated
|
|
// server encodes directly with their own status.
|
|
func TestPublicOperationTypedProblemKeepsItsStatus(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
code api.ProblemCode
|
|
statusCode int
|
|
}{
|
|
{name: "forbidden", code: api.ProblemCodeForbidden, statusCode: http.StatusForbidden},
|
|
{name: "version conflict", code: api.ProblemCodeVersionConflict, statusCode: http.StatusPreconditionFailed},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
router := newOverrideRouter(t, slog.New(slog.DiscardHandler), func(ctx context.Context) (*api.HealthResponse, error) {
|
|
return nil, problem.New(ctx, test.code)
|
|
})
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
|
|
|
requireProblem(t, response, test.statusCode, test.code)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPublicUnknownRouteReturnsNotFoundProblem(t *testing.T) {
|
|
router := newTestRouter(t, func(context.Context) error { return nil })
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/missing", nil))
|
|
|
|
requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound)
|
|
}
|
|
|
|
func TestPublicUnsupportedMethodReturnsMethodNotAllowedProblem(t *testing.T) {
|
|
router := newTestRouter(t, func(context.Context) error { return nil })
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/healthz", nil))
|
|
|
|
requireProblem(t, response, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed)
|
|
if allowed := response.Header().Get("Allow"); allowed != http.MethodGet {
|
|
t.Fatalf("Allow = %q, want %q", allowed, http.MethodGet)
|
|
}
|
|
}
|
|
|
|
func TestPublicPreflightKeepsEmptyResponse(t *testing.T) {
|
|
router := newTestRouter(t, func(context.Context) error { return nil })
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest(http.MethodOptions, "/api/v1/healthz", nil))
|
|
|
|
if response.Code != http.StatusNoContent || response.Body.Len() != 0 {
|
|
t.Fatalf("preflight = %d %q, want empty 204", response.Code, response.Body.String())
|
|
}
|
|
if methods := response.Header().Get("Access-Control-Allow-Methods"); methods != http.MethodGet {
|
|
t.Fatalf("Access-Control-Allow-Methods = %q, want %q", methods, http.MethodGet)
|
|
}
|
|
}
|
|
|
|
// requireProblem checks the problem+json envelope and returns the body decoded
|
|
// and validated by the generated contract types.
|
|
func requireProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem {
|
|
t.Helper()
|
|
if response.Code != statusCode {
|
|
t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String())
|
|
}
|
|
if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType {
|
|
t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType)
|
|
}
|
|
var body api.Problem
|
|
if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil {
|
|
t.Fatalf("decode problem %s: %v", response.Body.String(), err)
|
|
}
|
|
if err := body.Validate(); err != nil {
|
|
t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err)
|
|
}
|
|
if body.Code != code || int(body.Status) != statusCode {
|
|
t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, statusCode)
|
|
}
|
|
if body.Type != "urn:lincodex:problem:"+string(code) {
|
|
t.Fatalf("problem type = %q", body.Type)
|
|
}
|
|
traceID, ok := body.TraceID.Get()
|
|
if !ok || traceID != response.Header().Get("X-Request-ID") {
|
|
t.Fatalf("trace_id = %q, want the X-Request-ID header %q", traceID, response.Header().Get("X-Request-ID"))
|
|
}
|
|
return body
|
|
}
|
|
|
|
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
|
|
t.Helper()
|
|
logger := slog.New(slog.DiscardHandler)
|
|
healthHandler := newTestHealthHandler(checker)
|
|
return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), logger)
|
|
}
|
|
|
|
func newOverrideRouter(t *testing.T, logger *slog.Logger, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler {
|
|
t.Helper()
|
|
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
|
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
|
|
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
|
}
|
|
|
|
func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
|
|
return v1.NewHealthHandler(health.NewReadiness(checker), time.Second)
|
|
}
|
|
|
|
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
|
|
t.Helper()
|
|
router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger)
|
|
if err != nil {
|
|
t.Fatalf("NewRouter() error = %v", err)
|
|
}
|
|
return router
|
|
}
|
|
|
|
func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler {
|
|
t.Helper()
|
|
logger := slog.New(slog.DiscardHandler)
|
|
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
|
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
|
|
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger)
|
|
if err != nil {
|
|
t.Fatalf("NewRouter() error = %v", err)
|
|
}
|
|
return router
|
|
}
|