diff --git a/cmd/validate/main_test.go b/cmd/validate/main_test.go index c9fbc7b..9b3f358 100644 --- a/cmd/validate/main_test.go +++ b/cmd/validate/main_test.go @@ -46,3 +46,31 @@ func TestJSONSyntax(t *testing.T) { t.Fatalf("expected JSON syntax failure, got %q", &stderr) } } + +func TestDocumentDecoding(t *testing.T) { + for _, test := range []struct { + file string + body string + code int + }{ + {"escaped.json", `{"schema_version":"maximumdirect.campaign.v1","id":"weather","name":"Weather \ud83c\udf27"}`, 0}, + {"malformed-float.yml", "schema_version: maximumdirect.campaign.v1\nid: weather\nreading: !!float e3\n", 1}, + } { + t.Run(test.file, func(t *testing.T) { + file := filepath.Join(t.TempDir(), test.file) + if err := os.WriteFile(file, []byte(test.body), 0600); err != nil { + t.Fatal(err) + } + var stdout, stderr bytes.Buffer + if code := run([]string{"-root", "../..", file}, &stdout, &stderr); code != test.code { + t.Fatalf("want exit %d, got %d: stdout=%q stderr=%q", test.code, code, &stdout, &stderr) + } + if test.code == 0 && !strings.Contains(stdout.String(), "valid (maximumdirect.campaign.v1)") { + t.Fatalf("missing success report: %q", &stdout) + } + if test.code != 0 && !strings.Contains(stderr.String(), "decode:") { + t.Fatalf("missing decoding failure: %q", &stderr) + } + }) + } +} diff --git a/docs/validation.md b/docs/validation.md index cd88a44..6d8624b 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -31,8 +31,10 @@ errors include field paths and source positions where the YAML library or node profile provides them. Structural errors include JSON instance locations. Semantic duplicate-ID errors identify the collection and entry index. -The harness uses [go-yaml v4](https://github.com/yaml/go-yaml/tree/v4.0.0) for -parsing and [jsonschema v6](https://github.com/santhosh-tekuri/jsonschema/tree/v6.0.3) +The harness uses Go's standard JSON decoder for JSON syntax, including Unicode +surrogate-pair escapes, and [go-yaml v4](https://github.com/yaml/go-yaml/tree/v4.0.0) +otherwise. Both paths reject duplicate keys and preserve number precision. It uses +[jsonschema v6](https://github.com/santhosh-tekuri/jsonschema/tree/v6.0.3) for Draft 2020-12 validation. It performs glossary ID uniqueness after structural validation. It does not resolve domain references, check resource installation, infer consumer support, populate defaults, or rewrite files. @@ -60,6 +62,8 @@ must use JSON syntax. The same duplicate-key and semantic rules apply to both. additionally recognized beyond machine numeric range. The adapter preserves decimal precision as JSON numbers rather than converting through machine floating point. NaN and infinities are errors. + Explicitly tagged floats must have valid numeric syntax before normalization; + empty values or incomplete forms such as `!!float e3` are errors. - Anchors and aliases are accepted and resolved to values. Cycles are errors. Anchors, aliases, comments, and formatting are serialization details. - Standard mapping, sequence, string, integer, float, boolean, null, and diff --git a/internal/validation/decode.go b/internal/validation/decode.go index 38c66fc..2b400a0 100644 --- a/internal/validation/decode.go +++ b/internal/validation/decode.go @@ -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, "-") { diff --git a/internal/validation/validation_test.go b/internal/validation/validation_test.go index b9e59a7..d5e9591 100644 --- a/internal/validation/validation_test.go +++ b/internal/validation/validation_test.go @@ -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))