diff --git a/cmd/kosli/attestCustom.go b/cmd/kosli/attestCustom.go index d4721480c..e7b4b074c 100644 --- a/cmd/kosli/attestCustom.go +++ b/cmd/kosli/attestCustom.go @@ -26,7 +26,8 @@ const attestCustomLongDesc = attestCustomShortDesc + ` The name of the custom attestation type is specified using the ^--type^ flag. The path to the JSON or YAML file the custom type will evaluate is specified using the ^--attestation-data^ flag. A ^.yaml^ or ^.yml^ file is converted to JSON before it is sent: dates and timestamps stay strings exactly as written, -^yes^, ^no^, ^on^ and ^off^ stay strings, and aliases and merge keys are resolved. Duplicate keys are an error. +^yes^, ^no^, ^on^ and ^off^ stay strings, decimal numbers keep every digit, and aliases and merge keys are resolved. +Duplicate keys are an error. A YAML file with several documents needs ^--attestation-data-as-list^, which sends the documents as a JSON list. ` + attestationBindingDesc + ` diff --git a/cmd/kosli/attestationData_test.go b/cmd/kosli/attestationData_test.go index d5100b4eb..447430cd7 100644 --- a/cmd/kosli/attestationData_test.go +++ b/cmd/kosli/attestationData_test.go @@ -32,6 +32,12 @@ func TestLoadAttestationData(t *testing.T) { content: "name: Jane\nborn: 1990-05-17\n", wantJSON: `{"born":"1990-05-17","name":"Jane"}`, }, + { + name: "YAML numbers beyond float64 precision are sent exactly", + filename: "data.yaml", + content: "i: 123456789012345678901234567890\nf: 0.12345678901234567890\n", + wantJSON: `{"f":0.12345678901234567890,"i":123456789012345678901234567890}`, + }, { name: "a .yml file is YAML too", filename: "data.yml", @@ -56,6 +62,12 @@ func TestLoadAttestationData(t *testing.T) { content: `[1, 2]`, wantJSON: `[1,2]`, }, + { + name: "a JSON integer beyond 2^53 is sent exactly as written", + filename: "data.json", + content: `{"i": 12345678901234567890}`, + wantJSON: `{"i":12345678901234567890}`, + }, { name: "YAML in a file without a YAML extension is not converted", filename: "data.txt", diff --git a/cmd/kosli/cli_utils.go b/cmd/kosli/cli_utils.go index f9566d247..ddaf18375 100644 --- a/cmd/kosli/cli_utils.go +++ b/cmd/kosli/cli_utils.go @@ -449,8 +449,11 @@ func LoadJsonData(filepath string) (any, error) { } logger.Debug("loaded user data file content from: %s", filepath) } - err = json.Unmarshal([]byte(content), &result) - if err != nil { + // A float64 holds integers exactly only up to 2^53, so numbers stay as + // json.Number and are marshalled back as written. + decoder := json.NewDecoder(strings.NewReader(content)) + decoder.UseNumber() + if err := decoder.Decode(&result); err != nil { return result, err } return result, nil diff --git a/cmd/kosli/cli_utils_test.go b/cmd/kosli/cli_utils_test.go index 742d8849c..a5674924a 100644 --- a/cmd/kosli/cli_utils_test.go +++ b/cmd/kosli/cli_utils_test.go @@ -569,6 +569,52 @@ func (suite *CliUtilsTestSuite) TestLoadUserData() { } } +func (suite *CliUtilsTestSuite) TestLoadJsonDataKeepsNumbersAsWritten() { + for _, t := range []struct { + name string + content string + want string + }{ + { + name: "an integer beyond 2^53", + content: `{"i": 12345678901234567890}`, + want: `{"i":12345678901234567890}`, + }, + { + name: "a negative integer beyond 2^53 nested in a list", + content: `[{"i": [-9007199254740993]}]`, + want: `[{"i":[-9007199254740993]}]`, + }, + { + name: "a decimal with more digits than a float64 holds", + content: `{"f": 0.12345678901234567890}`, + want: `{"f":0.12345678901234567890}`, + }, + { + name: "a decimal with a trailing zero", + content: `{"f": 1.0}`, + want: `{"f":1.0}`, + }, + { + name: "an exponent", + content: `{"e": 1e2}`, + want: `{"e":1e2}`, + }, + } { + suite.Run(t.name, func() { + path := filepath.Join(suite.T().TempDir(), "data.json") + require.NoError(suite.T(), os.WriteFile(path, []byte(t.content), 0o600)) + + data, err := LoadJsonData(path) + require.NoError(suite.T(), err) + + got, err := json.Marshal(data) + require.NoError(suite.T(), err) + require.Equal(suite.T(), t.want, string(got)) + }) + } +} + // No filepath means the caller has nothing to send. Returning nil is what lets // omitempty keep the key out of the payload, so the CLI behaves like an API // client that omits the field rather than one that sends an empty object. diff --git a/internal/utils/yaml.go b/internal/utils/yaml.go index a60087665..a16f93362 100644 --- a/internal/utils/yaml.go +++ b/internal/utils/yaml.go @@ -2,6 +2,8 @@ package utils import ( "bytes" + "crypto/rand" + "encoding/json" "errors" "fmt" "io" @@ -20,7 +22,10 @@ const ( yamlMergeTag = "!!merge" ) -var yamlIntegerLiteral = regexp.MustCompile(`^[-+]?[0-9]+$`) +var ( + yamlIntegerLiteral = regexp.MustCompile(`^[-+]?[0-9]+$`) + yamlDecimalLiteral = regexp.MustCompile(`^([-+]?)([0-9]*)(?:\.([0-9]*))?([eE][-+]?[0-9]+)?$`) +) // YAMLDocuments converts a YAML stream into one JSON-encodable value per // document, in stream order. Empty and null documents are dropped, so the @@ -29,12 +34,16 @@ var yamlIntegerLiteral = regexp.MustCompile(`^[-+]?[0-9]+$`) // Scalars follow the YAML 1.2 core schema, with one exception inherited from // yaml.v3: an integer with a leading zero is octal. Dates and timestamps stay // strings exactly as written, and scalar mapping keys become strings exactly -// as written. Duplicate keys, non-scalar keys, and numbers that JSON cannot -// carry exactly (decimal integers beyond 64 bits, infinities, NaN) are -// errors. Hex, octal and binary integers beyond 64 bits, and floats beyond -// float64, are strings exactly as written. +// as written. Decimal numbers within float64's range keep every digit, as +// a json.Number in JSON's spelling: 1.10 stays 1.10, +.5 becomes 0.5, and +// 01.50 becomes 1.50. A leading zero is dropped only where a decimal point +// or an exponent rules out octal: 089 is an error. Duplicate keys, +// non-scalar keys, and numbers that JSON cannot carry (infinities, NaN) are +// errors. Hex, octal and binary integers beyond 64 bits, and decimal +// numbers beyond float64's range, are strings exactly as written. func YAMLDocuments(content []byte) ([]any, error) { documents := []any{} + numbers := yamlNumbers{marker: "\x00" + rand.Text() + ":", written: map[*yaml.Node]string{}} decoder := yaml.NewDecoder(bytes.NewReader(content)) for position := 1; ; position++ { var document yaml.Node @@ -48,14 +57,14 @@ func YAMLDocuments(content []byte) ([]any, error) { if isNullYAMLDocument(&document) { continue } - if err := prepareYAMLNode(&document); err != nil { + if err := numbers.prepareNode(&document); err != nil { return nil, inYAMLDocument(position, err) } var value any if err := document.Decode(&value); err != nil { return nil, inYAMLDocument(position, err) } - documents = append(documents, value) + documents = append(documents, numbers.restore(value)) } } @@ -74,28 +83,39 @@ func isNullYAMLDocument(document *yaml.Node) bool { return root.Kind == yaml.ScalarNode && root.ShortTag() == yamlNullTag } -// prepareYAMLNode rewrites the tree so that decoding it into any gives a +// yamlNumbers carries decimal numbers through yaml.v3, which decodes a +// number only to an int64, a uint64 or a float64. A number node becomes a +// string holding marker and the number, and restore turns such strings +// back into numbers. +type yamlNumbers struct { + // marker is random, so no string in a document starts with it. + marker string + // written holds the original text of each node turned into a string. + written map[*yaml.Node]string +} + +// prepareNode rewrites the tree so that decoding it into any gives a // value encoding/json can marshal without changing what the author wrote. // Alias nodes are not followed: their targets are visited where they are // anchored. -func prepareYAMLNode(node *yaml.Node) error { +func (n yamlNumbers) prepareNode(node *yaml.Node) error { switch node.Kind { case yaml.ScalarNode: - return prepareYAMLScalar(node) + return n.prepareScalar(node) case yaml.MappingNode: for i := 0; i+1 < len(node.Content); i += 2 { - key, err := yamlStringKey(node.Content[i]) + key, err := n.stringKey(node.Content[i]) if err != nil { return err } node.Content[i] = key - if err := prepareYAMLNode(node.Content[i+1]); err != nil { + if err := n.prepareNode(node.Content[i+1]); err != nil { return err } } case yaml.DocumentNode, yaml.SequenceNode: for _, child := range node.Content { - if err := prepareYAMLNode(child); err != nil { + if err := n.prepareNode(child); err != nil { return err } } @@ -103,23 +123,28 @@ func prepareYAMLNode(node *yaml.Node) error { return nil } -func prepareYAMLScalar(node *yaml.Node) error { +func (n yamlNumbers) prepareScalar(node *yaml.Node) error { switch node.ShortTag() { case yamlTimestampTag: // yaml.v3 would decode this to a time.Time, which marshals as a // full RFC 3339 timestamp even when only a date was written. node.Tag = yamlStrTag case yamlFloatTag: - // yaml.v3 resolves a decimal integer it cannot parse as one to a - // float: one that overflows 64 bits, or one with a leading zero - // that is not octal, such as 089. explicitlyTagged := node.Style&yaml.TaggedStyle != 0 literal := strings.ReplaceAll(node.Value, "_", "") - if !explicitlyTagged && yamlIntegerLiteral.MatchString(literal) { - if strings.HasPrefix(strings.TrimLeft(literal, "+-"), "0") { + if !explicitlyTagged { + // yaml.v3 resolves a decimal integer it cannot parse as one + // to a float: one that overflows 64 bits, or one with a + // leading zero that is not octal, such as 089. + if yamlIntegerLiteral.MatchString(literal) && strings.HasPrefix(strings.TrimLeft(literal, "+-"), "0") { return fmt.Errorf("line %d: %s has a leading zero but is not an octal number; quote it to send it as a string", node.Line, node.Value) } - return fmt.Errorf("line %d: integer %s does not fit in 64 bits; quote it to send it as a string", node.Line, node.Value) + if number, ok := jsonNumber(literal); ok { + n.written[node] = node.Value + node.Tag = yamlStrTag + node.Value = n.marker + number + return nil + } } var value float64 if err := node.Decode(&value); err != nil { @@ -132,9 +157,49 @@ func prepareYAMLScalar(node *yaml.Node) error { return nil } -// yamlStringKey returns the node to use as a mapping key in place of key, so +// jsonNumber spells a YAML decimal number the way JSON does, keeping every +// digit. It reports false for a literal that is not a decimal number. +func jsonNumber(literal string) (string, bool) { + parts := yamlDecimalLiteral.FindStringSubmatch(literal) + if parts == nil || parts[2]+parts[3] == "" { + return "", false + } + sign, integer, fraction, exponent := parts[1], strings.TrimLeft(parts[2], "0"), parts[3], parts[4] + if sign == "+" { + sign = "" + } + if integer == "" { + integer = "0" + } + if fraction != "" { + fraction = "." + fraction + } + return sign + integer + fraction + exponent, true +} + +// restore replaces, throughout a decoded value, each string prepareScalar +// made from a number with that number. +func (n yamlNumbers) restore(value any) any { + switch value := value.(type) { + case string: + if number, ok := strings.CutPrefix(value, n.marker); ok { + return json.Number(number) + } + case []any: + for i, item := range value { + value[i] = n.restore(item) + } + case map[string]any: + for key, item := range value { + value[key] = n.restore(item) + } + } + return value +} + +// stringKey returns the node to use as a mapping key in place of key, so // that every mapping decodes to a map[string]any. -func yamlStringKey(key *yaml.Node) (*yaml.Node, error) { +func (n yamlNumbers) stringKey(key *yaml.Node) (*yaml.Node, error) { target := key if key.Kind == yaml.AliasNode { target = key.Alias @@ -145,16 +210,20 @@ func yamlStringKey(key *yaml.Node) (*yaml.Node, error) { if key.Anchor != "" { // An alias elsewhere can use this node as a value, and the walk // reaches it only here. - if err := prepareYAMLScalar(key); err != nil { + if err := n.prepareScalar(key); err != nil { return nil, err } } - switch target.ShortTag() { - case yamlStrTag, yamlMergeTag: - return key, nil + written, isNumber := n.written[target] + if !isNumber { + switch target.ShortTag() { + case yamlStrTag, yamlMergeTag: + return key, nil + } + written = target.Value } // A copy, because an aliased key's target may also be used as a value. - return &yaml.Node{Kind: yaml.ScalarNode, Tag: yamlStrTag, Value: target.Value, Line: key.Line, Column: key.Column}, nil + return &yaml.Node{Kind: yaml.ScalarNode, Tag: yamlStrTag, Value: written, Line: key.Line, Column: key.Column}, nil } func yamlKindName(kind yaml.Kind) string { diff --git a/internal/utils/yaml_test.go b/internal/utils/yaml_test.go index cc32aaedf..884b0b481 100644 --- a/internal/utils/yaml_test.go +++ b/internal/utils/yaml_test.go @@ -2,6 +2,7 @@ package utils import ( "encoding/json" + "strings" "testing" "github.com/stretchr/testify/require" @@ -25,7 +26,19 @@ func TestYAMLDocumentsScalars(t *testing.T) { {`d: 2026-12-01`, `[{"d":"2026-12-01"}]`}, {`t: 2026-12-01T10:00:00Z`, `[{"t":"2026-12-01T10:00:00Z"}]`}, {`t: !!timestamp 2026-12-01`, `[{"t":"2026-12-01"}]`}, - {`v: 1.10`, `[{"v":1.1}]`}, + {`v: 1.10`, `[{"v":1.10}]`}, + {`v: 1.0`, `[{"v":1.0}]`}, + {`v: 1e2`, `[{"v":1e2}]`}, + {`v: 0.12345678901234567890`, `[{"v":0.12345678901234567890}]`}, + {`v: -1.5E-3`, `[{"v":-1.5E-3}]`}, + {`v: +1.50`, `[{"v":1.50}]`}, + {`v: +1.5e+3`, `[{"v":1.5e+3}]`}, + {`v: .50`, `[{"v":0.50}]`}, + {`v: -.5`, `[{"v":-0.5}]`}, + {`v: 1.`, `[{"v":1}]`}, + {`v: 1.e3`, `[{"v":1e3}]`}, + {`v: 01.50`, `[{"v":1.50}]`}, + {`v: 00.5`, `[{"v":0.5}]`}, {`v: "1.10"`, `[{"v":"1.10"}]`}, {`c: NO`, `[{"c":"NO"}]`}, {`e: yes`, `[{"e":"yes"}]`}, @@ -36,9 +49,14 @@ func TestYAMLDocumentsScalars(t *testing.T) { {`n: ~`, `[{"n":null}]`}, {`i: 12345678901234567890`, `[{"i":12345678901234567890}]`}, {`i: -9223372036854775808`, `[{"i":-9223372036854775808}]`}, + {`i: 123456789012345678901234567890`, `[{"i":123456789012345678901234567890}]`}, + {`i: -9223372036854775809`, `[{"i":-9223372036854775809}]`}, + {`i: +123456789012345678901234567890`, `[{"i":123456789012345678901234567890}]`}, + {`i: 123_456_789_012_345_678_901_234_567_890`, `[{"i":123456789012345678901234567890}]`}, {`o: 0123`, `[{"o":83}]`}, {`o: "0123"`, `[{"o":"0123"}]`}, {`f: !!float 5`, `[{"f":5}]`}, + {`f: !!float 1.10`, `[{"f":1.1}]`}, } { t.Run(tc.yaml, func(t *testing.T) { require.Equal(t, tc.json, yamlToJSON(t, tc.yaml)) @@ -61,6 +79,13 @@ func TestYAMLDocumentsStructure(t *testing.T) { {"an anchored number key keeps its type where its alias is a value", "&k 1: x\nb: *k", `[{"1":"x","b":1}]`}, {"a leading-zero key that is not octal is a string as written", "089: x\n.inf: y", `[{".inf":"y","089":"x"}]`}, {"integers in other bases that overflow 64 bits are strings as written", "h: 0x1FFFFFFFFFFFFFFFFFFF\ne: 1e400", `[{"e":"1e400","h":"0x1FFFFFFFFFFFFFFFFFFF"}]`}, + {"a decimal integer beyond float64 is a string as written", "i: 1" + strings.Repeat("0", 400), `[{"i":"1` + strings.Repeat("0", 400) + `"}]`}, + {"an aliased decimal is sent as written", "a: &x 1.10\nb: [*x, *x]", `[{"a":1.10,"b":[1.10,1.10]}]`}, + {"an aliased decimal key is a string as written", "a: &k +1.10\n*k : b", `[{"+1.10":"b","a":1.10}]`}, + {"an anchored decimal key stays as written where its alias is a value", "&k +1.10: x\nb: *k", `[{"+1.10":"x","b":1.10}]`}, + {"a merged decimal is sent as written", "base: &b {x: 1.10}\nc:\n <<: *b", `[{"base":{"x":1.10},"c":{"x":1.10}}]`}, + {"decimals keep their form in every document", "1.10\n---\n- 2.0", `[1.10,[2.0]]`}, + {"a string that looks like a number stays a string", `["1.10", '2.0', !!str 3.0]`, `[["1.10","2.0","3.0"]]`}, {"nested keys become strings", "a:\n - 1: x", `[{"a":[{"1":"x"}]}]`}, {"a top-level list is one document", "- a\n- b", `[["a","b"]]`}, {"a top-level scalar is one document", "hello", `["hello"]`}, @@ -94,8 +119,6 @@ func TestYAMLDocumentsErrors(t *testing.T) { {"a list as a key", "[a, b]: c", "line 1: a mapping key must be a scalar, found a sequence"}, {"a mapping as a key", "x:\n {a: b}: c", "line 2: a mapping key must be a scalar, found a mapping"}, {"an alias to a list as a key", "a: &k [1]\n*k : b", "line 2: a mapping key must be a scalar, found a sequence"}, - {"an integer beyond uint64", "i: 123456789012345678901234567890", "line 1: integer 123456789012345678901234567890 does not fit in 64 bits; quote it to send it as a string"}, - {"a negative integer beyond int64", "i: -9223372036854775809", "line 1: integer -9223372036854775809 does not fit in 64 bits; quote it to send it as a string"}, {"a leading-zero number that is not octal", "o: 089", "line 1: 089 has a leading zero but is not an octal number; quote it to send it as a string"}, {"a negative leading-zero number that is not octal", "o: -01890", "line 1: -01890 has a leading zero but is not an octal number; quote it to send it as a string"}, {"an anchored key whose alias is a value JSON cannot carry", "&k .inf: x\nb: *k", "line 1: .inf has no JSON representation; quote it to send it as a string"},