Skip to content
Closed
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
158 changes: 158 additions & 0 deletions aliases.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package publiccode

import (
"github.com/goccy/go-yaml/ast"
)

// maxAliasNodes is how many nodes the aliases of a document may add to it
// once expanded. The decoder copies the anchored value at each alias, so
// anchors that alias each other grow a small document exponentially.
// Manifests that reuse a few values stay far below this.
const maxAliasNodes = 10_000

// anchorIndex maps anchor names to the anchors with that name, in source
// order, including those under keys a decode never reaches.
type anchorIndex map[string][]*ast.AnchorNode

func indexAnchors(node ast.Node) anchorIndex {
anchors := anchorIndex{}
ast.Walk(anchors, node)

return anchors
}

//nolint:ireturn // ast.Walk needs a Visitor back.
func (a anchorIndex) Visit(node ast.Node) ast.Visitor {
if anchor, ok := node.(*ast.AnchorNode); ok {
name := anchor.Name.GetToken().Value
a[name] = append(a[name], anchor)
}

return a
}

// resolve returns the last anchor named like the alias that precedes it,
// as YAML says an alias refers to the most recent anchor, or nil.
func (a anchorIndex) resolve(alias *ast.AliasNode) *ast.AnchorNode {
tok := alias.Value.GetToken()

var target *ast.AnchorNode

for _, anchor := range a[tok.Value] {
if anchor.GetToken().Position.Offset >= tok.Position.Offset {
break
}

target = anchor
}

return target
}

// aliasExpansion counts the nodes a document has once its aliases are
// expanded, in time linear in the size of the document.
type aliasExpansion struct {
anchors anchorIndex
sizes map[*ast.AnchorNode]int
inside map[*ast.AnchorNode]bool
added int
over *ast.AliasNode
}

// findAliasOverflow returns the alias that takes the nodes added by alias
// expansion past maxAliasNodes, in source order, or nil.
func findAliasOverflow(node ast.Node) *ast.AliasNode {
e := aliasExpansion{
anchors: indexAnchors(node),
sizes: map[*ast.AnchorNode]int{},
inside: map[*ast.AnchorNode]bool{},
}
ast.Walk(&e, node)

return e.over
}

//nolint:ireturn // ast.Walk needs a Visitor back.
func (e *aliasExpansion) Visit(node ast.Node) ast.Visitor {
if e.over != nil {
return nil
}

alias, ok := node.(*ast.AliasNode)
if !ok {
return e
}

e.added = saturatingAdd(e.added, e.size(alias))
if e.added > maxAliasNodes {
e.over = alias
}

return nil
}

// size returns the number of nodes under node with aliases expanded,
// capped just past maxAliasNodes.
func (e *aliasExpansion) size(node ast.Node) int {
switch n := node.(type) {
case nil:
return 0
case *ast.DocumentNode:
return e.size(n.Body)
case *ast.TagNode:
return e.size(n.Value)
case *ast.AnchorNode:
return e.anchorSize(n)
case *ast.AliasNode:
anchor := e.anchors.resolve(n)
if anchor == nil {
return 1
}

return e.anchorSize(anchor)
case *ast.MappingKeyNode:
return e.size(n.Value)
case *ast.MappingValueNode:
return saturatingAdd(e.size(n.Key), e.size(n.Value))
case *ast.MappingNode:
total := 1
for _, value := range n.Values {
total = saturatingAdd(total, e.size(value))
}

return total
case *ast.SequenceNode:
total := 1
for _, value := range n.Values {
total = saturatingAdd(total, e.size(value))
}

return total
default:
return 1
}
}

func (e *aliasExpansion) anchorSize(anchor *ast.AnchorNode) int {
if size, ok := e.sizes[anchor]; ok {
return size
}

// An anchor can hold an alias of itself, "&a [*a]", which the decoder
// doesn't expand.
if e.inside[anchor] {
return 1
}

e.inside[anchor] = true
size := e.size(anchor.Value)
delete(e.inside, anchor)

e.sizes[anchor] = size

return size
}

func saturatingAdd(a, b int) int {
return min(a+b, maxAliasNodes+1)
}
78 changes: 78 additions & 0 deletions aliases_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package publiccode

import (
"fmt"
"strings"
"testing"

"github.com/goccy/go-yaml/parser"
)

// sequenceOf returns a flow sequence of n scalars.
func sequenceOf(n int) string {
return "[" + strings.TrimSuffix(strings.Repeat("x, ", n), ", ") + "]"
}

