diff --git a/aliases.go b/aliases.go new file mode 100644 index 0000000..fde9cb1 --- /dev/null +++ b/aliases.go @@ -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) +} diff --git a/aliases_test.go b/aliases_test.go new file mode 100644 index 0000000..2aba9af --- /dev/null +++ b/aliases_test.go @@ -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) + } + }) + } +} diff --git a/parser.go b/parser.go index 95671f4..98f4af3 100644 --- a/parser.go +++ b/parser.go @@ -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 { diff --git a/testdata/v0/invalid/aliases_nested.yml b/testdata/v0/invalid/aliases_nested.yml new file mode 100644 index 0000000..0d3d8a7 --- /dev/null +++ b/testdata/v0/invalid/aliases_nested.yml @@ -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 diff --git a/testdata/v0/valid/no-network/valid_with_aliases.yml b/testdata/v0/valid/no-network/valid_with_aliases.yml new file mode 100644 index 0000000..b98f98b --- /dev/null +++ b/testdata/v0/valid/no-network/valid_with_aliases.yml @@ -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 diff --git a/unknown_keys.go b/unknown_keys.go index 18763ad..f06067a 100644 --- a/unknown_keys.go +++ b/unknown_keys.go @@ -28,7 +28,7 @@ type unknownKey struct { // struct that has one, and picks it by ranging over a map, so it can't tell // a user about every unknown key, nor always about the same one. type unknownKeyFinder struct { - anchors map[string][]*ast.AnchorNode + anchors anchorIndex inside map[ast.Node]bool visited map[visit]bool seen map[*token.Token]bool @@ -61,12 +61,11 @@ var nonStringTags = []token.ReservedTagKeyword{ func findUnknownKeys(node ast.Node, typ reflect.Type) []unknownKey { f := unknownKeyFinder{ - anchors: map[string][]*ast.AnchorNode{}, + anchors: indexAnchors(node), inside: map[ast.Node]bool{}, visited: map[visit]bool{}, seen: map[*token.Token]bool{}, } - ast.Walk(&f, node) f.walk(node, typ, "") // Keys brought in by merge keys come up where they are merged. @@ -77,37 +76,6 @@ func findUnknownKeys(node ast.Node, typ reflect.Type) []unknownKey { return f.keys } -// Visit collects the anchors of the document in source order, including -// those under unknown keys, which the walk against the type never reaches. -// -//nolint:ireturn // ast.Walk needs a Visitor back. -func (f *unknownKeyFinder) Visit(node ast.Node) ast.Visitor { - if anchor, ok := node.(*ast.AnchorNode); ok { - name := anchor.Name.GetToken().Value - f.anchors[name] = append(f.anchors[name], anchor) - } - - return f -} - -// 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 (f *unknownKeyFinder) resolve(alias *ast.AliasNode) *ast.AnchorNode { - tok := alias.Value.GetToken() - - var target *ast.AnchorNode - - for _, anchor := range f.anchors[tok.Value] { - if anchor.GetToken().Position.Offset >= tok.Position.Offset { - break - } - - target = anchor - } - - return target -} - // hasCustomUnmarshaler reports whether go-yaml hands values of typ to the // type itself, which then decides on its own which keys it accepts. func hasCustomUnmarshaler(typ reflect.Type) bool { @@ -137,7 +105,7 @@ func (f *unknownKeyFinder) walk(node ast.Node, typ reflect.Type, path string) { return case *ast.AliasNode: - if anchor := f.resolve(n); anchor != nil { + if anchor := f.anchors.resolve(n); anchor != nil { f.walk(anchor.Value, typ, path) } @@ -213,7 +181,7 @@ func (f *unknownKeyFinder) eachKey(node ast.Node, fn func(name string, tok *toke case *ast.AnchorNode: f.eachKey(n.Value, fn) case *ast.AliasNode: - if anchor := f.resolve(n); anchor != nil { + if anchor := f.anchors.resolve(n); anchor != nil { f.eachKey(anchor.Value, fn) } case *ast.SequenceNode: @@ -251,7 +219,7 @@ func (f *unknownKeyFinder) keyName(key ast.Node) (string, bool) { case *ast.AnchorNode: return f.keyName(n.Value) case *ast.AliasNode: - if anchor := f.resolve(n); anchor != nil { + if anchor := f.anchors.resolve(n); anchor != nil { return f.keyName(anchor.Value) } case *ast.TagNode: diff --git a/v0_test.go b/v0_test.go index 37e00b2..fa70d28 100644 --- a/v0_test.go +++ b/v0_test.go @@ -616,6 +616,9 @@ func TestInvalidTestcasesV0(t *testing.T) { }, // misc + "aliases_nested.yml": ValidationResults{ + ValidationError{"", "zl7", "YAML aliases expand to more than 10000 nodes", 61, 16}, + }, "file_encoding.yml": ValidationResults{ValidationError{"", "", "Invalid UTF-8", 0, 0}}, "invalid_yaml.yml": ValidationResults{ValidationError{"", "", "value is not allowed in this context. map key-value is pre-defined", 38, 1}}, "mostly_empty.yml": ValidationResults{