package problem import ( "context" "errors" "fmt" "log/slog" "net/http" "regexp" "strings" faster "github.com/go-faster/errors" 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 = "" ) // decodeFieldMessage matches the message of the wrapper that generated // decoders put around the error of one object field, for example // `decode field "terms"`. The name is the JSON property name, which in this // contract never contains a quote or a backslash. var decodeFieldMessage = regexp.MustCompile(`^decode field "([^"\\]+)"$`) // arrayElementMessage is the message of the wrapper that jx puts around the // error of a callback. Directly under a field wrapper it marks an array // element, because an object value is always wrapped first by its own // `decode ` message. const arrayElementMessage = "callback" // 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 { fields = decodeFieldErrors(decodeErr.Err) } 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 } // decodeFieldErrors maps an error of the generated JSON decoder to field // errors. The decoder records no path of its own; it wraps the error of each // object field with `decode field ""` through go-faster/errors. The // pointer is rebuilt from those wrappers, read through the typed // errors.Formatter of each link rather than from the joined error text: // - a *validate.Error lists the missing required fields of the object at the // pointer, which become `required` with their own pointer; // - an array element has no index in the chain, so the pointer stops at the // array with `invalid`; // - any other failure, such as a wrong JSON type, an unknown property, an // unknown oneOf variant, or a malformed value, is `invalid` at the pointer // of the value whose decoding failed; // - a link that is neither a go-faster wrapper nor a leaf ends the walk with // `invalid` at the pointer reached so far, which is the whole body when no // field wrapper was recognized. func decodeFieldErrors(err error) []api.ProblemFieldError { pointer := wholeBodyPointer afterField := false for err != nil { if validationErr, ok := err.(*validate.Error); ok { //nolint:errorlint // the walk inspects each link of the chain itself return appendSchemaFieldErrors(nil, validationErr, pointer) } formatter, ok := err.(faster.Formatter) //nolint:errorlint // the walk inspects each link of the chain itself if !ok { break } message, next := linkMessage(formatter) switch match := decodeFieldMessage.FindStringSubmatch(message); { case match != nil: pointer += "/" + escapePointerToken(match[1]) afterField = true case message == arrayElementMessage && afterField: return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, pointer, fieldCodeInvalid)} default: afterField = false } err = next } return []api.ProblemFieldError{fieldError(api.ProblemFieldLocationBody, pointer, fieldCodeInvalid)} } // linkMessage returns the message of one link of a go-faster/errors chain // without the messages of the links it wraps, and the next link. func linkMessage(link faster.Formatter) (string, error) { printer := &messagePrinter{} next := link.FormatError(printer) return printer.message.String(), next } // messagePrinter collects the message of one error link. It never asks for // details, so no stack frame is printed. type messagePrinter struct { message strings.Builder } func (printer *messagePrinter) Print(args ...any) { _, _ = fmt.Fprint(&printer.message, args...) } func (printer *messagePrinter) Printf(format string, args ...any) { _, _ = fmt.Fprintf(&printer.message, format, args...) } func (*messagePrinter) Detail() bool { return false } 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} }