feat(api): add invitation, terms version, acceptance, and contact grant contract
This commit is contained in:
1 parent
b856d4ff54
commit
d2c6f1375a
140 files changed
+39767
-303
No files matched your search
@@ -3,11 +3,13 @@ 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"
|
||||
@@ -32,6 +34,18 @@ const (
|
||||
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 <Type>` message.
|
||||
const arrayElementMessage = "callback"
|
||||
|
||||
// arrayIndexName matches the "[index]" names that generated validators use
|
||||
// for array items.
|
||||
var arrayIndexName = regexp.MustCompile(`^\[(\d+)\]$`)
|
||||
@@ -184,12 +198,7 @@ func bodyFieldErrors(err error) []api.ProblemFieldError {
|
||||
|
||||
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)
|
||||
}
|
||||
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)
|
||||
@@ -200,6 +209,71 @@ func bodyFieldErrors(err error) []api.ProblemFieldError {
|
||||
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 "<name>"` 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 {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
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"
|
||||
@@ -96,16 +97,95 @@ func TestHandleServerErrorMapsGeneratedErrors(t *testing.T) {
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/name", Code: "required", Message: fieldMessageRequired}},
|
||||
},
|
||||
{
|
||||
name: "nested decoding failure has no reliable path",
|
||||
// A chain without go-faster field wrappers is not recognized, so
|
||||
// even an error text that looks like a field path maps to the
|
||||
// whole body.
|
||||
name: "unrecognized decoding chain falls back to the whole body",
|
||||
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}}}),
|
||||
}},
|
||||
err: decodeBodyError(`{"page":{}}`,
|
||||
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: "missing field of a nested object",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedField(generatedObject("CreateItem", generatedField(generatedObject("Terms",
|
||||
generatedField(&validate.Error{Fields: []validate.FieldError{
|
||||
{Name: "tax_basis", Error: validate.ErrFieldRequired},
|
||||
{Name: "a/b", Error: validate.ErrFieldRequired},
|
||||
}}, "salary")), "terms")), "")),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{
|
||||
{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary/tax_basis", Code: "required", Message: fieldMessageRequired},
|
||||
{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary/a~1b", Code: "required", Message: fieldMessageRequired},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid value of a nested object",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(generatedObject("Terms",
|
||||
generatedField(faster.Wrap(errors.New(`unexpected byte 34 '"'`), `"{" expected`), "salary")), "terms"))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/terms/salary", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
// jx reports no index for an array element, so the pointer stops
|
||||
// at the array.
|
||||
name: "nested array element",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(faster.Wrap(
|
||||
&validate.Error{Fields: []validate.FieldError{{Name: "status", Error: validate.ErrFieldRequired}}}, "callback"), "skills"))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/skills", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "field of a oneOf variant",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateComplaint", generatedField(generatedObject("Reference",
|
||||
generatedField(errors.New("invalid UUID length: 2"), "id")), "object"))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/object/id", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "ambiguous oneOf value of a nested field",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(
|
||||
faster.Wrap(faster.Wrap(errors.New("multiple oneOf matches"), "callback"), "capture"), "training"))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/training", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "unknown top-level oneOf variant",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, errors.New("unable to detect sum type variant")),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "unknown top-level field",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateItem", errors.New(`unexpected field "state"`))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "foreign wrapper inside a recognized chain",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
err: decodeBodyError(`{}`, generatedObject("CreateItem", generatedField(
|
||||
fmt.Errorf("parse: %w", &validate.Error{Fields: []validate.FieldError{{Name: "inner", Error: validate.ErrFieldRequired}}}), "terms"))),
|
||||
statusCode: http.StatusBadRequest,
|
||||
code: api.ProblemCodeValidationFailed,
|
||||
fields: []api.ProblemFieldError{{In: api.ProblemFieldLocationBody, Pointer: "/terms", Code: "invalid", Message: fieldMessageInvalid}},
|
||||
},
|
||||
{
|
||||
name: "schema validation keeps nested paths",
|
||||
request: httptest.NewRequest(http.MethodPost, "/api/v1/items", strings.NewReader(`{}`)),
|
||||
@@ -259,3 +339,27 @@ func readOverLimit(t *testing.T) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// decodeBodyError wraps a decoder error the way the generated request decoder
|
||||
// does.
|
||||
func decodeBodyError(body string, err error) error {
|
||||
return &ogenerrors.DecodeRequestError{
|
||||
OperationContext: ogenerrors.OperationContext{Name: "CreateItem", ID: "CreateItem"},
|
||||
Err: &ogenerrors.DecodeBodyError{ContentType: "application/json", Body: []byte(body), Err: err},
|
||||
}
|
||||
}
|
||||
|
||||
// generatedObject wraps the error of an object field the way a generated
|
||||
// Decode method and the jx object callback do.
|
||||
func generatedObject(typeName string, err error) error {
|
||||
return faster.Wrap(faster.Wrap(err, "callback"), "decode "+typeName)
|
||||
}
|
||||
|
||||
// generatedField wraps the error of one field value the way a generated
|
||||
// Decode method does. An empty name returns the error unchanged.
|
||||
func generatedField(err error, name string) error {
|
||||
if name == "" {
|
||||
return err
|
||||
}
|
||||
return faster.Wrap(err, `decode field "`+name+`"`)
|
||||
}
|
||||
Reference in new issue
Block a user