Repository navigation
PLAT-1314/feat: validate JSON payloads before API requests #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
411adaa
feat: validate request payloads before sending (PLAT-1314)
brtkwr 068ee57
test: correct payload schema fixture and typo case
brtkwr 209cce7
test: match root error output policy and simplify source fixtures
brtkwr 774e61a
fix: reject empty required bodies and cover dry-run validation
brtkwr a26a0a9
fix: preserve closed oneOf discrimination during permissive validation
brtkwr 38a4167
fix: preserve original schema constraints with a private payload proj…
brtkwr 2b7647c
fix: use composition item union for unknown-field warnings
brtkwr bb8c8ad
PLAT-1314/merge: integrate current main into payload validation
brtkwr f054d90
Merge branch 'main' into bkunwar/plat-1314-payload-validation
brtkwr 26e2a93
PLAT-1314/test: give diagnostics test a schema-valid probe operation
brtkwr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| package cli | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "sort" | ||
| "strings" | ||
|
|
||
| "github.com/getkin/kin-openapi/openapi3" | ||
| ) | ||
|
|
||
| // validatePayload checks a private payload projection. Shared embedded schemas | ||
| // and the original bytes sent to the API are never modified. | ||
| func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { | ||
| if len(raw) == 0 { | ||
| if op.RequestBody != nil && op.RequestBody.Value != nil && op.RequestBody.Value.Required { | ||
| return payloadError("request body is required") | ||
| } | ||
| return nil | ||
| } | ||
| var value any | ||
| if err := json.Unmarshal(raw, &value); err != nil { | ||
| return payloadError("request body must contain one valid JSON value") | ||
| } | ||
| if op.RequestBody == nil || op.RequestBody.Value == nil { | ||
| return nil | ||
| } | ||
| mt := op.RequestBody.Value.Content.Get("application/json") | ||
| if mt == nil || mt.Schema == nil || mt.Schema.Value == nil { | ||
| return nil | ||
| } | ||
| schema := mt.Schema.Value | ||
| if err := schema.VisitJSON(pruneUnknownPayload(schema, value), openapi3.VisitAsRequest()); err != nil { | ||
| // Do not render SchemaError.Error(): it includes the submitted payload. | ||
| var schemaErr *openapi3.SchemaError | ||
| if errors.As(err, &schemaErr) { | ||
| return payloadError(fmt.Sprintf("request body violates %s at %q; use --describe to inspect the schema", | ||
| schemaErr.SchemaField, "/"+strings.Join(schemaErr.JSONPointer(), "/"))) | ||
| } | ||
| return payloadError("request body does not match the operation schema; use --describe") | ||
| } | ||
| warnings := map[string]bool{} | ||
| unknownPayloadFields(schema, value, "", warnings) | ||
| paths := make([]string, 0, len(warnings)) | ||
| for path := range warnings { | ||
| paths = append(paths, path) | ||
| } | ||
| sort.Strings(paths) | ||
| for _, path := range paths { | ||
| fmt.Fprintf(w, "warning: unknown request property at %q; sending unchanged (the API schema may have drifted)\n", path) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func payloadError(message string) error { | ||
| return &apiError{code: "invalid_request_body", message: message, exit: ExitUsage} | ||
| } | ||
|
|
||
| func unknownPayloadFields(s *openapi3.Schema, value any, path string, warnings map[string]bool) { | ||
| schemas := allPayloadSchemas(s, map[*openapi3.Schema]bool{}) | ||
| switch v := value.(type) { | ||
| case map[string]any: | ||
| unknownObjectFields(schemas, v, path, warnings) | ||
| case []any: | ||
| items := payloadItemSchema(schemas) | ||
| for i, item := range v { | ||
| unknownPayloadFields(items, item, fmt.Sprintf("%s/%d", path, i), warnings) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func unknownObjectFields(schemas []*openapi3.Schema, value map[string]any, path string, warnings map[string]bool) { | ||
| shape := payloadObjectShape(schemas) | ||
| for key, item := range value { | ||
| childPath := path + "/" + strings.ReplaceAll(strings.ReplaceAll(key, "~", "~0"), "/", "~1") | ||
| if ref := shape.props[key]; ref != nil { | ||
| unknownPayloadFields(ref.Value, item, childPath, warnings) | ||
| } else if shape.open { | ||
| unknownPayloadFields(shape.extra, item, childPath, warnings) | ||
| } else if shape.declared { | ||
| warnings[childPath] = true | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func readValidatedRequestBody(w io.Writer, op *openapi3.Operation, b *opBindings, headers http.Header) (io.Reader, error) { | ||
| if b.bodyFile == nil || b.bodyData == nil { | ||
| return nil, nil | ||
| } | ||
| raw, err := readBody(*b.bodyFile, *b.bodyData) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if err := validatePayload(w, op, raw); err != nil { | ||
| return nil, err | ||
| } | ||
| if len(raw) == 0 { | ||
| return nil, nil | ||
| } | ||
| headers.Set("Content-Type", "application/json") | ||
| return bytes.NewReader(raw), nil | ||
| } | ||
|
|
||
| func allPayloadSchemas(s *openapi3.Schema, seen map[*openapi3.Schema]bool) []*openapi3.Schema { | ||
| if s == nil || seen[s] { | ||
| return nil | ||
| } | ||
| seen[s] = true | ||
| out := []*openapi3.Schema{s} | ||
| refs := append(append(append(openapi3.SchemaRefs{}, s.AllOf...), s.AnyOf...), s.OneOf...) | ||
| for _, ref := range refs { | ||
| if ref != nil { | ||
| out = append(out, allPayloadSchemas(ref.Value, seen)...) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| func pruneUnknownPayload(s *openapi3.Schema, value any) any { | ||
| schemas := allPayloadSchemas(s, map[*openapi3.Schema]bool{}) | ||
| switch v := value.(type) { | ||
| case map[string]any: | ||
| return pruneUnknownObject(schemas, v) | ||
| case []any: | ||
| items := payloadItemSchema(schemas) | ||
| out := make([]any, len(v)) | ||
| for i, item := range v { | ||
| out[i] = pruneUnknownPayload(items, item) | ||
| } | ||
| return out | ||
| default: | ||
| return value | ||
| } | ||
| } | ||
|
|
||
| type payloadShape struct { | ||
| props openapi3.Schemas | ||
| extra *openapi3.Schema | ||
| open, declared bool | ||
| } | ||
|
|
||
| func payloadObjectShape(schemas []*openapi3.Schema) payloadShape { | ||
| shape := payloadShape{props: openapi3.Schemas{}, extra: &openapi3.Schema{}} | ||
| for _, schema := range schemas { | ||
| if schema.AdditionalProperties.Schema != nil { | ||
| shape.extra.AllOf = append(shape.extra.AllOf, schema.AdditionalProperties.Schema) | ||
| } | ||
| shape.open = shape.open || schema.AdditionalProperties.Schema != nil || | ||
| (schema.AdditionalProperties.Has != nil && *schema.AdditionalProperties.Has) | ||
| shape.declared = shape.declared || len(schema.Properties) > 0 || | ||
| (schema.AdditionalProperties.Has != nil && !*schema.AdditionalProperties.Has) | ||
| for key, ref := range schema.Properties { | ||
| if shape.props[key] == nil { | ||
| shape.props[key] = &openapi3.SchemaRef{Value: &openapi3.Schema{}} | ||
| } | ||
| shape.props[key].Value.AllOf = append(shape.props[key].Value.AllOf, ref) | ||
| } | ||
| } | ||
| return shape | ||
| } | ||
|
|
||
| func pruneUnknownObject(schemas []*openapi3.Schema, value map[string]any) map[string]any { | ||
| shape := payloadObjectShape(schemas) | ||
| out := map[string]any{} | ||
| for key, item := range value { | ||
| if ref := shape.props[key]; ref != nil { | ||
| out[key] = pruneUnknownPayload(ref.Value, item) | ||
| } else if shape.open || !shape.declared { | ||
| out[key] = pruneUnknownPayload(shape.extra, item) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| func payloadItemSchema(schemas []*openapi3.Schema) *openapi3.Schema { | ||
| items := &openapi3.Schema{} | ||
| for _, schema := range schemas { | ||
| if schema.Items != nil { | ||
| items.AllOf = append(items.AllOf, schema.Items) | ||
| } | ||
| } | ||
| return items | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a payload contains a high-precision number, unmarshalling into
anyconverts it tofloat64before schema validation. This can change the value or even turn a non-integer into an integer—for example,36.000000000000001rounds to36and can pass an integer schema withmaximum: 36; sufficiently large valid JSON numbers also fail decoding as though the JSON were malformed. Validate a lossless numeric representation so constraints are checked against the value that will actually be sent.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed in #15: numbers are decoded losslessly, and any that float64 can't hold exactly skip local validation with a warning so the API decides.