feat(api): define public problem errors, pagination, and retry contract

This commit is contained in:
shira committed 2026-10-05 22:09:36 +03:00
1 parent b2f6e87bfe
commit 565ca94bbb
86 files changed
+8200 -154

No files matched your search

@@ -0,0 +1,142 @@
// Package problem writes RFC 9457 problem details for the public HTTP API.
//
// Every public error body is an api.Problem with a stable api.ProblemCode.
// The status, title, and detail of each code are fixed here, so a response
// never carries internal error text or echoed request values.
package problem
import (
"context"
"net/http"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// MediaType is the RFC 9457 media type of every public error response.
const MediaType = "application/problem+json"
// typePrefix forms the problem type URI; the contract documents this form.
const typePrefix = "urn:lincodex:problem:"
type definition struct {
status int32
title string
detail string
}
var definitions = map[api.ProblemCode]definition{
api.ProblemCodeValidationFailed: {
status: http.StatusBadRequest,
title: "Request validation failed",
detail: "One or more request fields are invalid.",
},
api.ProblemCodeUnauthenticated: {
status: http.StatusUnauthorized,
title: "Authentication required",
detail: "Sign in and repeat the request.",
},
api.ProblemCodeForbidden: {
status: http.StatusForbidden,
title: "Access denied",
detail: "You do not have permission to perform this operation.",
},
api.ProblemCodeNotFound: {
status: http.StatusNotFound,
title: "Resource not found",
detail: "The requested resource does not exist.",
},
api.ProblemCodeMethodNotAllowed: {
status: http.StatusMethodNotAllowed,
title: "Method not allowed",
detail: "The resource does not support this method; see the Allow header.",
},
api.ProblemCodeIdempotencyInProgress: {
status: http.StatusConflict,
title: "Request with this idempotency key is in progress",
detail: "Retry after the original request completes.",
},
api.ProblemCodeStateConflict: {
status: http.StatusConflict,
title: "Resource state conflict",
detail: "The resource is in a state that does not allow this operation.",
},
api.ProblemCodeVersionConflict: {
status: http.StatusPreconditionFailed,
title: "Resource version conflict",
detail: "The resource changed after it was read. Read it again before retrying.",
},
api.ProblemCodePayloadTooLarge: {
status: http.StatusRequestEntityTooLarge,
title: "Request body too large",
detail: "Reduce the request body size and retry.",
},
api.ProblemCodeUnsupportedMediaType: {
status: http.StatusUnsupportedMediaType,
title: "Unsupported media type",
detail: "Send the request body with a media type that the operation accepts.",
},
api.ProblemCodeIdempotencyKeyReused: {
status: http.StatusUnprocessableEntity,
title: "Idempotency key reused with a different request",
detail: "Use a new Idempotency-Key for a different request.",
},
api.ProblemCodePreconditionRequired: {
status: http.StatusPreconditionRequired,
title: "Precondition required",
detail: "Send If-Match with the ETag of the version you read.",
},
api.ProblemCodeRateLimited: {
status: http.StatusTooManyRequests,
title: "Too many requests",
detail: "Wait for the Retry-After interval and retry.",
},
api.ProblemCodeInternal: {
status: http.StatusInternalServerError,
title: "Internal server error",
detail: "The server could not complete the request.",
},
api.ProblemCodeNotImplemented: {
status: http.StatusNotImplemented,
title: "Operation not implemented",
detail: "This operation is not available yet.",
},
}
// New returns the problem response for code with its fixed status, title,
// and detail, and the request ID of ctx as trace_id. An unknown code yields
// the internal problem, so a caller cannot produce an undocumented status.
func New(ctx context.Context, code api.ProblemCode) *api.ProblemStatusCode {
known, ok := definitions[code]
if !ok {
code = api.ProblemCodeInternal
known = definitions[code]
}
response := api.Problem{
Type: typePrefix + string(code),
Title: known.title,
Status: known.status,
Code: code,
Detail: api.NewOptString(known.detail),
}
if requestID := kitmiddleware.GetRequestID(ctx); requestID != "" {
response.TraceID = api.NewOptString(requestID)
}
return &api.ProblemStatusCode{StatusCode: int(known.status), Response: response}
}
// Write sends problem as an application/problem+json response.
func Write(w http.ResponseWriter, problem *api.ProblemStatusCode) {
body, err := problem.Response.MarshalJSON()
if err != nil {
// The generated encoder does not fail for a Problem value; keep the
// status so the client still sees an error.
w.WriteHeader(problem.StatusCode)
return
}
w.Header().Set("Content-Type", MediaType)
w.WriteHeader(problem.StatusCode)
// The status is already committed; a failed write cannot be reported.
_, _ = w.Write(body)
}
@@ -0,0 +1,98 @@
package problem
import (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"runtime/debug"
"github.com/felixge/httpsnoop"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Recover answers a panic in next with the internal problem response and logs
// the panic type and stack once. It must run inside the request ID middleware so the problem
// and the log entry carry the request ID. When next has already started the
// response, the status is committed and no second body is written. A panic
// with http.ErrAbortHandler is re-raised so net/http aborts the response as
// that sentinel requires.
func (responder *Responder) Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tracked, started := trackResponseStart(w)
defer responder.recoverPanic(w, r, started)
next.ServeHTTP(tracked, r)
})
}
// recoverPanic must be deferred directly so that recover stops the panic.
func (responder *Responder) recoverPanic(w http.ResponseWriter, r *http.Request, started *bool) {
recovered := recover()
if recovered == nil {
return
}
if err, ok := recovered.(error); ok && errors.Is(err, http.ErrAbortHandler) {
panic(recovered)
}
ctx := r.Context()
responder.logger.ErrorContext(ctx, "public API request panicked",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
// The panic value may hold request data, so only its type is logged.
slog.String("panic_type", fmt.Sprintf("%T", recovered)),
slog.String("stack", string(debug.Stack())),
slog.Bool("response_started", *started),
)
if !*started {
Write(w, New(ctx, api.ProblemCodeInternal))
}
}
// trackResponseStart wraps w, keeping its optional interfaces, and reports
// whether the handler has started the response.
func trackResponseStart(w http.ResponseWriter) (http.ResponseWriter, *bool) {
started := new(bool)
tracked := httpsnoop.Wrap(w, httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(code int) {
*started = true
next(code)
}
},
Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {
return func(body []byte) (int, error) {
*started = true
return next(body)
}
},
WriteString: func(next httpsnoop.WriteStringFunc) httpsnoop.WriteStringFunc {
return func(body string) (int, error) {
*started = true
return next(body)
}
},
ReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {
return func(source io.Reader) (int64, error) {
*started = true
return next(source)
}
},
Flush: func(next httpsnoop.FlushFunc) httpsnoop.FlushFunc {
return func() {
*started = true
next()
}
},
Hijack: func(next httpsnoop.HijackFunc) httpsnoop.HijackFunc {
return func() (net.Conn, *bufio.ReadWriter, error) {
*started = true
return next()
}
},
})
return tracked, started
}
@@ -0,0 +1,66 @@
package problem
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"lincodex/backend/internal/adapter/primary/http/api"
)
func TestRecoverKeepsAStartedResponse(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
handler := responder.Recover(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte(`{"partial":`))
panic("encoder failed")
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
if response.Code != http.StatusAccepted || response.Body.String() != `{"partial":` {
t.Fatalf("response = %d %q, want the started response without a second body", response.Code, response.Body.String())
}
if !strings.Contains(logs.String(), `"response_started":true`) {
t.Fatalf("panic was not logged with the started response: %s", logs.String())
}
}
func TestRecoverWritesInternalProblemBeforeTheResponseStarts(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("profile of jane@example.com")
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if strings.Contains(response.Body.String(), "jane") || strings.Contains(logs.String(), "jane") {
t.Fatalf("panic value leaked; body %s, logs %s", response.Body.String(), logs.String())
}
if !strings.Contains(logs.String(), `"panic_type":"string"`) {
t.Fatalf("panic type was not logged: %s", logs.String())
}
}
func TestRecoverReraisesAbortHandler(t *testing.T) {
responder := NewResponder(slog.New(slog.DiscardHandler))
handler := responder.Recover(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic(http.ErrAbortHandler)
}))
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)
}
}()
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/items", nil))
t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler")
}
@@ -0,0 +1,240 @@
package problem
import (
"context"
"errors"
"log/slog"
"net/http"
"regexp"
"strings"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
"github.com/ogen-go/ogen/validate"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
"lincodex/backend/internal/adapter/primary/http/api"
)
// Field reasons published in ProblemFieldError.code.
const (
fieldCodeRequired = "required"
fieldCodeInvalid = "invalid"
)
const (
fieldMessageRequired = "The value is required."
fieldMessageInvalid = "The value does not match the contract."
// maxFieldErrors matches the maxItems bound of Problem.errors.
maxFieldErrors = 100
// wholeBodyPointer is the JSON Pointer of the request body root.
wholeBodyPointer = ""
)
// arrayIndexName matches the "[index]" names that generated validators use
// for array items.
var arrayIndexName = regexp.MustCompile(`^\[(\d+)\]$`)
var pointerTokenEscaper = strings.NewReplacer("~", "~0", "/", "~1")
var parameterLocations = map[openapi.ParameterLocation]api.ProblemFieldLocation{
openapi.LocationQuery: api.ProblemFieldLocationQuery,
openapi.LocationHeader: api.ProblemFieldLocationHeader,
openapi.LocationPath: api.ProblemFieldLocationPath,
openapi.LocationCookie: api.ProblemFieldLocationCookie,
}
// Responder maps errors at the public HTTP boundary to problem responses and
// logs the errors that are not the client's fault. It logs the error text of
// internal failures, so handwritten errors must follow the backend error
// standard and never carry personal data, request bodies, credentials, or
// other secrets. A request canceled by its client is logged at info level
// because it is not a server failure.
type Responder struct {
logger *slog.Logger
}
func NewResponder(logger *slog.Logger) *Responder {
return &Responder{logger: logger}
}
// HandlerError builds the response for an error returned by an api.Handler
// operation; it implements the contract of api.Handler.NewError. The
// generated server passes security failures here as well, so a
// *ogenerrors.SecurityError becomes 401. Authorization decisions that need 403
// return a typed *api.ProblemStatusCode from the operation instead, which the
// generated server encodes without calling NewError.
func (responder *Responder) HandlerError(ctx context.Context, err error) *api.ProblemStatusCode {
if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok {
return New(ctx, api.ProblemCodeUnauthenticated)
}
responder.logInternal(ctx, err)
return New(ctx, api.ProblemCodeInternal)
}
// HandleServerError is the ErrorHandler of the generated server. It receives
// ht.ErrNotImplemented, request decoding and validation errors, and response
// encoding failures.
func (responder *Responder) HandleServerError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
Write(w, responder.serverErrorProblem(ctx, r, err))
}
// NotFound answers a path that matches no operation of the generated server.
func (*Responder) NotFound(w http.ResponseWriter, r *http.Request) {
Write(w, New(r.Context(), api.ProblemCodeNotFound))
}
// MethodNotAllowed answers a known path requested with an unsupported method.
// The generated server has already set Access-Control-Allow-Methods for a
// CORS preflight, which keeps its empty 204 response.
func (*Responder) MethodNotAllowed(w http.ResponseWriter, r *http.Request, allowed string) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
w.Header().Set("Allow", allowed)
Write(w, New(r.Context(), api.ProblemCodeMethodNotAllowed))
}
func (responder *Responder) serverErrorProblem(ctx context.Context, r *http.Request, err error) *api.ProblemStatusCode {
if errors.Is(err, ht.ErrNotImplemented) {
return New(ctx, api.ProblemCodeNotImplemented)
}
// A body limit set with http.MaxBytesReader surfaces inside the decoding
// error, so it is checked before the generic request decoding branch.
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
return New(ctx, api.ProblemCodePayloadTooLarge)
}
if _, ok := errors.AsType[*validate.InvalidContentTypeError](err); ok {
return New(ctx, api.ProblemCodeUnsupportedMediaType)
}
if _, ok := errors.AsType[*ogenerrors.SecurityError](err); ok {
return New(ctx, api.ProblemCodeUnauthenticated)
}
if paramsErr, ok := errors.AsType[*ogenerrors.DecodeParamsError](err); ok {
return validationProblem(ctx, parameterFieldErrors(r, paramsErr))
}
if requestErr, ok := errors.AsType[*ogenerrors.DecodeRequestError](err); ok {
return validationProblem(ctx, bodyFieldErrors(requestErr))
}
responder.logInternal(ctx, err)
return New(ctx, api.ProblemCodeInternal)
}
func (responder *Responder) logInternal(ctx context.Context, err error) {
if errors.Is(err, context.Canceled) {
responder.logger.InfoContext(ctx, "public API request canceled by client",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
)
return
}
responder.logger.ErrorContext(ctx, "public API request failed",
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
slog.String("error", err.Error()),
)
}
func validationProblem(ctx context.Context, fields []api.ProblemFieldError) *api.ProblemStatusCode {
problem := New(ctx, api.ProblemCodeValidationFailed)
problem.Response.Errors = fields
return problem
}
func parameterFieldErrors(r *http.Request, err error) []api.ProblemFieldError {
paramErr, ok := errors.AsType[*ogenerrors.DecodeParamError](err)
if !ok {
return nil
}
location, ok := parameterLocations[paramErr.In]
if !ok {
return nil
}
code := fieldCodeInvalid
if errors.Is(paramErr.Err, validate.ErrFieldRequired) || !parameterPresent(r, paramErr.In, paramErr.Name) {
code = fieldCodeRequired
}
return []api.ProblemFieldError{fieldError(location, "/"+escapePointerToken(paramErr.Name), code)}
}
// parameterPresent reports whether the request carries the parameter. The
// generated decoder reports a missing query parameter with a plain error, so
// presence is checked on the request instead of in the error text.
func parameterPresent(r *http.Request, in openapi.ParameterLocation, name string) bool {
switch in {
case openapi.LocationQuery:
return r.URL.Query().Has(name)
case openapi.LocationHeader:
return len(r.Header.Values(name)) > 0
case openapi.LocationCookie:
_, err := r.Cookie(name)
return err == nil
case openapi.LocationPath:
// A request without the path segment matches no route.
return true
default:
return true
}
}
func bodyFieldErrors(err error) []api.ProblemFieldError {
if errors.Is(err, validate.ErrBodyRequired) {
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeRequired)}
}
var fields []api.ProblemFieldError
if decodeErr, ok := errors.AsType[*ogenerrors.DecodeBodyError](err); ok {
// Only a validation error that is the direct decoding cause names
// top-level fields. A wrapped one comes from a nested object whose
// path the decoder does not record, so it maps to the whole body.
if topLevel, ok := decodeErr.Err.(*validate.Error); ok { //nolint:errorlint // the unwrapped cause alone identifies top-level fields
fields = appendSchemaFieldErrors(fields, topLevel, wholeBodyPointer)
}
} else if validationErr, ok := errors.AsType[*validate.Error](err); ok {
// Schema validation after decoding nests field errors by path.
fields = appendSchemaFieldErrors(fields, validationErr, wholeBodyPointer)
}
if len(fields) == 0 {
return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, wholeBodyPointer, fieldCodeInvalid)}
}
return fields
}
func appendSchemaFieldErrors(fields []api.ProblemFieldError, err *validate.Error, prefix string) []api.ProblemFieldError {
for _, field := range err.Fields {
if len(fields) >= maxFieldErrors {
return fields
}
pointer := prefix + "/" + pointerToken(field.Name)
if nested, ok := field.Error.(*validate.Error); ok { //nolint:errorlint // only a direct nested validation error carries child paths
fields = appendSchemaFieldErrors(fields, nested, pointer)
continue
}
code := fieldCodeInvalid
if errors.Is(field.Error, validate.ErrFieldRequired) {
code = fieldCodeRequired
}
fields = append(fields, fieldError(api.ProblemFieldLocationBody, pointer, code))
}
return fields
}
func pointerToken(name string) string {
if match := arrayIndexName.FindStringSubmatch(name); match != nil {
return match[1]
}
return escapePointerToken(name)
}
// escapePointerToken escapes a reference token as RFC 6901 requires.
func escapePointerToken(token string) string {
return pointerTokenEscaper.Replace(token)
}
func fieldError(location api.ProblemFieldLocation, pointer, code string) api.ProblemFieldError {
message := fieldMessageInvalid
if code == fieldCodeRequired {
message = fieldMessageRequired
}
return api.ProblemFieldError{In: location, Pointer: pointer, Code: code, Message: message}
}
@@ -0,0 +1,261 @@
package problem
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/openapi"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"lincodex/backend/internal/adapter/primary/http/api"
)
// The errors below are built the way the generated server builds them, so the
// tests cover the mapping for decoder paths that the current public contract
// has no input for. The compatibility fixture exercises the same mapping
// through a real generated server in make -C backend check-ogen-compat.
func TestHandleServerErrorMapsGeneratedErrors(t *testing.T) {
operation := ogenerrors.OperationContext{Name: "CreateItem", ID: "CreateItem"}
for _, test := range []struct {
name string
request *http.Request
err error
statusCode int
code api.ProblemCode
fields []api.ProblemFieldError
}{
{
name: "not implemented",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: ht.ErrNotImplemented,
statusCode: http.StatusNotImplemented,
code: api.ProblemCodeNotImplemented,
},
{
name: "missing query parameter",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "state", In: openapi.LocationQuery, Err: missingQueryParameter("state"),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/state", Code: "required", Message: fieldMessageRequired}},
},
{
name: "invalid query parameter",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items?limit=1000", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "limit", In: openapi.LocationQuery,
Err: fmt.Errorf("int: %w", validate.Int{MinSet: true, Min: 1, MaxSet: true, Max: 100}.Validate(1000)),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationQuery, Pointer: "/limit", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "missing header",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil),
err: &ogenerrors.DecodeParamsError{OperationContext: operation, Err: &ogenerrors.DecodeParamError{
Name: "Idempotency-Key", In: openapi.LocationHeader,
Err: &validate.Error{Fields: []validate.FieldError{{Name: "Idempotency-Key", Error: validate.ErrFieldRequired}}},
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationHeader, Pointer: "/Idempotency-Key", Code: "required", Message: fieldMessageRequired}},
},
{
name: "missing body",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", nil),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.ErrBodyRequired},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "required", Message: fieldMessageRequired}},
},
{
name: "missing top-level body field",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{
ContentType: "application/json", Body: []byte(`{}`),
Err: &validate.Error{Fields: []validate.FieldError{{Name: "name", Error: validate.ErrFieldRequired}}},
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/name", Code: "required", Message: fieldMessageRequired}},
},
{
name: "nested decoding failure has no reliable path",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"page":{}}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: &ogenerrors.DecodeBodyError{
ContentType: "application/json", Body: []byte(`{"page":{}}`),
Err: fmt.Errorf("decode field \"page\": %w", &validate.Error{Fields: []validate.FieldError{{Name: "has_more", Error: validate.ErrFieldRequired}}}),
}},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "schema validation keeps nested paths",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: fmt.Errorf("validate: %w", &validate.Error{Fields: []validate.FieldError{
{Name: "items", Error: &validate.Error{Fields: []validate.FieldError{
{Name: "[2]", Error: &validate.Error{Fields: []validate.FieldError{{Name: "a/b", Error: &validate.MaxLengthError{Len: 101, MaxLength: 100}}}}},
}}},
}})},
statusCode: http.StatusBadRequest,
code: api.ProblemCodeValidationFailed,
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/items/2/a~1b", Code: "invalid", Message: fieldMessageInvalid}},
},
{
name: "body over the size limit",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{"name":"probe"}`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: readOverLimit(t)},
statusCode: http.StatusRequestEntityTooLarge,
code: api.ProblemCodePayloadTooLarge,
},
{
name: "unsupported media type",
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`name`)),
err: &ogenerrors.DecodeRequestError{OperationContext: operation, Err: validate.InvalidContentType("text/plain")},
statusCode: http.StatusUnsupportedMediaType,
code: api.ProblemCodeUnsupportedMediaType,
},
{
name: "security failure",
request: httptest.NewRequest(http.MethodGet, "/api/v1/items", nil),
err: &ogenerrors.SecurityError{OperationContext: operation, Security: "cookieAuth", Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied},
statusCode: http.StatusUnauthorized,
code: api.ProblemCodeUnauthenticated,
},
} {
t.Run(test.name, func(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
response := httptest.NewRecorder()
responder.HandleServerError(test.request.Context(), response, test.request, test.err)
body := decodeProblem(t, response, test.statusCode, test.code)
if !reflect.DeepEqual(body.Errors, test.fields) {
t.Fatalf("errors = %+v, want %+v", body.Errors, test.fields)
}
if logs.Len() != 0 {
t.Fatalf("a client error was logged as a server failure: %s", logs.String())
}
})
}
}
func TestHandleServerErrorHidesAndLogsUnexpectedErrors(t *testing.T) {
const internalText = "encode response: write failed"
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
request := httptest.NewRequest(http.MethodGet, "/api/v1/items", nil)
response := httptest.NewRecorder()
responder.HandleServerError(request.Context(), response, request, errors.New(internalText))
decodeProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
if strings.Contains(response.Body.String(), "write failed") {
t.Fatalf("response exposes internal error text: %s", response.Body.String())
}
if !strings.Contains(logs.String(), internalText) || !strings.Contains(logs.String(), `"level":"ERROR"`) {
t.Fatalf("unexpected error was not logged as an error: %s", logs.String())
}
}
func TestClientCancellationIsNotLoggedAsServerFailure(t *testing.T) {
var logs bytes.Buffer
responder := NewResponder(slog.New(slog.NewJSONHandler(&logs, nil)))
got := responder.HandlerError(context.Background(), fmt.Errorf("HealthHandler.GetHealthz - query: %w", context.Canceled))
if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("canceled request = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
if strings.Contains(logs.String(), `"level":"ERROR"`) || !strings.Contains(logs.String(), "canceled by client") {
t.Fatalf("client cancellation was not logged at info level: %s", logs.String())
}
}
func TestHandlerErrorSeparatesSecurityFailures(t *testing.T) {
responder := NewResponder(slog.New(slog.DiscardHandler))
securityErr := &ogenerrors.SecurityError{Security: "cookieAuth", Err: errors.New("session expired")}
if got := responder.HandlerError(context.Background(), securityErr); got.StatusCode != http.StatusUnauthorized || got.Response.Code != api.ProblemCodeUnauthenticated {
t.Fatalf("security failure = %d %q, want 401 unauthenticated", got.StatusCode, got.Response.Code)
}
if got := responder.HandlerError(context.Background(), errors.New("query failed")); got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("internal failure = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
}
func TestNewFallsBackToInternalForUnknownCode(t *testing.T) {
got := New(context.Background(), api.ProblemCode("undocumented"))
if got.StatusCode != http.StatusInternalServerError || got.Response.Code != api.ProblemCodeInternal {
t.Fatalf("unknown code = %d %q, want 500 internal", got.StatusCode, got.Response.Code)
}
}
func TestEveryContractCodeHasAnErrorStatus(t *testing.T) {
for _, code := range api.ProblemCodeInternal.AllValues() {
got := New(context.Background(), code)
if got.Response.Code != code {
t.Errorf("code %q has no definition and falls back to %q", code, got.Response.Code)
}
if err := got.Response.Validate(); err != nil {
t.Errorf("code %q builds an invalid problem: %v", code, err)
}
}
}
func decodeProblem(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 != MediaType {
t.Fatalf("Content-Type = %q, want %q", contentType, 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 {
t.Fatalf("code = %q, want %q", body.Code, code)
}
return body
}
func missingQueryParameter(name string) error {
return uri.NewQueryDecoder(url.Values{}).HasParam(uri.QueryParameterDecodingConfig{
Name: name, Style: uri.QueryStyleForm, Explode: true,
})
}
// readOverLimit returns the error that http.MaxBytesReader produces, as the
// generated request decoder would receive it.
func readOverLimit(t *testing.T) error {
t.Helper()
body := http.MaxBytesReader(httptest.NewRecorder(), io.NopCloser(strings.NewReader(`{"name":"probe"}`)), 4)
_, err := io.ReadAll(body)
if err == nil {
t.Fatal("MaxBytesReader accepted a body over its limit")
}
return err
}