diff --git a/aliases.go b/aliases.go index fde9cb1..2835249 100644 --- a/aliases.go +++ b/aliases.go @@ -1,15 +1,39 @@ package publiccode import ( + "fmt" + "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. +// Files that reuse a few values stay far below this. const maxAliasNodes = 10_000 +// maxAliasBytes bounds the scalar content copied by aliases. Strings can +// share memory during decoding but are written in full at every YAML export. +const maxAliasBytes = 4 << 20 + +type aliasSize struct { + nodes int + bytes int +} + +func (s aliasSize) add(other aliasSize) aliasSize { + return aliasSize{ + nodes: min(s.nodes+other.nodes, maxAliasNodes+1), + bytes: min(s.bytes+other.bytes, maxAliasBytes+1), + } +} + +type aliasOverflow struct { + *ast.AliasNode + + description string +} + // 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 @@ -50,21 +74,21 @@ func (a anchorIndex) resolve(alias *ast.AliasNode) *ast.AnchorNode { } // aliasExpansion counts the nodes a document has once its aliases are -// expanded, in time linear in the size of the document. +// expanded, including their scalar bytes, in time linear in the document size. type aliasExpansion struct { anchors anchorIndex - sizes map[*ast.AnchorNode]int + sizes map[*ast.AnchorNode]aliasSize inside map[*ast.AnchorNode]bool - added int - over *ast.AliasNode + added aliasSize + over *aliasOverflow } -// 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 { +// findAliasOverflow returns the alias that takes expansion past either +// budget, in source order, or nil. +func findAliasOverflow(node ast.Node) *aliasOverflow { e := aliasExpansion{ anchors: indexAnchors(node), - sizes: map[*ast.AnchorNode]int{}, + sizes: map[*ast.AnchorNode]aliasSize{}, inside: map[*ast.AnchorNode]bool{}, } ast.Walk(&e, node) @@ -83,20 +107,22 @@ func (e *aliasExpansion) Visit(node ast.Node) ast.Visitor { return e } - e.added = saturatingAdd(e.added, e.size(alias)) - if e.added > maxAliasNodes { - e.over = alias + e.added = e.added.add(e.size(alias)) + if e.added.nodes > maxAliasNodes { + e.over = &aliasOverflow{alias, fmt.Sprintf("YAML aliases expand to more than %d nodes", maxAliasNodes)} + } else if e.added.bytes > maxAliasBytes { + e.over = &aliasOverflow{alias, fmt.Sprintf("YAML aliases expand to more than %d scalar bytes", maxAliasBytes)} } 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 { +// size returns the nodes and scalar bytes under node with aliases expanded, +// capped just past their respective limits. +func (e *aliasExpansion) size(node ast.Node) aliasSize { switch n := node.(type) { case nil: - return 0 + return aliasSize{} case *ast.DocumentNode: return e.size(n.Body) case *ast.TagNode: @@ -106,34 +132,38 @@ func (e *aliasExpansion) size(node ast.Node) int { case *ast.AliasNode: anchor := e.anchors.resolve(n) if anchor == nil { - return 1 + return aliasSize{nodes: 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)) + return e.size(n.Key).add(e.size(n.Value)) case *ast.MappingNode: - total := 1 + total := aliasSize{nodes: 1} for _, value := range n.Values { - total = saturatingAdd(total, e.size(value)) + total = total.add(e.size(value)) } return total case *ast.SequenceNode: - total := 1 + total := aliasSize{nodes: 1} for _, value := range n.Values { - total = saturatingAdd(total, e.size(value)) + total = total.add(e.size(value)) } return total + case *ast.StringNode: + return aliasSize{nodes: 1, bytes: min(len(n.Value), maxAliasBytes+1)} + case *ast.LiteralNode: + return e.size(n.Value) default: - return 1 + return aliasSize{nodes: 1, bytes: min(len(n.GetToken().Value), maxAliasBytes+1)} } } -func (e *aliasExpansion) anchorSize(anchor *ast.AnchorNode) int { +func (e *aliasExpansion) anchorSize(anchor *ast.AnchorNode) aliasSize { if size, ok := e.sizes[anchor]; ok { return size } @@ -141,7 +171,7 @@ func (e *aliasExpansion) anchorSize(anchor *ast.AnchorNode) int { // An anchor can hold an alias of itself, "&a [*a]", which the decoder // doesn't expand. if e.inside[anchor] { - return 1 + return aliasSize{nodes: 1} } e.inside[anchor] = true @@ -152,7 +182,3 @@ func (e *aliasExpansion) anchorSize(anchor *ast.AnchorNode) int { return size } - -func saturatingAdd(a, b int) int { - return min(a+b, maxAliasNodes+1) -} diff --git a/aliases_test.go b/aliases_test.go index 2aba9af..936891e 100644 --- a/aliases_test.go +++ b/aliases_test.go @@ -76,3 +76,50 @@ func TestFindAliasOverflow(t *testing.T) { }) } } + +func TestAliasScalarByteBudget(t *testing.T) { + for _, scalar := range []struct { + name string + yaml string + }{ + {"plain", strings.Repeat("x", 1024)}, + {"quoted escapes", `"` + strings.Repeat(`\u0078`, 1024) + `"`}, + {"multibyte", strings.Repeat("é", 512)}, + {"literal", "|\n " + strings.Repeat("x", 1023) + "\n"}, + {"folded", ">\n " + strings.Repeat("x", 1023) + "\n"}, + {"tagged", "!!str " + strings.Repeat("x", 1024)}, + } { + t.Run(scalar.name, func(t *testing.T) { + for _, count := range []int{maxAliasBytes / 1024, maxAliasBytes/1024 + 1} { + source := "a: &a " + scalar.yaml + "\nb:\n" + strings.Repeat(" - *a\n", count) + file, err := parser.ParseBytes([]byte(source), 0) + if err != nil { + t.Fatal(err) + } + over := findAliasOverflow(file.Docs[0].Body) + if count == maxAliasBytes/1024 { + if over != nil { + t.Fatalf("rejected exact byte limit: %s", over.description) + } + } else if over == nil || over.description != "YAML aliases expand to more than 4194304 scalar bytes" { + t.Fatalf("expected scalar byte overflow, got %#v", over) + } + } + }) + } +} + +func TestAliasScalarBytesInCollections(t *testing.T) { + for _, source := range []string{ + "a: &a " + strings.Repeat("x", 1024) + "\nb: &b [*a, *a]\nc:\n" + strings.Repeat(" - *b\n", 2048), + "a: &a {" + strings.Repeat("x", 2048) + ": y}\nb:\n" + strings.Repeat(" - {<<: *a}\n", 2048), + } { + file, err := parser.ParseBytes([]byte(source), 0) + if err != nil { + t.Fatal(err) + } + if over := findAliasOverflow(file.Docs[0].Body); over == nil || over.description != "YAML aliases expand to more than 4194304 scalar bytes" { + t.Fatalf("expected scalar byte overflow, got %#v", over) + } + } +} diff --git a/parser.go b/parser.go index dae8d71..f8c0792 100644 --- a/parser.go +++ b/parser.go @@ -425,7 +425,7 @@ func (p *Parser) parseAndValidate( //nolint:maintidx 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), + Description: alias.description, Line: tok.Position.Line, Column: tok.Position.Column, }} diff --git a/parser_internal_test.go b/parser_internal_test.go index 4ef01fe..18e1496 100644 --- a/parser_internal_test.go +++ b/parser_internal_test.go @@ -482,3 +482,28 @@ func TestGetPositionInAnchoredMapping(t *testing.T) { }) } } + +func TestParseRejectsAliasedLongStrings(t *testing.T) { + p, err := NewParser(ParserConfig{DisableExternalChecks: true}) + if err != nil { + t.Fatal(err) + } + source := "publiccodeYmlVersion: '0'\ndescription:\n en:\n features:\n - &f " + strings.Repeat("x", 1024) + "\n" + strings.Repeat(" - *f\n", maxAliasBytes/1024+1) + pc, err := p.ParseStream(strings.NewReader(source)) + if pc != nil { + t.Fatal("returned a document with excessive alias expansion") + } + var results ValidationResults + if !errors.As(err, &results) || len(results) != 1 { + t.Fatalf("expected one validation error, got %v", err) + } + want := ValidationError{ + Key: "description.en.features[4097]", + Description: "YAML aliases expand to more than 4194304 scalar bytes", + Line: 4102, + Column: 9, + } + if !errors.Is(results[0], want) { + t.Fatalf("got %#v, want %#v", results[0], want) + } +}