diff --git a/cmd/twoctl/cli/validation.go b/cmd/twoctl/cli/validation.go index 92af35f..4782a21 100644 --- a/cmd/twoctl/cli/validation.go +++ b/cmd/twoctl/cli/validation.go @@ -6,8 +6,10 @@ import ( "errors" "fmt" "io" + "math/big" "net/http" "sort" + "strconv" "strings" "github.com/getkin/kin-openapi/openapi3" @@ -22,18 +24,21 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { } return nil } - var value any - if err := json.Unmarshal(raw, &value); err != nil { - return payloadError("request body must contain one valid JSON value") + value, err := decodePayload(raw) + if err != nil { + return err } - if op.RequestBody == nil || op.RequestBody.Value == nil { + schema := payloadSchema(op) + if schema == nil { return nil } - mt := op.RequestBody.Value.Content.Get("application/json") - if mt == nil || mt.Schema == nil || mt.Schema.Value == nil { + value, inexact := floatPayload(value, "") + if inexact != "" { + // The validator compares numbers as float64, so it could pass or reject + // this one wrongly; let the API decide. + fmt.Fprintf(w, "warning: number at %q cannot be checked exactly; skipping local schema validation (the API will validate it)\n", inexact) 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 @@ -56,6 +61,91 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { return nil } +// decodePayload keeps numbers as json.Number so precision loss can be detected. +func decodePayload(raw []byte) (any, error) { + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var value any + if err := dec.Decode(&value); err != nil || dec.Decode(&struct{}{}) != io.EOF { + return nil, payloadError("request body must contain one valid JSON value") + } + return value, nil +} + +func payloadSchema(op *openapi3.Operation) *openapi3.Schema { + if op.RequestBody == nil || op.RequestBody.Value == nil { + return nil + } + mt := op.RequestBody.Value.Content.Get("application/json") + if mt == nil || mt.Schema == nil { + return nil + } + return mt.Schema.Value +} + +// floatPayload converts JSON numbers to float64 and returns the path of the +// first number that float64 cannot represent exactly. +func floatPayload(value any, path string) (any, string) { + switch v := value.(type) { + case json.Number: + f, exact := exactFloat(v.String()) + if !exact { + return value, pointerOrRoot(path) + } + return f, "" + case map[string]any: + out := make(map[string]any, len(v)) + keys := make([]string, 0, len(v)) + for key := range v { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + item, inexact := floatPayload(v[key], path+"/"+strings.ReplaceAll(strings.ReplaceAll(key, "~", "~0"), "/", "~1")) + if inexact != "" { + return value, inexact + } + out[key] = item + } + return out, "" + case []any: + out := make([]any, len(v)) + for i, item := range v { + converted, inexact := floatPayload(item, fmt.Sprintf("%s/%d", path, i)) + if inexact != "" { + return value, inexact + } + out[i] = converted + } + return out, "" + default: + return value, "" + } +} + +// exactFloat reports whether the shortest float64 rendering of literal has the +// same value, so 0.1 is exact but 36.000000000000001 and 1e400 are not. +func exactFloat(literal string) (float64, bool) { + f, err := strconv.ParseFloat(literal, 64) + if err != nil { + return 0, false + } + if f == 0 { + mantissa := strings.TrimLeft(strings.SplitN(strings.ToLower(literal), "e", 2)[0], "-") + return f, strings.Trim(mantissa, "0.") == "" + } + want, ok := new(big.Rat).SetString(literal) + got, ok2 := new(big.Rat).SetString(strconv.FormatFloat(f, 'g', -1, 64)) + return f, ok && ok2 && want.Cmp(got) == 0 +} + +func pointerOrRoot(path string) string { + if path == "" { + return "/" + } + return path +} + func payloadError(message string) error { return &apiError{code: "invalid_request_body", message: message, exit: ExitUsage} } diff --git a/cmd/twoctl/cli/validation_test.go b/cmd/twoctl/cli/validation_test.go index 00f7216..35994bf 100644 --- a/cmd/twoctl/cli/validation_test.go +++ b/cmd/twoctl/cli/validation_test.go @@ -41,6 +41,14 @@ func TestPayloadValidation(t *testing.T) { {"malformed", `{"secret":`, "", true}, {"multiple values", `{} {}`, "", true}, {"null", `null`, "", true}, + {"exact decimal still validated", `{"amount":0.5,"currency":"GBP"}`, "", true}, + {"large exact integer", `{"amount":9007199254740992,"currency":"GBP"}`, "", false}, + {"fraction lost in float64", `{"amount":1.0000000000000001,"currency":"secret"}`, `"/amount" cannot be checked exactly`, false}, + {"integer beyond float64", `{"amount":9007199254740993,"currency":"GBP"}`, `"/amount" cannot be checked exactly`, false}, + {"out of float64 range", `{"amount":1e400,"currency":"GBP"}`, `"/amount" cannot be checked exactly`, false}, + {"underflow", `{"amount":1e-400,"currency":"GBP"}`, `"/amount" cannot be checked exactly`, false}, + {"nested inexact", `{"amount":1,"currency":"GBP","lines":[{"name":"x","qty":1e400}]}`, `"/lines/0/qty" cannot be checked exactly`, false}, + {"zero", `{"amount":-0.0e10,"currency":"GBP"}`, "", true}, } { t.Run(tc.name, func(t *testing.T) { var warnings bytes.Buffer