diff --git a/cmd/kosli/attestCustom.go b/cmd/kosli/attestCustom.go index b1d336586..d4721480c 100644 --- a/cmd/kosli/attestCustom.go +++ b/cmd/kosli/attestCustom.go @@ -15,15 +15,19 @@ type CustomAttestationPayload struct { type attestCustomOptions struct { *CommonAttestationOptions - attestationDataFile string - payload CustomAttestationPayload + attestationDataFile string + attestationDataAsList bool + payload CustomAttestationPayload } const attestCustomShortDesc = `Report a custom attestation to an artifact or a trail in a Kosli flow. ` const attestCustomLongDesc = attestCustomShortDesc + ` The name of the custom attestation type is specified using the ^--type^ flag. -The path to the JSON file the custom type will evaluate is specified using the ^--attestation-data^ 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. +A YAML file with several documents needs ^--attestation-data-as-list^, which sends the documents as a JSON list. ` + attestationBindingDesc + ` ` + kosliIgnoreDesc + ` @@ -84,6 +88,17 @@ kosli attest custom \ --attachments yourAttachmentPathName \ --api-token yourAPIToken \ --org yourOrgName + +# report a custom attestation about a trail from a multi-document YAML file (sent as a JSON list, one item per document): +kosli attest custom \ + --type customTypeName \ + --name yourAttestationName \ + --attestation-data yourYamlFilePath \ + --attestation-data-as-list \ + --flow yourFlowName \ + --trail yourTrailName \ + --api-token yourAPIToken \ + --org yourOrgName ` func newAttestCustomCmd(out io.Writer) *cobra.Command { @@ -141,6 +156,7 @@ func newAttestCustomCmd(out io.Writer) *cobra.Command { addAttestationFlags(cmd, o.CommonAttestationOptions, o.payload.CommonAttestationPayload, ci) cmd.Flags().StringVar(&o.payload.TypeName, "type", "", attestationCustomTypeNameFlag) cmd.Flags().StringVar(&o.attestationDataFile, "attestation-data", "", attestationCustomDataFileFlag) + cmd.Flags().BoolVar(&o.attestationDataAsList, "attestation-data-as-list", false, attestationCustomDataAsListFlag) err := RequireFlags(cmd, []string{"type", "attestation-data", "flow", "trail", "name"}) if err != nil { @@ -156,7 +172,7 @@ func (o *attestCustomOptions) run(args []string) error { return err } - o.payload.AttestationData, err = LoadJsonData(o.attestationDataFile) + o.payload.AttestationData, err = LoadAttestationData(o.attestationDataFile, o.attestationDataAsList) if err != nil { return fmt.Errorf("failed to load attestation data. %s", err) } diff --git a/cmd/kosli/attestCustom_test.go b/cmd/kosli/attestCustom_test.go index 6f807cefb..70fac8d46 100644 --- a/cmd/kosli/attestCustom_test.go +++ b/cmd/kosli/attestCustom_test.go @@ -158,6 +158,37 @@ func (suite *AttestCustomCommandTestSuite) TestAttestCustomCmd() { cmd: fmt.Sprintf("attest custom --name bar --annotate foo.baz=bar %s", suite.defaultKosliArguments), golden: "Error: --annotate flag should be in the format key=value. Invalid key: 'foo.baz'. Key can only contain [A-Za-z0-9_]\n", }, + { + name: "can attest custom with YAML attestation data", + cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/person-type-data-example.yaml", suite.defaultKosliArguments), + golden: "custom:person attestation 'bar' is reported to trail: test-321\n", + }, + { + name: "dry-run prints YAML attestation data as the converted JSON", + cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/person-type-data-example.yaml --dry-run", suite.defaultKosliArguments), + goldenRegex: `(?s)"attestation_data": \{\s+"age": 34,\s+"born": "1990-05-17",\s+"name": "Jane"\s+\}`, + }, + { + wantError: true, + name: "fails when a YAML file has several documents and --attestation-data-as-list is not set", + cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml", suite.defaultKosliArguments), + golden: "Error: failed to load attestation data. testdata/backstage-catalog-info.yaml contains 4 YAML documents. Use --attestation-data-as-list to send them as a list\n", + }, + { + name: "can attest custom with a multi-document YAML file as a list", + cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml --attestation-data-as-list", suite.defaultKosliArguments), + golden: "custom:person attestation 'bar' is reported to trail: test-321\n", + }, + { + name: "dry-run prints a multi-document YAML file as a root-level list", + cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml --attestation-data-as-list --dry-run", suite.defaultKosliArguments), + goldenRegex: `(?s)"attestation_data": \[\s+\{\s+"apiVersion": "backstage.io/v1alpha1",\s+"kind": "System",.*"kind": "Component",.*"kind": "Component",.*"kind": "Group",`, + }, + { + name: "dry-run wraps JSON attestation data in a list with --attestation-data-as-list", + cmd: fmt.Sprintf("attest custom --name bar --attestation-data-as-list --dry-run %s", suite.defaultKosliArguments), + goldenRegex: `(?s)"attestation_data": \[\s+\{\s+"age": 34,\s+"name": "Jane"\s+\}\s+\]`, + }, { wantError: true, name: "fails when --name has invalid dot format", diff --git a/cmd/kosli/attestationData_test.go b/cmd/kosli/attestationData_test.go new file mode 100644 index 000000000..d5100b4eb --- /dev/null +++ b/cmd/kosli/attestationData_test.go @@ -0,0 +1,198 @@ +package main + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func writeAttestationDataFile(t *testing.T, name, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + return path +} + +func TestLoadAttestationData(t *testing.T) { + for _, tc := range []struct { + name string + filename string + content string + asList bool + wantJSON string + wantErr string + }{ + { + name: "a .yaml file with one document is sent as that document", + filename: "data.yaml", + content: "name: Jane\nborn: 1990-05-17\n", + wantJSON: `{"born":"1990-05-17","name":"Jane"}`, + }, + { + name: "a .yml file is YAML too", + filename: "data.yml", + content: "- a\n- b\n", + wantJSON: `["a","b"]`, + }, + { + name: "the extension is matched case-insensitively", + filename: "DATA.YAML", + content: "name: Jane\n", + wantJSON: `{"name":"Jane"}`, + }, + { + name: "a .json file takes the JSON path", + filename: "data.json", + content: `{"name": "Jane", "age": 34}`, + wantJSON: `{"age":34,"name":"Jane"}`, + }, + { + name: "a file with no extension takes the JSON path", + filename: "data", + content: `[1, 2]`, + wantJSON: `[1,2]`, + }, + { + name: "YAML in a file without a YAML extension is not converted", + filename: "data.txt", + content: "name: Jane\n", + wantErr: "data.txt does not contain a valid JSON", + }, + { + name: "several YAML documents is an error that names the flag", + filename: "data.yaml", + content: "a: 1\n---\nb: 2\n", + wantErr: "data.yaml contains 2 YAML documents. Use --attestation-data-as-list to send them as a list", + }, + { + name: "empty documents are not counted", + filename: "data.yaml", + content: "---\n---\na: 1\n---\n~\n", + wantJSON: `{"a":1}`, + }, + { + name: "an empty YAML file is an error", + filename: "data.yaml", + content: "", + wantErr: "data.yaml contains no YAML documents. Use --attestation-data-as-list to send an empty list", + }, + { + name: "invalid YAML names the file", + filename: "data.yaml", + content: "a: 1\na: 2\n", + wantErr: "data.yaml does not contain valid YAML: ", + }, + { + name: "as a list, one YAML document is a list of one", + filename: "data.yaml", + content: "a: 1\n", + asList: true, + wantJSON: `[{"a":1}]`, + }, + { + name: "as a list, several YAML documents are one item each, in file order", + filename: "data.yaml", + content: "b: 2\n---\na: 1\n---\n- x\n", + asList: true, + wantJSON: `[{"b":2},{"a":1},["x"]]`, + }, + { + name: "as a list, empty documents between real ones are dropped", + filename: "data.yaml", + content: "---\n# Source: chart/templates/a.yaml\n---\na: 1\n---\n---\nnull\n---\nb: 2\n---\n", + asList: true, + wantJSON: `[{"a":1},{"b":2}]`, + }, + { + name: "as a list, an empty YAML file is an empty list", + filename: "data.yaml", + content: "", + asList: true, + wantJSON: `[]`, + }, + { + name: "as a list, a top-level YAML sequence is one document and is not unpacked", + filename: "data.yaml", + content: "- a\n- b\n", + asList: true, + wantJSON: `[["a","b"]]`, + }, + { + name: "as a list, a JSON object is wrapped in a list of one", + filename: "data.json", + content: `{"name": "Jane"}`, + asList: true, + wantJSON: `[{"name":"Jane"}]`, + }, + { + name: "as a list, a top-level JSON array is one document and is not unpacked", + filename: "data.json", + content: `[1, 2]`, + asList: true, + wantJSON: `[[1,2]]`, + }, + { + name: "as a list, an empty JSON file is still invalid JSON", + filename: "data.json", + content: "", + asList: true, + wantErr: "data.json does not contain a valid JSON", + }, + } { + t.Run(tc.name, func(t *testing.T) { + path := writeAttestationDataFile(t, tc.filename, tc.content) + data, err := LoadAttestationData(path, tc.asList) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + return + } + require.NoError(t, err) + got, err := json.Marshal(data) + require.NoError(t, err) + require.Equal(t, tc.wantJSON, string(got)) + }) + } +} + +func TestLoadAttestationDataMissingFile(t *testing.T) { + for _, name := range []string{"missing.yaml", "missing.json"} { + _, err := LoadAttestationData(filepath.Join(t.TempDir(), name), false) + require.ErrorIs(t, err, os.ErrNotExist) + } +} + +// A published policy reads this exact shape: the documents of the catalog file +// as a root-level list, in file order. +func TestLoadAttestationDataBackstageCatalogAsList(t *testing.T) { + data, err := LoadAttestationData("testdata/backstage-catalog-info.yaml", true) + require.NoError(t, err) + got, err := json.Marshal(data) + require.NoError(t, err) + + want, err := os.ReadFile("testdata/backstage-catalog-info.expected.json") + require.NoError(t, err) + var compact bytes.Buffer + require.NoError(t, json.Compact(&compact, want)) + + // Compared as bytes rather than with JSONEq so that item order, and + // anything wrapped around the list, fails the test. + require.Equal(t, sortedKeysJSON(t, compact.Bytes()), string(got)) + require.Equal(t, byte('['), got[0]) +} + +// sortedKeysJSON re-encodes raw the way encoding/json encodes a decoded +// value: object keys sorted, array order kept. +func sortedKeysJSON(t *testing.T, raw []byte) string { + t.Helper() + var value any + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + require.NoError(t, decoder.Decode(&value)) + out, err := json.Marshal(value) + require.NoError(t, err) + return string(out) +} diff --git a/cmd/kosli/cli_utils.go b/cmd/kosli/cli_utils.go index 5aeb57d44..f9566d247 100644 --- a/cmd/kosli/cli_utils.go +++ b/cmd/kosli/cli_utils.go @@ -7,6 +7,7 @@ import ( "io" urlPackage "net/url" "os" + "path/filepath" "reflect" "slices" "strconv" @@ -464,6 +465,48 @@ func LoadOptionalJsonData(filepath string) (any, error) { return LoadJsonData(filepath) } +// LoadAttestationData loads the data of a custom attestation from a JSON or +// YAML file. The extension picks the format, and YAML is converted to the +// JSON value it describes. +// +// A file holds a stream of documents: any number in YAML, exactly one in +// JSON. With asList the data is the list of those documents, otherwise the +// file must hold exactly one document and the data is that document. +func LoadAttestationData(path string, asList bool) (any, error) { + var documents []any + format := "JSON" + switch strings.ToLower(filepath.Ext(path)) { + case ".yaml", ".yml": + format = "YAML" + content, err := os.ReadFile(path) + if err != nil { + return nil, err + } + documents, err = utils.YAMLDocuments(content) + if err != nil { + return nil, fmt.Errorf("%s does not contain valid YAML: %w", path, err) + } + default: + document, err := LoadJsonData(path) + if err != nil { + return nil, err + } + documents = []any{document} + } + + if asList { + return documents, nil + } + switch len(documents) { + case 0: + return nil, fmt.Errorf("%s contains no %s documents. Use --attestation-data-as-list to send an empty list", path, format) + case 1: + return documents[0], nil + default: + return nil, fmt.Errorf("%s contains %d %s documents. Use --attestation-data-as-list to send them as a list", path, len(documents), format) + } +} + // ValidateArtifactArg validates the artifact name or path argument func ValidateArtifactArg(args []string, artifactType, inputSha256 string, alwaysRequireArtifactName bool) error { if len(args) > 1 { diff --git a/cmd/kosli/root.go b/cmd/kosli/root.go index 84645f3b2..71d76588f 100644 --- a/cmd/kosli/root.go +++ b/cmd/kosli/root.go @@ -334,7 +334,8 @@ Paths the list already matches stay excluded whatever is later added there, so k attestationCompliantFlag = "[defaulted] Whether the attestation is compliant or not." attestationRepoRootFlag = "[defaulted] The directory where the source git repository is available. It must be the repository's top-level directory. Only used if --commit is used or defaulted in CI, see https://docs.kosli.com/integrations/ci_cd/#defaulted-kosli-command-flags-from-ci-variables ." attestationCustomTypeNameFlag = "The name of the custom attestation type." - attestationCustomDataFileFlag = "The filepath of a JSON file containing the custom attestation data. The maximum JSON payload size is 1MB." + attestationCustomDataFileFlag = "The filepath of a JSON or YAML file containing the custom attestation data. The file extension picks the format: .yaml and .yml files are converted to JSON, any other file is read as JSON. In YAML, a number with a leading zero is read as octal (0644 becomes 420), so quote version-like values and codes (\"1.10\", \"0123\") to keep them as written. The maximum JSON payload size is 1MB, measured after conversion." + attestationCustomDataAsListFlag = "[optional] Send the custom attestation data as a list with one item per document in the file. A YAML file with several documents (separated by ---) needs this flag; empty documents are skipped. A JSON file is one document, so its value is wrapped in a list of one." uploadJunitResultsFlag = "[defaulted] Whether to upload the provided Junit results directory as an attachment to Kosli or not." uploadSnykResultsFlag = "[defaulted] Whether to upload the provided Snyk results file as an attachment to Kosli or not." attestationAssertFlag = "[optional] Exit with non-zero code if the attestation is non-compliant" diff --git a/cmd/kosli/testdata/backstage-catalog-info.expected.json b/cmd/kosli/testdata/backstage-catalog-info.expected.json new file mode 100644 index 000000000..d91442e40 --- /dev/null +++ b/cmd/kosli/testdata/backstage-catalog-info.expected.json @@ -0,0 +1,55 @@ +[ + { + "apiVersion": "backstage.io/v1alpha1", + "kind": "System", + "metadata": { + "name": "checkout", + "description": "Everything a shopper touches between basket and receipt" + }, + "spec": { + "owner": "team-payments" + } + }, + { + "apiVersion": "backstage.io/v1alpha1", + "kind": "Component", + "metadata": { + "name": "checkout-api", + "annotations": { + "github.com/project-slug": "example/checkout-api" + } + }, + "spec": { + "type": "service", + "lifecycle": "production", + "owner": "team-payments", + "system": "checkout" + } + }, + { + "apiVersion": "backstage.io/v1alpha1", + "kind": "Component", + "metadata": { + "name": "receipt-mailer", + "annotations": { + "github.com/project-slug": "example/receipt-mailer" + } + }, + "spec": { + "type": "service", + "lifecycle": "experimental", + "system": "checkout" + } + }, + { + "apiVersion": "backstage.io/v1alpha1", + "kind": "Group", + "metadata": { + "name": "team-payments" + }, + "spec": { + "type": "team", + "children": [] + } + } +] diff --git a/cmd/kosli/testdata/backstage-catalog-info.yaml b/cmd/kosli/testdata/backstage-catalog-info.yaml new file mode 100644 index 000000000..4615bb03d --- /dev/null +++ b/cmd/kosli/testdata/backstage-catalog-info.yaml @@ -0,0 +1,38 @@ +apiVersion: backstage.io/v1alpha1 +kind: System +metadata: + name: checkout + description: Everything a shopper touches between basket and receipt +spec: + owner: team-payments +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: checkout-api + annotations: + github.com/project-slug: example/checkout-api +spec: + type: service + lifecycle: production + owner: team-payments + system: checkout +--- +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: receipt-mailer + annotations: + github.com/project-slug: example/receipt-mailer +spec: + type: service + lifecycle: experimental + system: checkout +--- +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: team-payments +spec: + type: team + children: [] diff --git a/cmd/kosli/testdata/empty-flag-audit-coverage.json b/cmd/kosli/testdata/empty-flag-audit-coverage.json index ce30451e8..ae44ada22 100644 --- a/cmd/kosli/testdata/empty-flag-audit-coverage.json +++ b/cmd/kosli/testdata/empty-flag-audit-coverage.json @@ -119,6 +119,7 @@ "artifact-type": "string", "attachments": "stringSlice", "attestation-data": "string", + "attestation-data-as-list": "bool", "commit": "string", "description": "string", "dry-run": "bool", diff --git a/cmd/kosli/testdata/person-type-data-example.yaml b/cmd/kosli/testdata/person-type-data-example.yaml new file mode 100644 index 000000000..ecf3d6cdb --- /dev/null +++ b/cmd/kosli/testdata/person-type-data-example.yaml @@ -0,0 +1,3 @@ +name: Jane +age: 34 +born: 1990-05-17 diff --git a/hack/empty-flag-audit/categories.json b/hack/empty-flag-audit/categories.json index 7c1fb7598..ef31202c1 100644 --- a/hack/empty-flag-audit/categories.json +++ b/hack/empty-flag-audit/categories.json @@ -7,6 +7,7 @@ "assume-yes": "switch", "attachments": "identity", "attestation-data": "identity", + "attestation-data-as-list": "switch", "attestation-id": "identity", "attestations": "filter", "aws-key-id": "credentials", diff --git a/hack/empty-flag-audit/spec.json b/hack/empty-flag-audit/spec.json index 1b2a9d6a5..075c6b915 100644 --- a/hack/empty-flag-audit/spec.json +++ b/hack/empty-flag-audit/spec.json @@ -568,6 +568,7 @@ "artifact-type", "attachments", "attestation-data", + "attestation-data-as-list", "commit", "description", "dry-run", @@ -619,7 +620,8 @@ "trail": "{trail}", "type": "{name}", "user-data": "cmd/kosli/testdata/person-schema.json", - "no-commit-info": "true" + "no-commit-info": "true", + "attestation-data-as-list": "true" }, "setup": [ { diff --git a/internal/utils/yaml.go b/internal/utils/yaml.go new file mode 100644 index 000000000..a60087665 --- /dev/null +++ b/internal/utils/yaml.go @@ -0,0 +1,169 @@ +package utils + +import ( + "bytes" + "errors" + "fmt" + "io" + "math" + "regexp" + "strings" + + "gopkg.in/yaml.v3" +) + +const ( + yamlStrTag = "!!str" + yamlNullTag = "!!null" + yamlFloatTag = "!!float" + yamlTimestampTag = "!!timestamp" + yamlMergeTag = "!!merge" +) + +var yamlIntegerLiteral = regexp.MustCompile(`^[-+]?[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 +// result can be empty but is never nil. +// +// 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. +func YAMLDocuments(content []byte) ([]any, error) { + documents := []any{} + decoder := yaml.NewDecoder(bytes.NewReader(content)) + for position := 1; ; position++ { + var document yaml.Node + err := decoder.Decode(&document) + if errors.Is(err, io.EOF) { + return documents, nil + } + if err != nil { + return nil, inYAMLDocument(position, err) + } + if isNullYAMLDocument(&document) { + continue + } + if err := prepareYAMLNode(&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) + } +} + +func inYAMLDocument(position int, err error) error { + if position == 1 { + return err + } + return fmt.Errorf("document %d: %w", position, err) +} + +func isNullYAMLDocument(document *yaml.Node) bool { + if len(document.Content) == 0 { + return true + } + root := document.Content[0] + return root.Kind == yaml.ScalarNode && root.ShortTag() == yamlNullTag +} + +// prepareYAMLNode 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 { + switch node.Kind { + case yaml.ScalarNode: + return prepareYAMLScalar(node) + case yaml.MappingNode: + for i := 0; i+1 < len(node.Content); i += 2 { + key, err := yamlStringKey(node.Content[i]) + if err != nil { + return err + } + node.Content[i] = key + if err := prepareYAMLNode(node.Content[i+1]); err != nil { + return err + } + } + case yaml.DocumentNode, yaml.SequenceNode: + for _, child := range node.Content { + if err := prepareYAMLNode(child); err != nil { + return err + } + } + } + return nil +} + +func prepareYAMLScalar(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") { + 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) + } + var value float64 + if err := node.Decode(&value); err != nil { + return err + } + if math.IsInf(value, 0) || math.IsNaN(value) { + return fmt.Errorf("line %d: %s has no JSON representation; quote it to send it as a string", node.Line, node.Value) + } + } + return nil +} + +// yamlStringKey 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) { + target := key + if key.Kind == yaml.AliasNode { + target = key.Alias + } + if target.Kind != yaml.ScalarNode { + return nil, fmt.Errorf("line %d: a mapping key must be a scalar, found %s", key.Line, yamlKindName(target.Kind)) + } + 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 { + return nil, err + } + } + switch target.ShortTag() { + case yamlStrTag, yamlMergeTag: + return key, nil + } + // 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 +} + +func yamlKindName(kind yaml.Kind) string { + switch kind { + case yaml.SequenceNode: + return "a sequence" + case yaml.MappingNode: + return "a mapping" + default: + return "a non-scalar node" + } +} diff --git a/internal/utils/yaml_test.go b/internal/utils/yaml_test.go new file mode 100644 index 000000000..cc32aaedf --- /dev/null +++ b/internal/utils/yaml_test.go @@ -0,0 +1,113 @@ +package utils + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func yamlToJSON(t *testing.T, in string) string { + t.Helper() + docs, err := YAMLDocuments([]byte(in)) + require.NoError(t, err) + out, err := json.Marshal(docs) + require.NoError(t, err) + return string(out) +} + +// This table is the scalar conversion contract documented for users. +func TestYAMLDocumentsScalars(t *testing.T) { + for _, tc := range []struct { + yaml string + json string + }{ + {`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"}]`}, + {`c: NO`, `[{"c":"NO"}]`}, + {`e: yes`, `[{"e":"yes"}]`}, + {`e: no`, `[{"e":"no"}]`}, + {`e: on`, `[{"e":"on"}]`}, + {`e: off`, `[{"e":"off"}]`}, + {`b: true`, `[{"b":true}]`}, + {`n: ~`, `[{"n":null}]`}, + {`i: 12345678901234567890`, `[{"i":12345678901234567890}]`}, + {`i: -9223372036854775808`, `[{"i":-9223372036854775808}]`}, + {`o: 0123`, `[{"o":83}]`}, + {`o: "0123"`, `[{"o":"0123"}]`}, + {`f: !!float 5`, `[{"f":5}]`}, + } { + t.Run(tc.yaml, func(t *testing.T) { + require.Equal(t, tc.json, yamlToJSON(t, tc.yaml)) + }) + } +} + +func TestYAMLDocumentsStructure(t *testing.T) { + for _, tc := range []struct { + name string + yaml string + json string + }{ + {"aliases resolve", "a: &x [1, 2]\nb: *x", `[{"a":[1,2],"b":[1,2]}]`}, + {"merge keys resolve", "base: &b {x: 1, y: 1}\nc:\n <<: *b\n y: 2", `[{"base":{"x":1,"y":1},"c":{"x":1,"y":2}}]`}, + {"a quoted << is an ordinary key", `{"<<": 1}`, `[{"\u003c\u003c":1}]`}, + {"scalar keys become strings as written", "1: a\n1.10: b\ntrue: c\n~: d\n2026-12-01: e\n0123: f", `[{"0123":"f","1":"a","1.10":"b","2026-12-01":"e","true":"c","~":"d"}]`}, + {"an aliased scalar key becomes a string", "a: &k 1\n*k : b", `[{"1":"b","a":1}]`}, + {"an anchored date key stays as written where its alias is a value", "&d 2026-01-01: x\nb: *d", `[{"2026-01-01":"x","b":"2026-01-01"}]`}, + {"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"}]`}, + {"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"]`}, + {"several documents keep file order", "a: 1\n---\nb: 2\n---\n- c", `[{"a":1},{"b":2},["c"]]`}, + {"empty and null documents are dropped", "---\na: 1\n---\n---\n~\n---\nnull\n---\n# comment\n---\nb: 2\n", `[{"a":1},{"b":2}]`}, + {"empty input has no documents", "", `[]`}, + {"only separators has no documents", "---\n---\n", `[]`}, + {"only comments has no documents", "# nothing\n", `[]`}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.json, yamlToJSON(t, tc.yaml)) + }) + } +} + +func TestYAMLDocumentsNoDocumentsIsEmptyNotNil(t *testing.T) { + docs, err := YAMLDocuments(nil) + require.NoError(t, err) + require.NotNil(t, docs) + require.Empty(t, docs) +} + +func TestYAMLDocumentsErrors(t *testing.T) { + for _, tc := range []struct { + name string + yaml string + wantErr string + }{ + {"duplicate keys", "a: 1\na: 2", `line 2: mapping key "a" already defined at line 1`}, + {"keys that collide once they are strings", "1: a\n\"1\": b", `line 2: mapping key "1" already defined at line 1`}, + {"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"}, + {"infinity", "f: .inf", "line 1: .inf has no JSON representation; quote it to send it as a string"}, + {"negative infinity in a list", "- 1\n- -.Inf", "line 2: -.Inf has no JSON representation; quote it to send it as a string"}, + {"not a number", "f: .nan", "line 1: .nan has no JSON representation; quote it to send it as a string"}, + {"invalid yaml", "a: [1, 2", "yaml: "}, + {"an error in a later document names the document", "a: 1\n---\nb: 1\nb: 2", "document 2: "}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := YAMLDocuments([]byte(tc.yaml)) + require.ErrorContains(t, err, tc.wantErr) + }) + } +}