func TestFindAliasOverflow(t *testing.T) {
// Each level aliases the one before three times.
var nested strings.Builder

nested.WriteString("l0: &l0 [a, b, c]\n")

for i := 1; i < 60; i++ {
fmt.Fprintf(&nested, "l%d: &l%d [*l%d, *l%d, *l%d]\n", i, i, i-1, i-1, i-1)
}

nested.WriteString("last: *l59\n")

tests := []struct {
name string
yaml string
// line of the alias reported, 0 for none
line int
}{
{"no aliases", "a: [x, y]\nb: {c: d}\n", 0},
{
// The sequence and its entries make maxAliasNodes nodes.
"at the limit",
"a: &a " + sequenceOf(maxAliasNodes-1) + "\nb: *a\n",
0,
},
{
"past the limit",
"a: &a " + sequenceOf(maxAliasNodes-1) + "\nb: *a\ns: &s x\nc: *s\n",
4,
},
{
"merge keys",
"a: &a {k: " + sequenceOf(maxAliasNodes/2) + "}\nb: {<<: *a}\nc: {<<: *a}\n",
3,
},
{
"latest anchor",
"a: &a " + sequenceOf(maxAliasNodes) + "\nb: &a x\nc: *a\nd: *a\n",
0,
},
{"alias of its own anchor", "a: &a [x, *a]\nb: &b {<<: *b}\n", 0},
{"unknown anchor", "a: *nope\n", 0},
{"nested", nested.String(), 8},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file, err := parser.ParseBytes([]byte(tt.yaml), 0)
if err != nil {
t.Fatalf("unexpected parse error: %v", err)
}

line := 0
if alias := findAliasOverflow(file.Docs[0].Body); alias != nil {
line = alias.GetToken().Position.Line
}

if line != tt.line {
t.Errorf("got alias at line %d, want %d", line, tt.line)
}
})
}
}
13 changes: 13 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,19 @@ func (p *Parser) parseAndValidate(in io.Reader, fileURL *url.URL) (PublicCode, e
return nil, ValidationResults{newValidationError("", "multiple YAML documents in one file are not supported")}
}

// Decoding copies the value at each alias, so check how much the
// aliases add before decoding anything.
if alias := findAliasOverflow(file.Docs[0].Body); alias != nil {
tok := alias.GetToken()

return nil, ValidationResults{ValidationError{
Key: findKeyAtLine(file.Docs[0].Body, tok.Position.Line, ""),
Description: fmt.Sprintf("YAML aliases expand to more than %d nodes", maxAliasNodes),
Line: tok.Position.Line,
Column: tok.Position.Column,
}}
}

// Extract publiccodeYmlVersion from the AST.
versionPath, err := yaml.PathString("$.publiccodeYmlVersion")
if err != nil {
Expand Down
74 changes: 74 additions & 0 deletions testdata/v0/invalid/aliases_nested.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
publiccodeYmlVersion: "0"

name: Medusa
url: "https://github.com/italia/developers.italia.it.git"

platforms:
- web

categories:
- cloud-management

developmentStatus: development

softwareType: "standalone/other"

description:
en-GB:
localisedName: Medusa
shortDescription: >
A rather short description which
is probably useless
longDescription: >
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 158 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 316 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 474 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 632 characters.
features:
- Just one feature

legal:
license: AGPL-3.0-or-later

maintenance:
type: "community"

contacts:
- name: Francesco Rossi

localisation:
localisationReady: true
availableLanguages:
- en

# Each level aliases the one before three times, so usedBy expands
# to 3^20 entries.
zl0: &l0 [a, b, c]
zl1: &l1 [*l0, *l0, *l0]
zl2: &l2 [*l1, *l1, *l1]
zl3: &l3 [*l2, *l2, *l2]
zl4: &l4 [*l3, *l3, *l3]
zl5: &l5 [*l4, *l4, *l4]
zl6: &l6 [*l5, *l5, *l5]
zl7: &l7 [*l6, *l6, *l6]
zl8: &l8 [*l7, *l7, *l7]
zl9: &l9 [*l8, *l8, *l8]
zl10: &l10 [*l9, *l9, *l9]
zl11: &l11 [*l10, *l10, *l10]
zl12: &l12 [*l11, *l11, *l11]
zl13: &l13 [*l12, *l12, *l12]
zl14: &l14 [*l13, *l13, *l13]
zl15: &l15 [*l14, *l14, *l14]
zl16: &l16 [*l15, *l15, *l15]
zl17: &l17 [*l16, *l16, *l16]
zl18: &l18 [*l17, *l17, *l17]
zl19: &l19 [*l18, *l18, *l18]
usedBy: *l19
55 changes: 55 additions & 0 deletions testdata/v0/valid/no-network/valid_with_aliases.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
publiccodeYmlVersion: "0"

name: Medusa
url: "https://github.com/italia/developers.italia.it.git"

platforms:
- &web web

categories:
- cloud-management

developmentStatus: development

softwareType: "standalone/other"

description:
en-GB: &description
localisedName: Medusa
shortDescription: >
A rather short description which
is probably useless
longDescription: >
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 158 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 316 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 474 characters.
Very long description of this software, also split
on multiple rows. You should note what the software
is and why one should need it. This is 632 characters.
features:
- Just one feature
en-US: *description

legal:
license: AGPL-3.0-or-later

maintenance:
type: "contract"

contractors:
- name: &contractor Fornitore Srl
until: "2099-01-01"

contacts:
- name: *contractor

localisation:
localisationReady: true
availableLanguages:
- en
Loading