From 67736a96d162dc2d1d0c2ea671402ef3899e3e1c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 00:33:09 -0500 Subject: [PATCH 1/4] fix(mcpx): compare integer headers numerically for float-form bodies (#1665) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit plain() rendered a JSON number only through ParseInt, so a whole-valued body literal in float form (42.0, 42.00, 4.2e1, -0.0) errored as not-an-integer before Check's numeric fallback could run — the spec's numeric comparison only ever forgave the header's form, and even byte-identical 42.0/42.0 was rejected. plain() now falls back to ParseFloat and renders integral values as integers, preserving the not-an-integer error for non-integral values and the 2^53-1 safe-range guard. Adds the package's first test file pinning both directions (triage: queue task 1862; fix: queue task 4222). --- pkgs/mcpx/internal/mcpheaders/mcpheaders.go | 23 +++++++-- .../internal/mcpheaders/mcpheaders_test.go | 50 +++++++++++++++++++ 2 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go index c1a339ef89..4f5f2198e5 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go @@ -11,6 +11,7 @@ import ( "encoding/base64" "encoding/json" "fmt" + "math" "sort" "strconv" "strings" @@ -290,14 +291,26 @@ func plain(root any, p Param) (string, bool, error) { case bool: return strconv.FormatBool(x), true, nil case json.Number: - i, err := strconv.ParseInt(x.String(), 10, 64) - if err != nil { + if i, err := strconv.ParseInt(x.String(), 10, 64); err == nil { + if i > maxSafeInt || i < -maxSafeInt { + return "", false, fmt.Errorf("%s: %d is outside the JavaScript safe-integer range", strings.Join(p.Path, "."), i) + } + return strconv.FormatInt(i, 10), true, nil + } + // A whole-valued number written in float form (42.0, 42.00, + // 4.2e1, -0.0) is an integer for comparison purposes: JSON + // Schema's integer type accepts it and the spec says integers + // compare numerically. Rejecting it here, before Check's + // numeric fallback can run, made the forgiveness one-sided — + // it only ever applied to the header's form (#1665). + f, err := strconv.ParseFloat(x.String(), 64) + if err != nil || math.Trunc(f) != f { return "", false, fmt.Errorf("%s: %s is not an integer", strings.Join(p.Path, "."), x) } - if i > maxSafeInt || i < -maxSafeInt { - return "", false, fmt.Errorf("%s: %d is outside the JavaScript safe-integer range", strings.Join(p.Path, "."), i) + if f > float64(maxSafeInt) || f < -float64(maxSafeInt) { + return "", false, fmt.Errorf("%s: %s is outside the JavaScript safe-integer range", strings.Join(p.Path, "."), x) } - return strconv.FormatInt(i, 10), true, nil + return strconv.FormatInt(int64(f), 10), true, nil } return "", false, fmt.Errorf("%s: a %T cannot be mirrored into a header", strings.Join(p.Path, "."), v) } diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go new file mode 100644 index 0000000000..95673ca5fa --- /dev/null +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go @@ -0,0 +1,50 @@ +package mcpheaders + +import ( + "encoding/json" + "strings" + "testing" +) + +// TestCheckIntegerComparesNumericallyBothWays pins #1665: an integer +// body value compares numerically against the header whichever side +// carries the float form. Before the fix, plain() rejected any +// float-form body literal as "not an integer" before the comparison +// ran, so only a float-form header was forgiven. +func TestCheckIntegerComparesNumericallyBothWays(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + header := func(v string) func(string) (string, bool) { + return func(string) (string, bool) { return v, true } + } + accepted := []struct{ args, hdr string }{ + {`{"n": 42}`, "42"}, + {`{"n": 42}`, "42.0"}, + {`{"n": 42.0}`, "42"}, + {`{"n": 42.0}`, "42.0"}, + {`{"n": 42.00}`, "42"}, + {`{"n": 4.2e1}`, "42"}, + {`{"n": -0.0}`, "0"}, + } + for _, c := range accepted { + if err := Check(params, json.RawMessage(c.args), header(c.hdr)); err != nil { + t.Errorf("Check(%s, header %q) = %v, want nil", c.args, c.hdr, err) + } + } + rejected := []struct { + args, hdr, want string + }{ + {`{"n": 42}`, "43", "does not match"}, + {`{"n": 42.0}`, "43", "does not match"}, + {`{"n": 42.5}`, "42", "is not an integer"}, + {`{"n": 9007199254740993}`, "9007199254740993", "outside the JavaScript safe-integer range"}, + {`{"n": 1e20}`, "100000000000000000000", "outside the JavaScript safe-integer range"}, + } + for _, c := range rejected { + err := Check(params, json.RawMessage(c.args), header(c.hdr)) + if err == nil { + t.Errorf("Check(%s, header %q) = nil, want error containing %q", c.args, c.hdr, c.want) + } else if !strings.Contains(err.Error(), c.want) { + t.Errorf("Check(%s, header %q) = %v, want error containing %q", c.args, c.hdr, err, c.want) + } + } +} From 3930c15886193f65944c7180ee6d6965b34bc20a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 01:00:18 -0500 Subject: [PATCH 2/4] fix(mcpx): judge integer headers on exact decimal value, not float64 (Codex P2 on #2955) plain()ParseFloat+Trunc rounded 9007199254740990.5 to an integer, underflowed 1e-400 to 0, and rounded 9007199254740991.0 out of range; Check numeric fallback had the same float64 equality flaw on the header side. Integrality and comparison now use big.Rat on the exact literal (boundedRat caps absurd exponents so 1e999999999 cannot force a billion-digit allocation), preserving the not-an-integer / outside-safe-range verdicts. Failing-first permutations in TestCheckIntegerPrecisionPermutations (7 failures pre-fix), incl. a correction found while fixing: 9007199254740991.0 is exactly maxSafeInt and is now correctly accepted. --- pkgs/mcpx/internal/mcpheaders/mcpheaders.go | 101 +++++++++++++++--- .../internal/mcpheaders/mcpheaders_test.go | 54 ++++++++++ 2 files changed, 139 insertions(+), 16 deletions(-) diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go index 4f5f2198e5..1e106487d3 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go @@ -11,7 +11,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "math" + "math/big" "sort" "strconv" "strings" @@ -231,10 +231,12 @@ func Check(params []Param, args json.RawMessage, header func(string) (string, bo continue } // Integers compare numerically: 42.0 in a header is 42. + // The comparison is exact: a float64 round-trip would call + // 9007199254740990.5 equal to 9007199254740990. if _, isNum := lookupNumber(root, p.Path); isNum { - hf, herr := strconv.ParseFloat(got, 64) - bf, berr := strconv.ParseFloat(body, 64) - if herr == nil && berr == nil && hf == bf { + hf, hok := exactNumber(got) + bf, bok := exactNumber(body) + if hok && bok && hf.Cmp(bf) == 0 { continue } } @@ -291,30 +293,97 @@ func plain(root any, p Param) (string, bool, error) { case bool: return strconv.FormatBool(x), true, nil case json.Number: - if i, err := strconv.ParseInt(x.String(), 10, 64); err == nil { - if i > maxSafeInt || i < -maxSafeInt { - return "", false, fmt.Errorf("%s: %d is outside the JavaScript safe-integer range", strings.Join(p.Path, "."), i) - } - return strconv.FormatInt(i, 10), true, nil - } // A whole-valued number written in float form (42.0, 42.00, // 4.2e1, -0.0) is an integer for comparison purposes: JSON // Schema's integer type accepts it and the spec says integers // compare numerically. Rejecting it here, before Check's // numeric fallback can run, made the forgiveness one-sided — - // it only ever applied to the header's form (#1665). - f, err := strconv.ParseFloat(x.String(), 64) - if err != nil || math.Trunc(f) != f { + // it only ever applied to the header's form (#1665). The + // verdict is computed on the exact decimal value: a float64 + // round-trip rounds 9007199254740990.5 to an integer and + // underflows 1e-400 to 0. + i, verdict := exactInteger(x.String()) + switch verdict { + case integerNotWhole: return "", false, fmt.Errorf("%s: %s is not an integer", strings.Join(p.Path, "."), x) - } - if f > float64(maxSafeInt) || f < -float64(maxSafeInt) { + case integerOutOfRange: return "", false, fmt.Errorf("%s: %s is outside the JavaScript safe-integer range", strings.Join(p.Path, "."), x) } - return strconv.FormatInt(int64(f), 10), true, nil + return strconv.FormatInt(i, 10), true, nil } return "", false, fmt.Errorf("%s: a %T cannot be mirrored into a header", strings.Join(p.Path, "."), v) } +type integerVerdict int + +const ( + integerOK integerVerdict = iota + integerNotWhole + integerOutOfRange +) + +// exactInteger judges a JSON number literal on its exact decimal +// value: whether it is a whole number, and if so whether it lies +// inside the JavaScript safe-integer range. +func exactInteger(s string) (int64, integerVerdict) { + if i, err := strconv.ParseInt(s, 10, 64); err == nil { + if i > maxSafeInt || i < -maxSafeInt { + return 0, integerOutOfRange + } + return i, integerOK + } + r, ok := boundedRat(s) + if !ok { + // boundedRat refuses only absurd exponents, and there the + // exponent's sign decides: a positive one makes any nonzero + // mantissa an out-of-range integer, a negative one a nonzero + // fraction below 1. + if j := strings.IndexAny(s, "eE"); j >= 0 && strings.HasPrefix(s[j+1:], "-") { + return 0, integerNotWhole + } + return 0, integerOutOfRange + } + if !r.IsInt() { + return 0, integerNotWhole + } + n := r.Num() + if !n.IsInt64() || n.Int64() > maxSafeInt || n.Int64() < -maxSafeInt { + return 0, integerOutOfRange + } + return n.Int64(), integerOK +} + +// exactNumber parses a strict JSON number literal into its exact +// rational value, for Check's numeric comparison. A header string is +// sender-controlled, so the JSON grammar is enforced first — +// big.Rat.SetString alone would also accept "3/2" and friends. +func exactNumber(s string) (*big.Rat, bool) { + dec := json.NewDecoder(strings.NewReader(s)) + dec.UseNumber() + var n json.Number + if err := dec.Decode(&n); err != nil || dec.More() { + return nil, false + } + return boundedRat(n.String()) +} + +// boundedRat is big.Rat.SetString with an exponent bound: without +// one, a literal like 1e999999999 would make SetString try to +// materialise a billion-digit number. An all-zero mantissa is +// exactly zero at any exponent, so it is answered directly; any +// other refusal is left to the caller to interpret. +func boundedRat(s string) (*big.Rat, bool) { + if j := strings.IndexAny(s, "eE"); j >= 0 { + if e, err := strconv.Atoi(s[j+1:]); err != nil || e > 512 || e < -512 { + if strings.Trim(s[:j], "-0.") == "" { + return new(big.Rat), true + } + return nil, false + } + } + return new(big.Rat).SetString(s) +} + // maxSafeInt is 2^53-1, JavaScript's Number.MAX_SAFE_INTEGER. const maxSafeInt = int64(1)<<53 - 1 diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go index 95673ca5fa..58454f6208 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go @@ -48,3 +48,57 @@ func TestCheckIntegerComparesNumericallyBothWays(t *testing.T) { } } } + +// TestCheckIntegerPrecisionPermutations pins the Codex finding on +// PR 2955: integrality must be judged on the exact decimal value, not +// on a float64 round-trip -- 9007199254740990.5 rounds to an integer +// in float64, and 1e-400 underflows to 0. +func TestCheckIntegerPrecisionPermutations(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + header := func(v string) func(string) (string, bool) { + return func(string) (string, bool) { return v, true } + } + accepted := []struct{ args, hdr string }{ + {`{"n": 9007199254740990.0}`, "9007199254740990"}, + {`{"n": 9007199254740991.0}`, "9007199254740991"}, + {`{"n": 0.5e1}`, "5"}, + {`{"n": 42}`, "4.2e1"}, + } + for _, c := range accepted { + if err := Check(params, json.RawMessage(c.args), header(c.hdr)); err != nil { + t.Errorf("Check(%s, header %q) = %v, want nil", c.args, c.hdr, err) + } + } + rejected := []struct { + args, hdr, want string + }{ + {`{"n": 9007199254740990.5}`, "9007199254740990", "is not an integer"}, + {`{"n": -9007199254740990.5}`, "-9007199254740990", "is not an integer"}, + {`{"n": 1e-400}`, "0", "is not an integer"}, + {`{"n": 5e-1}`, "0", "is not an integer"}, + {`{"n": 9007199254740990}`, "9007199254740990.5", "does not match"}, + {`{"n": 9007199254740992.0}`, "9007199254740992", "outside the JavaScript safe-integer range"}, + {`{"n": 1e999999}`, "1", "outside the JavaScript safe-integer range"}, + } + for _, c := range rejected { + err := Check(params, json.RawMessage(c.args), header(c.hdr)) + if err == nil { + t.Errorf("Check(%s, header %q) = nil, want error containing %q", c.args, c.hdr, c.want) + } else if !strings.Contains(err.Error(), c.want) { + t.Errorf("Check(%s, header %q) = %v, want error containing %q", c.args, c.hdr, err, c.want) + } + } + // Values shares plain(): a value mcpx sends is a value mcpx + // accepts, and a non-integer is refused on the send side too. + if _, err := Values(params, map[string]any{"n": json.Number("9007199254740990.5")}); err == nil || + !strings.Contains(err.Error(), "is not an integer") { + t.Errorf("Values(9007199254740990.5) = %v, want 'is not an integer'", err) + } + got, err := Values(params, map[string]any{"n": json.Number("42.0")}) + if err != nil { + t.Fatalf("Values(42.0) = %v, want nil", err) + } + if got[ParamPrefix+"n"] != "42" { + t.Errorf("Values(42.0) header = %q, want %q", got[ParamPrefix+"n"], "42") + } +} From 21aa2cb1692dfcb35fdee9b05e6b5990db86184c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 02:29:46 -0500 Subject: [PATCH 3/4] fix(mcpx): strict whole-literal numeric parsing in mcpheaders (Codex P2 x3 on #2955) All three Codex findings were in the exact-number helpers: (1) exactNumber decoded into json.Number, which also accepts a JSON string and stops before trailing junk, so headers like "42", 42] and 42} passed as the number 42 -- parseDecimal now validates the whole string against the JSON number grammar. (2) boundedRat refused raw exponents past 512 before judging the mantissa, so 1000...0e-513 (exactly 1) was rejected -- the literal is now normalised first (leading/trailing zeros folded into the scale) and bounds apply to the normalised digits and effective scale. (3) Literals without an exponent carried unbounded digits into big.Rat -- significant digits and effective scale are now bounded (4096) before any big arithmetic; beyond the bound, exactInteger classifies on the normalised scale (fraction vs out-of-range integer) without materialising the value. Tests: TestCheckRejectsNonNumberHeaders, TestCheckExponentCancellingMantissa, TestCheckHugeIntegerLiteralBounded. go test ./internal/mcpheaders/ ./internal/mcpserver/ -count=1 passes on the laptop. --- pkgs/mcpx/internal/mcpheaders/mcpheaders.go | 192 +++++++++++++++--- .../internal/mcpheaders/mcpheaders_test.go | 47 +++++ 2 files changed, 210 insertions(+), 29 deletions(-) diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go index 1e106487d3..4d946e3653 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go @@ -332,56 +332,190 @@ func exactInteger(s string) (int64, integerVerdict) { } return i, integerOK } - r, ok := boundedRat(s) + d, ok := parseDecimal(s) + if d.digits == "" { + // Zero in any form (-0.0, 0e5), or no literal at all; the + // ParseInt path above already took plain "0", so this is the + // float/exponent spellings of zero. + if ok { + return 0, integerOK + } + return 0, integerNotWhole + } if !ok { - // boundedRat refuses only absurd exponents, and there the - // exponent's sign decides: a positive one makes any nonzero - // mantissa an out-of-range integer, a negative one a nonzero - // fraction below 1. - if j := strings.IndexAny(s, "eE"); j >= 0 && strings.HasPrefix(s[j+1:], "-") { + // Grammar was valid but the literal is beyond the processing + // bounds (thousands of significant digits or an enormous + // effective scale). After normalisation scale < 0 means the + // last significant digit sits below the units place, so the + // value is a nonzero fraction; scale >= 0 makes it an integer + // with thousands of digits, far outside the safe range. + if d.scale < 0 { return 0, integerNotWhole } return 0, integerOutOfRange } - if !r.IsInt() { + if d.scale < 0 { return 0, integerNotWhole } - n := r.Num() - if !n.IsInt64() || n.Int64() > maxSafeInt || n.Int64() < -maxSafeInt { + // Whole: the integer has len(digits)+scale digits. More than 16 + // cannot fit the safe range (which tops out at 9007199254740991). + if len(d.digits)+d.scale > 16 { + return 0, integerOutOfRange + } + v, err := strconv.ParseInt(d.digits+strings.Repeat("0", d.scale), 10, 64) + if err != nil { + return 0, integerOutOfRange + } + if d.neg { + v = -v + } + if v > maxSafeInt || v < -maxSafeInt { return 0, integerOutOfRange } - return n.Int64(), integerOK + return v, integerOK } // exactNumber parses a strict JSON number literal into its exact // rational value, for Check's numeric comparison. A header string is -// sender-controlled, so the JSON grammar is enforced first — -// big.Rat.SetString alone would also accept "3/2" and friends. +// sender-controlled, so the whole string must be the literal -- +// quoted strings, trailing brackets and other junk are not numbers +// (Codex review on PR 2955). func exactNumber(s string) (*big.Rat, bool) { - dec := json.NewDecoder(strings.NewReader(s)) - dec.UseNumber() - var n json.Number - if err := dec.Decode(&n); err != nil || dec.More() { + d, ok := parseDecimal(s) + if !ok { return nil, false } - return boundedRat(n.String()) + if d.digits == "" { + return new(big.Rat), true + } + num, _ := new(big.Int).SetString(d.digits, 10) + r := new(big.Rat).SetInt(num) + if d.scale != 0 { + n := d.scale + if n < 0 { + n = -n + } + pow := new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(n)), nil)) + if d.scale > 0 { + r.Mul(r, pow) + } else { + r.Quo(r, pow) + } + } + if d.neg { + r.Neg(r) + } + return r, true } -// boundedRat is big.Rat.SetString with an exponent bound: without -// one, a literal like 1e999999999 would make SetString try to -// materialise a billion-digit number. An all-zero mantissa is -// exactly zero at any exponent, so it is answered directly; any -// other refusal is left to the caller to interpret. -func boundedRat(s string) (*big.Rat, bool) { - if j := strings.IndexAny(s, "eE"); j >= 0 { - if e, err := strconv.Atoi(s[j+1:]); err != nil || e > 512 || e < -512 { - if strings.Trim(s[:j], "-0.") == "" { - return new(big.Rat), true +// maxDecimalDigits bounds the significant digits (and the effective +// scale) one literal may carry into exact arithmetic. Without it, a +// sender-supplied literal with a million digits -- or an exponent +// that only cancels after materialising one -- would make the exact +// comparison allocate in proportion to the attacker's text, or +// worse, to their exponent (Codex review on PR 2955). +const maxDecimalDigits = 4096 + +// decimal is a JSON number literal in normalised form: +// +// value = (neg ? -1 : 1) * digits * 10^scale +// +// digits carries no leading or trailing zeros, so scale < 0 exactly +// when the value is a nonzero fraction. digits == "" is exactly zero, +// at any exponent. Normalising BEFORE any bound is applied is what +// lets 1000...0e-513 (514-digit mantissa, exponent -513) be judged +// as the small integer it is, instead of being refused for its raw +// exponent. +type decimal struct { + neg bool + digits string + scale int +} + +// parseDecimal validates s as one strict JSON number literal -- the +// whole string, JSON grammar: -?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)? +// -- and normalises it. ok is false when the grammar fails, or when +// the normalised literal exceeds maxDecimalDigits; in the bounds +// case the returned decimal still describes the literal (with the +// exponent clamped) so callers can classify it. +func parseDecimal(s string) (decimal, bool) { + i := 0 + neg := false + if i < len(s) && s[i] == '-' { + neg = true + i++ + } + if i >= len(s) { + return decimal{}, false + } + intStart := i + if s[i] == '0' { + i++ + } else if s[i] >= '1' && s[i] <= '9' { + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + } else { + return decimal{}, false + } + intPart := s[intStart:i] + fracPart := "" + if i < len(s) && s[i] == '.' { + i++ + fs := i + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + if i == fs { + return decimal{}, false + } + fracPart = s[fs:i] + } + exp := 0 + if i < len(s) && (s[i] == 'e' || s[i] == 'E') { + i++ + sign := 1 + if i < len(s) && (s[i] == '+' || s[i] == '-') { + if s[i] == '-' { + sign = -1 } - return nil, false + i++ + } + es := i + for i < len(s) && s[i] >= '0' && s[i] <= '9' { + i++ + } + if i == es { + return decimal{}, false } + // The exponent text itself is attacker-controlled length; + // anything past six significant digits is clamped to a + // sentinel far beyond the processing bounds. + et := strings.TrimLeft(s[es:i], "0") + if len(et) > 6 { + exp = sign * (maxDecimalDigits * 1000) + } else if et != "" { + e, _ := strconv.Atoi(et) + exp = sign * e + } + } + if i != len(s) { + return decimal{}, false + } + digits := intPart + fracPart + scale := exp - len(fracPart) + digits = strings.TrimLeft(digits, "0") + trimmed := strings.TrimRight(digits, "0") + scale += len(digits) - len(trimmed) + digits = trimmed + if digits == "" { + return decimal{}, true + } + d := decimal{neg: neg, digits: digits, scale: scale} + if len(digits) > maxDecimalDigits || scale > maxDecimalDigits || scale < -maxDecimalDigits { + return d, false } - return new(big.Rat).SetString(s) + return d, true } // maxSafeInt is 2^53-1, JavaScript's Number.MAX_SAFE_INTEGER. diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go index 58454f6208..3242ee0940 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go @@ -102,3 +102,50 @@ func TestCheckIntegerPrecisionPermutations(t *testing.T) { t.Errorf("Values(42.0) header = %q, want %q", got[ParamPrefix+"n"], "42") } } + +// TestCheckRejectsNonNumberHeaders pins the Codex findings on +// PR 2955: the numeric fallback must validate the ENTIRE header as a +// JSON number literal. A quoted string, or a number with trailing +// junk, is not the same numeric value. +func TestCheckRejectsNonNumberHeaders(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + for _, hdr := range []string{`"42"`, "42]", "42}", "42 ", " 42", "4/2", "0x2A", "42e", "042", "+42", ".42", ""} { + h := func(string) (string, bool) { return hdr, true } + if err := Check(params, json.RawMessage(`{"n": 42}`), h); err == nil { + t.Errorf("Check(header %q) = nil, want a mismatch error", hdr) + } + } +} + +// TestCheckExponentCancellingMantissa pins the second Codex finding: +// the exponent bound applies AFTER the mantissa is normalised, so a +// literal whose zeros cancel its exponent is judged on its value. +func TestCheckExponentCancellingMantissa(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + for _, hdr := range []string{ + "1" + strings.Repeat("0", 513) + "e-513", + "0." + strings.Repeat("0", 512) + "1e513", + } { + h := func(string) (string, bool) { return hdr, true } + if err := Check(params, json.RawMessage(`{"n": 1}`), h); err != nil { + t.Errorf("Check(header %.20q...) = %v, want nil", hdr, err) + } + } +} + +// TestCheckHugeIntegerLiteralBounded pins the third Codex finding: a +// huge integer literal with no exponent is classified out-of-range +// without materialising it in arbitrary precision. +func TestCheckHugeIntegerLiteralBounded(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + h := func(string) (string, bool) { return "1", true } + for _, body := range []string{ + `{"n": ` + strings.Repeat("9", 5000) + `}`, + `{"n": ` + strings.Repeat("9", 5000) + `.0}`, + } { + err := Check(params, json.RawMessage(body), h) + if err == nil || !strings.Contains(err.Error(), "outside the JavaScript safe-integer range") { + t.Errorf("Check(huge body) = %v, want safe-range error", err) + } + } +} From 230cda2c68e87d2c4f39d83271ec0dd0d9ea2345 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 02:56:09 -0500 Subject: [PATCH 4/4] fix(mcpx): preserve exponent overflow through mantissa normalisation (#1665) --- pkgs/mcpx/internal/mcpheaders/mcpheaders.go | 30 ++++++++++++++----- .../internal/mcpheaders/mcpheaders_test.go | 30 +++++++++++++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go index 4d946e3653..7875a86ba6 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders.go @@ -488,15 +488,29 @@ func parseDecimal(s string) (decimal, bool) { if i == es { return decimal{}, false } - // The exponent text itself is attacker-controlled length; - // anything past six significant digits is clamped to a - // sentinel far beyond the processing bounds. + // The exponent text itself is attacker-controlled length, + // so it is parsed exactly only up to a saturation bound -- + // and the bound is tied to the input length, not fixed. + // Mantissa normalisation can shift the scale by at most + // len(s) (every input byte is at most one mantissa digit + // or cancelling zero), so an exponent beyond + // len(s)+maxDecimalDigits can never be cancelled back + // into the processing bounds, while every exponent up to + // it keeps its exact value and classification (Codex + // review on PR 2955: a fixed sentinel of 4096000 was + // exactly cancelled by a mantissa carrying that many + // zeros, resurrecting 10^3096000 -- and a tiny fraction + // -- as the integer 1). et := strings.TrimLeft(s[es:i], "0") - if len(et) > 6 { - exp = sign * (maxDecimalDigits * 1000) - } else if et != "" { - e, _ := strconv.Atoi(et) - exp = sign * e + if et != "" { + sat := len(s) + maxDecimalDigits + 1 + if len(et) > 9 { + exp = sign * sat + } else if e, _ := strconv.Atoi(et); e > sat { + exp = sign * sat + } else { + exp = sign * e + } } } if i != len(s) { diff --git a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go index 3242ee0940..0f6793f48b 100644 --- a/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go +++ b/pkgs/mcpx/internal/mcpheaders/mcpheaders_test.go @@ -149,3 +149,33 @@ func TestCheckHugeIntegerLiteralBounded(t *testing.T) { } } } + +// TestCheckExponentOverflowNotCancellable pins the fourth Codex +// finding on PR 2955: the exponent clamp must not be a fixed sentinel +// a long mantissa can cancel. "1" followed by 4,096,000 zeros with +// e-1000000 is 10^3096000 (far outside the safe range), not 1; the +// fractional permutation is a tiny nonzero fraction, not 1. +func TestCheckExponentOverflowNotCancellable(t *testing.T) { + params := []Param{{Name: "n", Path: []string{"n"}}} + h1 := func(string) (string, bool) { return "1", true } + hugeInt := `{"n": 1` + strings.Repeat("0", 4096000) + `e-1000000}` + err := Check(params, json.RawMessage(hugeInt), h1) + if err == nil || !strings.Contains(err.Error(), "outside the JavaScript safe-integer range") { + t.Errorf("Check(1<4096000 zeros>e-1000000, header 1) = %v, want safe-range error", err) + } + tinyFrac := `{"n": 0.` + strings.Repeat("0", 4095999) + `1e1000000}` + err = Check(params, json.RawMessage(tinyFrac), h1) + if err == nil || !strings.Contains(err.Error(), "is not an integer") { + t.Errorf("Check(0.<4095999 zeros>1e1000000, header 1) = %v, want not-an-integer error", err) + } + // The same literals in the header must not compare equal to 1 either. + for _, hdr := range []string{ + "1" + strings.Repeat("0", 4096000) + "e-1000000", + "0." + strings.Repeat("0", 4095999) + "1e1000000", + } { + h := func(string) (string, bool) { return hdr, true } + if err := Check(params, json.RawMessage(`{"n": 1}`), h); err == nil { + t.Errorf("Check(body 1, header %.20q...) = nil, want a mismatch error", hdr) + } + } +}