diff --git a/overlay/aliases.go b/overlay/aliases.go new file mode 100644 index 00000000..fb50423e --- /dev/null +++ b/overlay/aliases.go @@ -0,0 +1,267 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package overlay + +import ( + "fmt" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/go-yaml/plugin/loaderlimits" + "github.com/pb33f/libopenapi/utils" +) + +// An overlay addresses the JSON data model of a document, where every value +// belongs to one place. A YAML anchor shares one node between every alias and +// merge key that names it. Left shared, an action on one place changes the +// others, and removing the node that defines an anchor leaves its aliases +// naming nothing, so the result does not parse. Documents and update values +// are made plain trees before any action applies. + +// aliasLimits is yaml's own alias expansion limit, with its defaults. +var aliasLimits loaderlimits.Plugin + +// maxAliasText is the most text (values and comments) that alias copies can +// add. A copy shares its strings with the node it copies, so the node limit +// controls memory, but only this limit controls the size of the output. +const maxAliasText = 64 << 20 + +const ( + aliasExpanding uint8 = iota + 1 + aliasExpanded +) + +type aliasExpansion struct { + // state holds only the nodes an alias can name. No other node is visited twice. + state map[*yaml.Node]uint8 + // sizes holds the size of each expanded node that an alias copies. + sizes map[*yaml.Node]treeSize + nodes int + aliasNodes int + aliasText int +} + +type treeSize struct { + nodes int + text int +} + +// expandAliases replaces every alias under root with its own copy of the node +// it names, applies merge keys, and drops anchor names. A tree with none of +// these keeps every node it has. +func expandAliases(root *yaml.Node) error { + return (&aliasExpansion{}).expand(root, false) +} + +// plainUpdate returns an update value with no alias, anchor or merge key. The +// overlay is the caller's, so a value that has any is copied before expansion. +func plainUpdate(update *yaml.Node) (*yaml.Node, error) { + if !sharesNodes(update) { + return update, nil + } + // An alias cannot replace itself, so expand the value as a child. + holder := &yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{utils.CloneYAMLNode(update)}} + if err := expandAliases(holder); err != nil { + return nil, err + } + return holder.Content[0], nil +} + +func sharesNodes(node *yaml.Node) bool { + if node == nil { + return false + } + if node.Kind == yaml.AliasNode || node.Anchor != "" || node.Tag == "!!merge" { + return true + } + for _, child := range node.Content { + if sharesNodes(child) { + return true + } + } + return false +} + +func (e *aliasExpansion) expand(node *yaml.Node, aliased bool) error { + shared := aliased || node.Anchor != "" + if shared { + switch e.state[node] { + case aliasExpanded: + return nil + case aliasExpanding: + return fmt.Errorf("%w: anchor %q contains itself", ErrInvalidAlias, node.Anchor) + } + if e.state == nil { + e.state = make(map[*yaml.Node]uint8) + } + e.state[node] = aliasExpanding + } + + e.nodes++ + mapping := node.Kind == yaml.MappingNode + merges := false + for i, child := range node.Content { + if child == nil { + continue + } + if child.Kind != yaml.AliasNode { + // Only a key can be a merge key. A "<<" value is a string. + if child.Tag == "!!merge" && mapping && i%2 == 0 { + merges = true + } + if err := e.expand(child, false); err != nil { + return err + } + continue + } + copied, err := e.copyAlias(child, mapping && i%2 == 0) + if err != nil { + return err + } + node.Content[i] = copied + } + if merges { + if err := resolveMerges(node); err != nil { + return err + } + } + node.Anchor = "" + + if shared { + e.state[node] = aliasExpanded + } + return nil +} + +// copyAlias returns a copy of the node that alias names. The copy is counted +// against the limits before it is made. +func (e *aliasExpansion) copyAlias(alias *yaml.Node, key bool) (*yaml.Node, error) { + if alias.Alias == nil { + return nil, fmt.Errorf("%w: alias %q names no node", ErrInvalidAlias, alias.Value) + } + // go-yaml counts the alias as a node of the document. + e.nodes++ + // The named node is expanded once, in place. Every alias then takes a + // copy of a tree that has no alias left in it. + if err := e.expand(alias.Alias, true); err != nil { + return nil, err + } + size, ok := e.sizes[alias.Alias] + if !ok { + if size, ok = measureTree(alias.Alias); !ok { + return nil, fmt.Errorf("%w: anchor %q holds a nil node", ErrInvalidAlias, alias.Value) + } + if e.sizes == nil { + e.sizes = make(map[*yaml.Node]treeSize) + } + e.sizes[alias.Alias] = size + } + + e.nodes += size.nodes + e.aliasNodes += size.nodes + e.aliasText += size.text + if err := aliasLimits.CheckAlias(e.aliasNodes, e.nodes); err != nil { + return nil, fmt.Errorf("%w: %w", ErrExcessiveAliases, err) + } + if e.aliasText > maxAliasText { + return nil, fmt.Errorf("%w: alias copies add more than %d bytes of text", ErrExcessiveAliases, maxAliasText) + } + + copied := copyTree(alias.Alias) + keepAliasComments(copied, alias) + // go-yaml reads an alias key as a literal key, also when it names "<<". + // A quoted string keeps it literal. + if key && copied.Kind == yaml.ScalarNode && copied.Value == "<<" { + copied.Tag = "!!str" + copied.Style = yaml.DoubleQuotedStyle + } + return copied, nil +} + +// keepAliasComments gives a copy the comments at its alias. The comments at +// the anchor belong to the place of the anchor. go-yaml keeps the head and line +// comment at the start of a block mapping or sequence on its first entry, so +// the copy moves them there too. +func keepAliasComments(copied, alias *yaml.Node) { + copied.HeadComment = alias.HeadComment + copied.LineComment = alias.LineComment + copied.FootComment = alias.FootComment + block := copied.Kind == yaml.MappingNode || copied.Kind == yaml.SequenceNode + if !block || copied.Style&yaml.FlowStyle != 0 || len(copied.Content) == 0 { + return + } + first := copied.Content[0] + first.HeadComment = "" + first.LineComment = copied.LineComment + copied.LineComment = "" +} + +// measureTree returns the number of nodes and the bytes of text in an +// expanded tree. It returns false if the tree holds a nil node. +func measureTree(node *yaml.Node) (treeSize, bool) { + size := treeSize{ + nodes: 1, + text: len(node.Value) + len(node.HeadComment) + len(node.LineComment) + len(node.FootComment), + } + for _, child := range node.Content { + if child == nil { + return treeSize{}, false + } + childSize, ok := measureTree(child) + if !ok { + return treeSize{}, false + } + size.nodes += childSize.nodes + size.text += childSize.text + } + return size, true +} + +// copyTree copies an expanded tree. The tree holds no nil node. +func copyTree(node *yaml.Node) *yaml.Node { + copied := *node + if len(node.Content) > 0 { + copied.Content = make([]*yaml.Node, len(node.Content)) + for i, child := range node.Content { + copied.Content[i] = copyTree(child) + } + } + return &copied +} + +// resolveMerges applies the merge keys of an expanded mapping. As in go-yaml, +// each merge value must be a mapping or a list of mappings. +func resolveMerges(node *yaml.Node) error { + for i := 0; i+1 < len(node.Content); i += 2 { + if key := node.Content[i]; key != nil && key.Tag == "!!merge" && !isMergeSource(node.Content[i+1]) { + return fmt.Errorf("%w (line %d)", ErrInvalidMergeKey, key.Line) + } + } + resolved := utils.ResolveMergeNodes(node) + if resolved == node { + // ResolveMergeNodes returns the node unchanged when the merge gives no + // entry. {<<: {}} is the empty mapping. + node.Content = nil + return nil + } + node.Content = resolved.Content + return nil +} + +func isMergeSource(value *yaml.Node) bool { + if value == nil { + return false + } + switch value.Kind { + case yaml.MappingNode: + return true + case yaml.SequenceNode: + for _, item := range value.Content { + if item == nil || item.Kind != yaml.MappingNode { + return false + } + } + return true + } + return false +} diff --git a/overlay/aliases_test.go b/overlay/aliases_test.go new file mode 100644 index 00000000..fdf1225b --- /dev/null +++ b/overlay/aliases_test.go @@ -0,0 +1,582 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package overlay + +import ( + "fmt" + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/go-yaml/plugin/loaderlimits" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +const aliasOverlayHead = `overlay: 1.0.0 +info: + title: Alias overlay + version: 1.0.0 +` + +// sharedContentSpec has one media type map that two operations use: /admin/a +// defines the anchor and /b is an alias to it. +const sharedContentSpec = `openapi: 3.1.0 +info: + title: Aliases + version: 1.0.0 +paths: + /admin/a: + get: + responses: + '200': + description: ok + content: &shared + application/json: + schema: + type: string + /b: + get: + responses: + '200': + description: ok + content: *shared +` + +// applyToYAML applies the actions and checks that the result is a document +// that parses again and has no anchor or alias left in it. +func applyToYAML(t *testing.T, spec, actions string) string { + t.Helper() + result, err := Apply([]byte(spec), parseOverlay(t, aliasOverlayHead+actions)) + require.NoError(t, err) + + var parsed yaml.Node + require.NoError(t, yaml.Unmarshal(result.Bytes, &parsed), "the result must parse:\n%s", result.Bytes) + assertPlainTree(t, &parsed) + return string(result.Bytes) +} + +func assertPlainTree(t *testing.T, node *yaml.Node) { + t.Helper() + assert.NotEqual(t, yaml.AliasNode, node.Kind, "alias left in the result") + assert.Empty(t, node.Anchor, "anchor left in the result") + assert.NotEqual(t, "!!merge", node.Tag, "merge key left in the result") + for _, child := range node.Content { + assertPlainTree(t, child) + } +} + +func TestApply_RemoveAnchorOwner_KeepsAliasedValue(t *testing.T) { + out := applyToYAML(t, sharedContentSpec, `actions: + - target: $.paths['/admin/a'] + remove: true +`) + + assert.Equal(t, `openapi: 3.1.0 +info: + title: Aliases + version: 1.0.0 +paths: + /b: + get: + responses: + '200': + description: ok + content: + application/json: + schema: + type: string +`, out) +} + +func TestApply_RemoveAnchorOwner_KeepsEveryAliasedValue(t *testing.T) { + spec := sharedContentSpec + ` /c: + get: + responses: + '200': + description: ok + content: *shared +` + out := applyToYAML(t, spec, `actions: + - target: $.paths['/admin/a'] + remove: true +`) + + assert.NotContains(t, out, "/admin/a") + assert.Equal(t, 2, strings.Count(out, "application/json")) +} + +func TestApply_RemoveThroughAlias_LeavesAnchorOwner(t *testing.T) { + out := applyToYAML(t, sharedContentSpec, `actions: + - target: $.paths['/b'].get.responses['200'].content['application/json'] + remove: true +`) + + assert.Equal(t, `openapi: 3.1.0 +info: + title: Aliases + version: 1.0.0 +paths: + /admin/a: + get: + responses: + '200': + description: ok + content: + application/json: + schema: + type: string + /b: + get: + responses: + '200': + description: ok + content: {} +`, out) +} + +func TestApply_UpdateThroughAlias_LeavesAnchorOwner(t *testing.T) { + out := applyToYAML(t, sharedContentSpec, `actions: + - target: $.paths['/b'].get.responses['200'].content['application/json'].schema + update: + format: uuid +`) + + assert.Equal(t, 1, strings.Count(out, "format: uuid")) + assert.Less(t, strings.Index(out, "/b:"), strings.Index(out, "format: uuid")) +} + +func TestApply_UpdateAnchorOwner_LeavesAliasedValue(t *testing.T) { + out := applyToYAML(t, sharedContentSpec, `actions: + - target: $.paths['/admin/a'].get.responses['200'].content['application/json'].schema + update: + format: email +`) + + assert.Equal(t, 1, strings.Count(out, "format: email")) + assert.Greater(t, strings.Index(out, "/b:"), strings.Index(out, "format: email")) +} + +func TestApply_CopyAnchorOwner(t *testing.T) { + spec := sharedContentSpec + ` /c: + get: + responses: {} +` + out := applyToYAML(t, spec, `actions: + - target: $.paths['/c'].get.responses + copy: $.paths['/admin/a'].get.responses +`) + + assert.Equal(t, 3, strings.Count(out, "application/json")) +} + +func TestApply_MergeKey_RemoveAnchorOwner(t *testing.T) { + spec := `openapi: 3.1.0 +info: + title: Merge keys + version: 1.0.0 +paths: + /admin/a: + get: &op + summary: shared summary + operationId: a + responses: + '200': + description: ok + /b: + get: + <<: *op + operationId: b +` + out := applyToYAML(t, spec, `actions: + - target: $.paths['/admin/a'] + remove: true +`) + + assert.Equal(t, `openapi: 3.1.0 +info: + title: Merge keys + version: 1.0.0 +paths: + /b: + get: + operationId: b + summary: shared summary + responses: + '200': + description: ok +`, out) +} + +func TestApply_MergeKey_TargetMergedProperty(t *testing.T) { + spec := `openapi: 3.1.0 +info: + title: Merge keys + version: 1.0.0 +paths: + /a: + get: &op + summary: shared summary + responses: + '200': + description: ok + /b: + get: + <<: *op + operationId: b +` + out := applyToYAML(t, spec, `actions: + - target: $.paths['/b'].get.summary + update: summary of b +`) + + assert.Equal(t, 1, strings.Count(out, "summary: shared summary")) + assert.Equal(t, 1, strings.Count(out, "summary: summary of b")) +} + +func TestApply_UpdateValueWithAlias(t *testing.T) { + spec := `openapi: 3.1.0 +info: + title: Aliases + version: 1.0.0 +paths: + /a: + get: + responses: {} + /b: + get: + responses: {} +` + out := applyToYAML(t, spec, `actions: + - target: $.paths['/a'].get.responses + update: + '200': &ok + description: ok + - target: $.paths['/b'].get.responses + update: + '200': *ok +`) + + assert.Equal(t, 2, strings.Count(out, "description: ok")) +} + +func TestApply_UpdateValueWithAlias_OverlayUnchanged(t *testing.T) { + overlay := parseOverlay(t, aliasOverlayHead+`actions: + - target: $.info + update: + contact: &who + name: Docs + - target: $.info + update: + x-owner: *who +`) + before, err := yaml.Marshal(overlay.Actions[1].Update) + require.NoError(t, err) + + _, err = Apply([]byte(sharedContentSpec), overlay) + require.NoError(t, err) + + after, err := yaml.Marshal(overlay.Actions[1].Update) + require.NoError(t, err) + assert.Equal(t, string(before), string(after)) +} + +func TestExpandAliases_Cycle(t *testing.T) { + list := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Anchor: "loop"} + list.Content = []*yaml.Node{{Kind: yaml.AliasNode, Value: "loop", Alias: list}} + root := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{list}} + + assert.ErrorIs(t, expandAliases(root), ErrInvalidAlias) +} + +func TestExpandAliases_AliasWithoutTarget(t *testing.T) { + root := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{ + {Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{{Kind: yaml.AliasNode, Value: "gone"}}}, + }} + + assert.ErrorIs(t, expandAliases(root), ErrInvalidAlias) +} + +func TestApply_ExcessiveAliases(t *testing.T) { + // Each level holds ten aliases to the level before it: ten levels expand + // to ten billion values. + var spec strings.Builder + spec.WriteString("openapi: 3.1.0\ninfo:\n title: Aliases\n version: 1.0.0\npaths: {}\nx-l0: &l0 [a, a, a, a, a, a, a, a, a, a]\n") + for level := 1; level <= 9; level++ { + aliases := strings.TrimSuffix(strings.Repeat(fmt.Sprintf("*l%d, ", level-1), 10), ", ") + fmt.Fprintf(&spec, "x-l%d: &l%d [%s]\n", level, level, aliases) + } + + _, err := Apply([]byte(spec.String()), parseOverlay(t, aliasOverlayHead+`actions: + - target: $.info + update: + title: Changed +`)) + + assert.ErrorIs(t, err, ErrExcessiveAliases) +} + +func TestExpandAliases_NoAliases_KeepsNodes(t *testing.T) { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte("a:\n b: [1, 2]\n"), &root)) + before := root.Content[0].Content[1] + + require.NoError(t, expandAliases(&root)) + + assert.Same(t, before, root.Content[0].Content[1]) +} + +func TestPlainUpdate_NilChild(t *testing.T) { + // A tree built in code can hold a nil child. It is left as it is. + update := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{ + nil, + {Kind: yaml.ScalarNode, Tag: "!!str", Value: "a", Anchor: "named"}, + }} + + plain, err := plainUpdate(update) + require.NoError(t, err) + + require.Len(t, plain.Content, 2) + assert.Nil(t, plain.Content[0]) + assert.Empty(t, plain.Content[1].Anchor) + assert.Equal(t, "named", update.Content[1].Anchor, "the overlay's own value must not change") + + // An alias cannot copy a node that holds a nil child at any depth. + named := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Anchor: "list", Content: []*yaml.Node{ + {Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{nil}}, + }} + _, err = plainUpdate(&yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{ + named, + {Kind: yaml.AliasNode, Value: "list", Alias: named}, + }}) + assert.ErrorIs(t, err, ErrInvalidAlias) +} + +func TestExpandAliases_LimitCheckedBeforeCopy(t *testing.T) { + saved := aliasLimits + aliasLimits = *loaderlimits.New(loaderlimits.AliasValue(100)) + t.Cleanup(func() { aliasLimits = saved }) + + named := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Anchor: "big"} + for range 10_000 { + named.Content = append(named.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: "a"}) + } + root := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq", Content: []*yaml.Node{ + named, + {Kind: yaml.AliasNode, Value: "big", Alias: named}, + }} + + var err error + allocs := testing.AllocsPerRun(5, func() { err = expandAliases(root) }) + + assert.ErrorIs(t, err, ErrExcessiveAliases) + assert.Less(t, allocs, 100.0, "the copy must not be made when it is over the limit") +} + +func TestApply_ExcessiveAliasText(t *testing.T) { + // 65 aliases are in the alias count limit, but their copies add 65 MiB of text. + var spec strings.Builder + fmt.Fprintf(&spec, "openapi: 3.1.0\ninfo:\n title: Aliases\n version: 1.0.0\npaths: {}\nx-text: &text %s\nx-copies:\n", + strings.Repeat("a", 1<<20)) + for range 65 { + spec.WriteString(" - *text\n") + } + + _, err := Apply([]byte(spec.String()), parseOverlay(t, aliasOverlayHead+`actions: + - target: $.info + update: + title: Changed +`)) + + assert.ErrorIs(t, err, ErrExcessiveAliases) +} + +func TestApply_FlatAliasList(t *testing.T) { + spec := "openapi: 3.1.0\ninfo:\n title: Aliases\n version: 1.0.0\npaths: {}\nx-name: &n v\nx-list: [" + + strings.TrimSuffix(strings.Repeat("*n, ", 2048), ", ") + "]\n" + var decoded any + require.NoError(t, yaml.Unmarshal([]byte(spec), &decoded), "go-yaml accepts the list") + + out := applyToYAML(t, spec, `actions: + - target: $.info + update: + title: Changed +`) + + var result struct { + List []string `yaml:"x-list"` + } + require.NoError(t, yaml.Unmarshal([]byte(out), &result)) + assert.Len(t, result.List, 2048) +} + +func TestApply_AliasKeyIsLiteralMergeText(t *testing.T) { + // The alias key names a plain "<<" value. go-yaml reads an alias key as a + // literal key, not as a merge key. + spec := `openapi: 3.1.0 +info: + title: Keys + version: 1.0.0 +paths: {} +x-key: &key << +x-map: + *key : literal + <<: {merged: true} +` + var want map[string]any + require.NoError(t, yaml.Unmarshal([]byte(spec), &want)) + require.Equal(t, map[string]any{"<<": "literal", "merged": true}, want["x-map"]) + + result, err := Apply([]byte(spec), parseOverlay(t, aliasOverlayHead+`actions: + - target: $.info + update: + title: Changed +`)) + require.NoError(t, err) + + var got map[string]any + require.NoError(t, yaml.Unmarshal(result.Bytes, &got), "the result must parse:\n%s", result.Bytes) + assert.Equal(t, want["x-map"], got["x-map"]) +} + +func TestApply_EmptyMerge_HasNoProperties(t *testing.T) { + spec := "openapi: 3.1.0\ninfo:\n title: Merge keys\n version: 1.0.0\npaths: {}\nx-empty:\n <<: {}\n" + + // {<<: {}} is the empty mapping, so the wildcard matches no property. + out := applyToYAML(t, spec, `actions: + - target: $['x-empty'].* + update: + a: b +`) + + assert.Contains(t, out, "x-empty: {}\n") + assert.NotContains(t, out, "a: b") +} + +func TestApply_MergeValueNotMapping(t *testing.T) { + values := map[string]string{ + "scalar": "name", + "null": "~", + "list with a scalar": "[{a: b}, name]", + "alias to a scalar": "*name", + } + for name, value := range values { + t.Run(name, func(t *testing.T) { + spec := "openapi: 3.1.0\ninfo:\n title: Merge keys\n version: 1.0.0\npaths: {}\nx-name: &name name\n" + + "x-map: {<<: " + value + ", enabled: true}\n" + var decoded any + require.Error(t, yaml.Unmarshal([]byte(spec), &decoded), "go-yaml rejects the merge value") + + _, err := Apply([]byte(spec), parseOverlay(t, aliasOverlayHead+`actions: + - target: $.info + update: + title: Changed +`)) + + assert.ErrorIs(t, err, ErrInvalidMergeKey) + }) + } +} + +func TestApply_MergeKeyList(t *testing.T) { + // The earlier merge source wins, and the mapping's own keys win over both. + spec := `openapi: 3.1.0 +info: + title: Merge keys + version: 1.0.0 +paths: {} +x-a: &a {name: a, kind: first} +x-b: &b {name: b, extra: true, own: no} +x-map: + <<: [*a, *b] + own: yes +` + var want map[string]any + require.NoError(t, yaml.Unmarshal([]byte(spec), &want)) + + out := applyToYAML(t, spec, `actions: + - target: $.info + update: + title: Changed +`) + + var got map[string]any + require.NoError(t, yaml.Unmarshal([]byte(out), &got)) + assert.Equal(t, want["x-map"], got["x-map"]) + assert.Equal(t, map[string]any{"name": "a", "kind": "first", "extra": true, "own": "yes"}, got["x-map"]) +} + +func TestPlainUpdate_MergeKeyWithoutValue(t *testing.T) { + // A tree built in code can hold a merge key with a nil value. + update := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{ + {Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}, + nil, + }} + + _, err := plainUpdate(update) + + assert.ErrorIs(t, err, ErrInvalidMergeKey) +} + +func TestApply_AliasKeepsItsComments(t *testing.T) { + // go-yaml keeps the comments at the start of a block mapping or sequence + // on its first entry, and the comments of a flow mapping or a scalar on + // the node itself. + spec := `openapi: 3.1.0 +info: + title: Comments + version: 1.0.0 +paths: {} +servers: + # production deployment + - &prod + url: https://example.com + # staging deployment + - *prod +x-block: &block # block anchor + name: a +x-block-copy: *block # block alias +x-list: &list # list anchor + - a +x-list-copy: *list # list alias +x-flow: &flow {name: b} # flow anchor +x-flow-copy: *flow # flow alias +x-scalar: &scalar c # scalar anchor +x-scalar-copy: *scalar # scalar alias +` + out := applyToYAML(t, spec, `actions: + - target: $.info + update: + title: Changed +`) + + assert.Equal(t, `openapi: 3.1.0 +info: + title: Changed + version: 1.0.0 +paths: {} +servers: + - # production deployment + url: https://example.com + # staging deployment + - url: https://example.com +x-block: + name: a # block anchor +x-block-copy: + name: a # block alias +x-list: + - a # list anchor +x-list-copy: + - a # list alias +x-flow: {name: b} # flow anchor +x-flow-copy: {name: b} # flow alias +x-scalar: c # scalar anchor +x-scalar-copy: c # scalar alias +`, out) +} + +func TestMergeNode_UnsupportedKind(t *testing.T) { + alias := &yaml.Node{Kind: yaml.AliasNode} + assert.ErrorIs(t, mergeNode(alias, alias), ErrIncompatibleUpdate) +} diff --git a/overlay/conformance_test.go b/overlay/conformance_test.go index ab3e78cf..690c37be 100644 --- a/overlay/conformance_test.go +++ b/overlay/conformance_test.go @@ -362,8 +362,8 @@ func TestApply_ReferenceWithoutComponents(t *testing.T) { } func TestApply_RejectCyclicAliasMerge(t *testing.T) { - // A cyclic YAML alias cannot represent a JSON value. Reject it instead of - // silently leaving the old alias in place during a recursive object merge. + // A cyclic YAML alias cannot represent a JSON value. The target is + // rejected when its aliases are expanded, before any action applies. target := []byte("object: &original {self: *original}") ov := parseOverlay(t, `overlay: 1.2.0 info: {title: Cyclic input, version: '1'} @@ -372,7 +372,20 @@ actions: update: &replacement {self: *replacement} `) result, err := Apply(target, ov) - require.ErrorIs(t, err, ErrIncompatibleUpdate) + require.ErrorIs(t, err, ErrInvalidAlias) + require.Nil(t, result) + assert.Contains(t, err.Error(), `anchor "original" contains itself`) +} + +func TestApply_RejectCyclicAliasUpdate(t *testing.T) { + ov := parseOverlay(t, `overlay: 1.2.0 +info: {title: Cyclic update, version: '1'} +actions: + - target: $.object + update: &replacement {self: *replacement} +`) + result, err := Apply([]byte("object: {}"), ov) + require.ErrorIs(t, err, ErrInvalidAlias) require.Nil(t, result) - assert.Contains(t, err.Error(), `property "self"`) + assert.Contains(t, err.Error(), `anchor "replacement" contains itself`) } diff --git a/overlay/engine.go b/overlay/engine.go index 032bd278..dc440768 100644 --- a/overlay/engine.go +++ b/overlay/engine.go @@ -28,6 +28,9 @@ func Apply(targetBytes []byte, overlay *highoverlay.Overlay) (*Result, error) { if err := jsonnode.Unmarshal(targetBytes, &rootNode); err != nil { return nil, err } + if err := expandAliases(&rootNode); err != nil { + return nil, err + } // Parent index is built lazily and rebuilt after updates/copies to ensure // remove actions can target nodes created by earlier update/copy actions. @@ -115,7 +118,11 @@ func applyAction(root *yaml.Node, action *highoverlay.Action, parentIdx parentIn if err := validateTargets(nodes); err != nil { return nil, err } - if err := applyUpdateAction(nodes, action.Update); err != nil { + update, err := plainUpdate(action.Update) + if err != nil { + return nil, err + } + if err := applyUpdateAction(nodes, update); err != nil { return nil, err } } diff --git a/overlay/errors.go b/overlay/errors.go index 9e9c0138..80fdec27 100644 --- a/overlay/errors.go +++ b/overlay/errors.go @@ -62,6 +62,12 @@ var ( // Application errors ErrNoTargetDocument = errors.New("no target document provided") + // YAML alias and merge key errors. Aliases and merge keys are expanded + // before actions apply. + ErrInvalidAlias = errors.New("YAML alias cannot be expanded") + ErrExcessiveAliases = errors.New("excessive YAML alias expansion") + ErrInvalidMergeKey = errors.New("YAML merge key value is not a mapping or a list of mappings") + // Copy action errors ErrCopySourceNotFound = errors.New("copy source JSONPath matched zero nodes") ErrCopySourceMultiple = errors.New("copy source JSONPath must match exactly one node")