From a92d0949c7dd9ca8d12e66a3a5e87e85b77e70a6 Mon Sep 17 00:00:00 2001 From: Bharat Kunwar Date: Tue, 3 Nov 2026 14:34:44 +0545 Subject: [PATCH 1/2] PLAT-1314/fix: skip local validation for numbers float64 cannot hold exactly Payload validation decoded numbers as float64, so 36.000000000000001 could pass an integer or maximum check and numbers outside float64 range were reported as invalid JSON. Numbers are now decoded losslessly; when one cannot be represented exactly, the CLI warns and sends the body unchanged for the API to validate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QUnP8hJ3og3dxSHHcYij5n --- cmd/twoctl/cli/validation.go | 76 ++++++++++++++++++++++++++++++- cmd/twoctl/cli/validation_test.go | 8 ++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/cmd/twoctl/cli/validation.go b/cmd/twoctl/cli/validation.go index 92af35f..ec48c5b 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,8 +24,10 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { } return nil } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() var value any - if err := json.Unmarshal(raw, &value); err != nil { + if err := dec.Decode(&value); err != nil || dec.Decode(&struct{}{}) != io.EOF { return payloadError("request body must contain one valid JSON value") } if op.RequestBody == nil || op.RequestBody.Value == nil { @@ -34,6 +38,13 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { return nil } schema := mt.Schema.Value + 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 + } 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 +67,69 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { return nil } +// 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 From 1215a61a1c58d44036212b78fde80efa612eb6e6 Mon Sep 17 00:00:00 2001 From: Bharat Kunwar Date: Tue, 3 Nov 2026 14:36:12 +0545 Subject: [PATCH 2/2] PLAT-1314/refactor: split payload decoding out of validatePayload Keeps validatePayload under the gocyclo threshold of 15. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QUnP8hJ3og3dxSHHcYij5n --- cmd/twoctl/cli/validation.go | 38 +++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/cmd/twoctl/cli/validation.go b/cmd/twoctl/cli/validation.go index ec48c5b..4782a21 100644 --- a/cmd/twoctl/cli/validation.go +++ b/cmd/twoctl/cli/validation.go @@ -24,20 +24,14 @@ func validatePayload(w io.Writer, op *openapi3.Operation, raw []byte) error { } return nil } - dec := json.NewDecoder(bytes.NewReader(raw)) - dec.UseNumber() - var value any - if err := dec.Decode(&value); err != nil || dec.Decode(&struct{}{}) != io.EOF { - return payloadError("request body must contain one valid JSON value") - } - if op.RequestBody == nil || op.RequestBody.Value == nil { - return nil + value, err := decodePayload(raw) + if err != nil { + return err } - mt := op.RequestBody.Value.Content.Get("application/json") - if mt == nil || mt.Schema == nil || mt.Schema.Value == nil { + schema := payloadSchema(op) + if schema == nil { return nil } - schema := mt.Schema.Value value, inexact := floatPayload(value, "") if inexact != "" { // The validator compares numbers as float64, so it could pass or reject @@ -67,6 +61,28 @@ 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) {