Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
267 changes: 267 additions & 0 deletions overlay/aliases.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading