241 lines
8.8 KiB
Go
241 lines
8.8 KiB
Go
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}
|
|
}
|