Fix JSON Unicode decoding and YAML float validation

This commit is contained in:
2026-11-28 23:25:12 +00:00
parent 9cc9f6f777
commit 9f7744bda8
4 changed files with 128 additions and 4 deletions

View File

@@ -3,17 +3,29 @@
package validation
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"go.yaml.in/yaml/v4"
)
// Decode uses go-yaml's parser and scalar resolution, adapting its node graph to
// the documented JSON data model. Numbers retain their precision as json.Number.
// Decode uses the standard JSON decoder for JSON syntax and go-yaml otherwise,
// adapting both to the documented data model without losing number precision.
func Decode(data []byte) (any, error) {
if json.Valid(data) {
d := json.NewDecoder(bytes.NewReader(data))
d.UseNumber()
value, err := jsonValue(d, "")
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return value, nil
}
var document yaml.Node
if err := yaml.Load(data, &document, yaml.WithUniqueKeys()); err != nil {
return nil, fmt.Errorf("decode: %w", err)
@@ -26,6 +38,50 @@ func Decode(data []byte) (any, error) {
return value, nil
}
// jsonValue consumes library-decoded tokens so duplicate keys, including keys
// with equivalent escape spellings, cannot be lost in a map unmarshalling step.
// Decode has already checked that the input is one syntactically valid value.
func jsonValue(d *json.Decoder, path string) (any, error) {
token, err := d.Token()
if err != nil {
return nil, err
}
switch token {
case json.Delim('{'):
value := make(map[string]any)
for d.More() {
token, err := d.Token()
if err != nil {
return nil, err
}
key := token.(string) // Valid JSON objects have string keys.
childPath := path + "/" + escape(key)
if _, exists := value[key]; exists {
return nil, fmt.Errorf("%s (byte %d): duplicate mapping key %q", pointer(childPath), d.InputOffset(), key)
}
value[key], err = jsonValue(d, childPath)
if err != nil {
return nil, err
}
}
_, err = d.Token() // Closing brace.
return value, err
case json.Delim('['):
value := make([]any, 0)
for d.More() {
child, err := jsonValue(d, fmt.Sprintf("%s/%d", path, len(value)))
if err != nil {
return nil, err
}
value = append(value, child)
}
_, err = d.Token() // Closing bracket.
return value, err
default:
return token, nil
}
}
type decoder struct {
active map[*yaml.Node]bool
values map[*yaml.Node]any
@@ -136,6 +192,11 @@ func scalar(n *yaml.Node) (any, error) {
// Normalize YAML's leading '+', '.5', and '5.' spellings, retaining the
// decimal digits instead of converting through float64.
text := strings.TrimPrefix(strings.ReplaceAll(n.Value, "_", ""), "+")
// Check syntax before supplying missing zeroes. Range errors are allowed:
// the exact decimal representation need not fit in a machine float.
if _, err := strconv.ParseFloat(text, 64); err != nil && !errors.Is(err, strconv.ErrRange) {
return nil, fmt.Errorf("invalid float %q: %w", n.Value, err)
}
mantissa, exponent, hasExponent := strings.Cut(strings.ToLower(text), "e")
sign := ""
if strings.HasPrefix(mantissa, "-") {

View File

@@ -142,6 +142,7 @@ func TestDecodeProfile(t *testing.T) {
"a: !custom value", "a: !!binary Zm9v", "a: !!set {x: null}", "a: !!omap [{x: 1}]",
"a: &cycle [*cycle]", "a: *unknown", "a: .inf", "a: -.Inf", "a: .NaN",
"a: !!float true", "a: !!int false", "a: [broken", "a: &x {b: 1}\nc: {<<: *x}",
`a: !!float ""`, "a: !!float e3", "a: !!float +", "a: !!float .",
} {
t.Run(input, func(t *testing.T) {
if _, err := Decode([]byte(input)); err == nil || !strings.HasPrefix(err.Error(), "decode:") {
@@ -177,12 +178,42 @@ copy: *items
}
}
func TestJSONDecoding(t *testing.T) {
value, err := Decode([]byte(`{"schema_version":"maximumdirect.campaign.v1","id":"weather","name":"Weather \ud83c\udf27","observations":[{"amount":0.123456789012345678901,"scale":1e500,"available":true,"missing":null}]}`))
if err != nil {
t.Fatal(err)
}
want := map[string]any{
"schema_version": "maximumdirect.campaign.v1", "id": "weather", "name": "Weather 🌧",
"observations": []any{map[string]any{
"amount": json.Number("0.123456789012345678901"), "scale": json.Number("1e500"),
"available": true, "missing": nil,
}},
}
if !reflect.DeepEqual(value, want) {
t.Fatalf("JSON decoding changed data: got %#v, want %#v", value, want)
}
if err := loadSet(t).Validate(value); err != nil {
t.Fatal(err)
}
for _, input := range []string{
`{"a":1,"\u0061":2}`,
`{"observations":[{"value":1,"value":2}]}`,
`{"\ud83c\udf27":1,"🌧":2}`,
} {
if _, err := Decode([]byte(input)); err == nil || !strings.Contains(err.Error(), "duplicate mapping key") {
t.Fatalf("expected duplicate-key failure for %s, got %v", input, err)
}
}
}
func TestNumericPrecision(t *testing.T) {
for input, want := range map[string]string{
"1234567890123456789012345678901234567890": "1234567890123456789012345678901234567890",
"0.123456789012345678901234567890": "0.123456789012345678901234567890",
".5": "0.5", "5.": "5.0", "+.5": "0.5", "-0.5": "-0.5", "1e500": "1e500",
"0x10": "16", "0o10": "8", "0b10": "2", "010": "8", "1_000": "1000",
`!!float "0"`: "0", "!!float .5": "0.5", "!!float 5.": "5.0", "!!float 1e500": "1e500",
} {
t.Run(input, func(t *testing.T) {
value, err := Decode([]byte("measurement: " + input))