Fix self referencing anchors should cause error (#132)

This commit is contained in:
ChristopherHX
2025-09-27 00:04:03 +02:00
committed by GitHub
parent 67f0e3d852
commit 9c2f3e9f70
2 changed files with 23 additions and 4 deletions

View File

@@ -6,25 +6,33 @@ import (
"gopkg.in/yaml.v3"
)
// Assumes there is no cycle ensured via test TestVerifyCycleIsInvalid
func resolveAliases(node *yaml.Node) error {
func resolveAliasesExt(node *yaml.Node, path map[*yaml.Node]bool, skipCheck bool) error {
if !skipCheck && path[node] {
return errors.New("circular alias")
}
switch node.Kind {
case yaml.AliasNode:
aliasTarget := node.Alias
if aliasTarget == nil {
return errors.New("unresolved alias node")
}
path[node] = true
*node = *aliasTarget
if err := resolveAliases(node); err != nil {
if err := resolveAliasesExt(node, path, true); err != nil {
return err
}
delete(path, aliasTarget)
case yaml.DocumentNode, yaml.MappingNode, yaml.SequenceNode:
for _, child := range node.Content {
if err := resolveAliases(child); err != nil {
if err := resolveAliasesExt(child, path, false); err != nil {
return err
}
}
}
return nil
}
func resolveAliases(node *yaml.Node) error {
return resolveAliasesExt(node, map[*yaml.Node]bool{}, false)
}

View File

@@ -19,6 +19,17 @@ b: &b
assert.Error(t, err)
}
func TestVerifyCycleIsInvalid2(t *testing.T) {
var node yaml.Node
err := yaml.Unmarshal([]byte(`
a: &a
ref: *a
`), &node)
assert.NoError(t, err)
err = resolveAliases(&node)
assert.Error(t, err)
}
func TestVerifyNilAliasError(t *testing.T) {
var node yaml.Node
err := yaml.Unmarshal([]byte(`