From 3167b3e95bcf22f0eda1bd57a4115bf1e320982a Mon Sep 17 00:00:00 2001 From: Fabio Bonelli Date: Fri, 27 Nov 2026 13:34:06 +0000 Subject: [PATCH] fix: report every unknown key in source order go-yaml stops at the first unknown key of the first struct that has one, and picks it from a map, so a publiccode.yml file with several unknown keys got one error naming a different key from run to run. Fixing such a file took one run per key, and CI logs changed for the same input. --- parser.go | 83 ++++--- parser_internal_test.go | 97 ++++++++ testdata/v0/invalid/unknown_fields.yml | 58 +++++ unknown_keys.go | 325 +++++++++++++++++++++++++ v0_test.go | 8 + 5 files changed, 539 insertions(+), 32 deletions(-) create mode 100644 testdata/v0/invalid/unknown_fields.yml create mode 100644 unknown_keys.go diff --git a/parser.go b/parser.go index ce1a282..95671f4 100644 --- a/parser.go +++ b/parser.go @@ -11,6 +11,7 @@ import ( "os" "path" "path/filepath" + "reflect" "regexp" "slices" "strings" @@ -804,42 +805,60 @@ func decode[T any](data []byte, publiccode *T, file *ast.File) (ve ValidationRes d := yaml.NewDecoder(bytes.NewReader(data), yaml.DisallowUnknownField()) - if err := d.Decode(publiccode); err != nil { - var ( - unknownErr *yaml.UnknownFieldError - yamlErr yaml.Error - ) + err := d.Decode(publiccode) + if err == nil { + return ve + } - switch { - case errors.As(err, &unknownErr): - line := 0 - if unknownErr.Token != nil { - line = unknownErr.Token.Position.Line - } + // The decoder reports one unknown key at most and stops at the first + // error, so look for all of them whatever error it returned. + for _, key := range findUnknownKeys(file.Docs[0].Body, reflect.TypeFor[T]()) { + ve = append(ve, ValidationError{ + Key: key.path, + Description: fmt.Sprintf("unknown field %q", key.name), + Line: key.token.Position.Line, + Column: 1, + }) + } - key := findKeyAtLine(file.Docs[0].Body, line, "") - ve = append(ve, ValidationError{ - Key: key, - Description: unknownErr.Message, - Line: line, - Column: 1, - }) - case errors.As(err, &yamlErr): - line := 0 - if tok := yamlErr.GetToken(); tok != nil { - line = tok.Position.Line - } + var ( + unknownErr *yaml.UnknownFieldError + yamlErr yaml.Error + ) - key := findKeyAtLine(file.Docs[0].Body, line, "") - ve = append(ve, ValidationError{ - Key: key, - Description: "wrong type for this field", - Line: line, - Column: 1, - }) - default: - ve = append(ve, newValidationError("", err.Error())) + switch { + case errors.As(err, &unknownErr): + if len(ve) > 0 { + break + } + + line := 0 + if unknownErr.Token != nil { + line = unknownErr.Token.Position.Line + } + + key := findKeyAtLine(file.Docs[0].Body, line, "") + ve = append(ve, ValidationError{ + Key: key, + Description: unknownErr.Message, + Line: line, + Column: 1, + }) + case errors.As(err, &yamlErr): + line := 0 + if tok := yamlErr.GetToken(); tok != nil { + line = tok.Position.Line } + + key := findKeyAtLine(file.Docs[0].Body, line, "") + ve = append(ve, ValidationError{ + Key: key, + Description: "wrong type for this field", + Line: line, + Column: 1, + }) + default: + ve = append(ve, newValidationError("", err.Error())) } return ve diff --git a/parser_internal_test.go b/parser_internal_test.go index b50df37..d5199c7 100644 --- a/parser_internal_test.go +++ b/parser_internal_test.go @@ -73,6 +73,103 @@ name: } } +func TestDecodeReportsEveryUnknownKey(t *testing.T) { + tests := map[string]struct { + yaml string + want ValidationResults + }{ + "keys in a flow mapping": { + yaml: `publiccodeYmlVersion: "0" +legal: {license: MIT, b: 1, a: 2} +`, + want: ValidationResults{ + ValidationError{"", "legal.b", `unknown field "b"`, 2, 1}, + ValidationError{"", "legal.a", `unknown field "a"`, 2, 1}, + }, + }, + "key of an anchor used twice": { + yaml: `publiccodeYmlVersion: "0" +fundedBy: + - &org {uri: "urn:x-test:a", foo: 1} + - *org +`, + want: ValidationResults{ + ValidationError{"", "fundedBy[0].foo", `unknown field "foo"`, 3, 1}, + }, + }, + "key brought in by a merge key": { + yaml: `publiccodeYmlVersion: "0" +x: &base {type: internal, bar: 1} +maintenance: + <<: *base + baz: 2 +`, + want: ValidationResults{ + ValidationError{"", "x", `unknown field "x"`, 2, 1}, + ValidationError{"", "maintenance.bar", `unknown field "bar"`, 2, 1}, + ValidationError{"", "maintenance.baz", `unknown field "baz"`, 5, 1}, + }, + }, + "anchor holding an alias of itself": { + yaml: `publiccodeYmlVersion: "0" +fundedBy: &x [*x] +foo: 1 +`, + want: ValidationResults{ + ValidationError{"", "foo", `unknown field "foo"`, 3, 1}, + ValidationError{"", "fundedBy", "wrong type for this field", 2, 1}, + }, + }, + "mapping merging an alias of itself": { + yaml: `publiccodeYmlVersion: "0" +maintenance: &x {type: internal, foo: 1, <<: *x} +`, + want: ValidationResults{ + ValidationError{"", "maintenance.foo", `unknown field "foo"`, 2, 1}, + newValidationError("", "cannot find anchor by alias name x"), + }, + }, + "tagged, quoted and anchored keys": { + yaml: `publiccodeYmlVersion: "0" +!!str zzTagged: 1 +"zzQuoted": 2 +&k zzAnchored: 3 +!!str 4: 4 +`, + want: ValidationResults{ + ValidationError{"", "zzTagged", `unknown field "zzTagged"`, 2, 1}, + ValidationError{"", "zzQuoted", `unknown field "zzQuoted"`, 3, 1}, + ValidationError{"", "zzAnchored", `unknown field "zzAnchored"`, 4, 1}, + ValidationError{"", "4", `unknown field "4"`, 5, 1}, + }, + }, + "key next to a wrong type": { + yaml: `publiccodeYmlVersion: "0" +name: [a] +foo: 1 +`, + want: ValidationResults{ + ValidationError{"", "foo", `unknown field "foo"`, 3, 1}, + ValidationError{"", "name", "wrong type for this field", 2, 1}, + }, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + file, err := parser.ParseBytes([]byte(test.yaml), 0) + if err != nil { + t.Fatalf("unexpected parse error: %v", err) + } + + got := decode([]byte(test.yaml), &PublicCodeV0{}, file) + if got.Error() != test.want.Error() { + t.Errorf("got:\n%v\nwant:\n%v", got, test.want) + } + }) + } +} + func TestToURLLocalPath(t *testing.T) { // toURL with a local file path should return a file:// URL. u, err := toURL("./testdata/v0/valid/valid.yml") diff --git a/testdata/v0/invalid/unknown_fields.yml b/testdata/v0/invalid/unknown_fields.yml new file mode 100644 index 0000000..33ffcb6 --- /dev/null +++ b/testdata/v0/invalid/unknown_fields.yml @@ -0,0 +1,58 @@ +publiccodeYmlVersion: "0" + +name: Medusa +url: "https://github.com/italia/developers.italia.it.git" + +# Should NOT validate: none of the keys named zzz* exist in publiccode.yml, +# and each must get its own error. +zzzTop: 1 + +platforms: + - web + +categories: + - cloud-management + +developmentStatus: development + +softwareType: "standalone/other" + +description: + en-GB: + localisedName: Medusa + zzzDescription: 2 + 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 + zzzContact: 3 + +localisation: + localisationReady: true + availableLanguages: + - en + +zzzLast: 4 diff --git a/unknown_keys.go b/unknown_keys.go new file mode 100644 index 0000000..18763ad --- /dev/null +++ b/unknown_keys.go @@ -0,0 +1,325 @@ +package publiccode + +import ( + "cmp" + "encoding" + "fmt" + "maps" + "reflect" + "slices" + "strings" + + "github.com/goccy/go-yaml" + "github.com/goccy/go-yaml/ast" + "github.com/goccy/go-yaml/token" +) + +// unknownKey is a mapping key the decoder has no struct field for. +type unknownKey struct { + path string + name string + token *token.Token +} + +// unknownKeyFinder walks a YAML document against the Go type it decodes into +// and collects every key without a matching field, in source order. +// +// go-yaml's DisallowUnknownField stops at the first unknown key of the first +// 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 + inside map[ast.Node]bool + visited map[visit]bool + seen map[*token.Token]bool + keys []unknownKey +} + +type visit struct { + node ast.Node + typ reflect.Type +} + +// unmarshalerTypes are the interfaces go-yaml hands a value to instead of +// decoding it field by field. +var unmarshalerTypes = []reflect.Type{ + reflect.TypeFor[yaml.BytesUnmarshaler](), + reflect.TypeFor[yaml.BytesUnmarshalerContext](), + reflect.TypeFor[yaml.InterfaceUnmarshaler](), + reflect.TypeFor[yaml.InterfaceUnmarshalerContext](), + reflect.TypeFor[yaml.NodeUnmarshaler](), + reflect.TypeFor[yaml.NodeUnmarshalerContext](), + reflect.TypeFor[encoding.TextUnmarshaler](), +} + +// nonStringTags are the tags that turn a key into something other than a +// string, which the decoder then can't match against a field name. +var nonStringTags = []token.ReservedTagKeyword{ + token.IntegerTag, token.FloatTag, token.NullTag, + token.BinaryTag, token.BooleanTag, token.TimestampTag, +} + +func findUnknownKeys(node ast.Node, typ reflect.Type) []unknownKey { + f := unknownKeyFinder{ + anchors: map[string][]*ast.AnchorNode{}, + 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. + slices.SortStableFunc(f.keys, func(a, b unknownKey) int { + return cmp.Compare(a.token.Position.Offset, b.token.Position.Offset) + }) + + 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 { + ptr := reflect.PointerTo(typ) + + return slices.ContainsFunc(unmarshalerTypes, ptr.Implements) +} + +func (f *unknownKeyFinder) walk(node ast.Node, typ reflect.Type, path string) { + for typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + + switch n := node.(type) { + case nil: + return + case *ast.DocumentNode: + f.walk(n.Body, typ, path) + + return + case *ast.TagNode: + f.walk(n.Value, typ, path) + + return + case *ast.AnchorNode: + f.walk(n.Value, typ, path) + + return + case *ast.AliasNode: + if anchor := f.resolve(n); anchor != nil { + f.walk(anchor.Value, typ, path) + } + + return + } + + // Each node is checked once per type: aliases can make the same + // mapping reachable many times over. + v := visit{node: node, typ: typ} + if f.visited[v] { + return + } + + f.visited[v] = true + + if hasCustomUnmarshaler(typ) { + return + } + + switch typ.Kind() { //nolint:exhaustive // other kinds hold no mapping keys + case reflect.Struct: + f.walkStruct(node, typ, path) + case reflect.Map: + f.walkMap(node, typ.Elem(), path) + case reflect.Slice, reflect.Array: + if seq, ok := node.(*ast.SequenceNode); ok { + for i, entry := range seq.Values { + f.walk(entry, typ.Elem(), fmt.Sprintf("%s[%d]", path, i)) + } + } + } +} + +func (f *unknownKeyFinder) walkMap(node ast.Node, elem reflect.Type, path string) { + f.eachKey(node, func(name string, _ *token.Token, value ast.Node) { + f.walk(value, elem, joinKey(path, name)) + }) +} + +func (f *unknownKeyFinder) walkStruct(node ast.Node, typ reflect.Type, path string) { + fields := structFields(typ) + + f.eachKey(node, func(name string, tok *token.Token, value ast.Node) { + field, ok := fields[name] + if !ok { + // Report a key once, however many aliases lead to it. + if tok != nil && !f.seen[tok] { + f.seen[tok] = true + f.keys = append(f.keys, unknownKey{path: joinKey(path, name), name: name, token: tok}) + } + + return + } + + f.walk(value, field, joinKey(path, name)) + }) +} + +// eachKey calls fn for every key of a mapping, following merge keys +// into the mappings they merge, like the decoder does. +func (f *unknownKeyFinder) eachKey(node ast.Node, fn func(name string, tok *token.Token, value ast.Node)) { + // A node can merge an alias of itself: "&a {<<: *a}" or "&a [*a]". + if node == nil || f.inside[node] { + return + } + + f.inside[node] = true + defer delete(f.inside, node) + + switch n := node.(type) { + case *ast.TagNode: + f.eachKey(n.Value, fn) + case *ast.AnchorNode: + f.eachKey(n.Value, fn) + case *ast.AliasNode: + if anchor := f.resolve(n); anchor != nil { + f.eachKey(anchor.Value, fn) + } + case *ast.SequenceNode: + // Only reached through a merge key: "<<: [*a, *b]". + for _, entry := range n.Values { + f.eachKey(entry, fn) + } + case ast.MapNode: + iter := n.MapRange() + for iter.Next() { + key := iter.Key() + if key.IsMergeKey() { + f.eachKey(iter.Value(), fn) + + continue + } + + // The decoder only matches string keys against field names. + name, ok := f.keyName(key) + if !ok { + continue + } + + fn(name, key.GetToken(), iter.Value()) + } + } +} + +// keyName returns the string the decoder turns a mapping key into, looking +// through tags, anchors and aliases, or false if the key is not a string. +func (f *unknownKeyFinder) keyName(key ast.Node) (string, bool) { + switch n := key.(type) { + case *ast.StringNode: + return n.Value, true + case *ast.AnchorNode: + return f.keyName(n.Value) + case *ast.AliasNode: + if anchor := f.resolve(n); anchor != nil { + return f.keyName(anchor.Value) + } + case *ast.TagNode: + tag := token.ReservedTagKeyword(n.Start.Value) + if n.Directive == nil && slices.Contains(nonStringTags, tag) { + return "", false + } + + if n.Directive == nil && tag != token.StringTag { + return f.keyName(n.Value) + } + + // "!!str 1" is the string "1". + if name, ok := f.keyName(n.Value); ok { + return name, true + } + + if scalar, ok := n.Value.(ast.ScalarNode); ok && scalar.GetValue() != nil { + return fmt.Sprint(scalar.GetValue()), true + } + } + + return "", false +} + +// structFields maps the YAML key of every field of typ, including the +// fields of inline structs, to its type, following go-yaml's naming rules. +func structFields(typ reflect.Type) map[string]reflect.Type { + fields := map[string]reflect.Type{} + + for field := range typ.Fields() { + tag := field.Tag.Get("yaml") + if tag == "" { + tag = field.Tag.Get("json") + } + + if tag == "-" || (field.PkgPath != "" && !field.Anonymous) { + continue + } + + name, options, _ := strings.Cut(tag, ",") + if name == "" { + name = strings.ToLower(field.Name) + } + + if slices.Contains(strings.Split(options, ","), "inline") { + inline := field.Type + for inline.Kind() == reflect.Pointer { + inline = inline.Elem() + } + + if inline.Kind() == reflect.Struct { + maps.Copy(fields, structFields(inline)) + } + + continue + } + + fields[name] = field.Type + } + + return fields +} + +func joinKey(path, name string) string { + if path == "" { + return name + } + + return path + "." + name +} diff --git a/v0_test.go b/v0_test.go index 6113eb9..37e00b2 100644 --- a/v0_test.go +++ b/v0_test.go @@ -634,6 +634,14 @@ func TestInvalidTestcasesV0(t *testing.T) { "unknown_field.yml": ValidationResults{ ValidationError{"", "foobar", "unknown field \"foobar\"", 10, 1}, }, + "unknown_fields.yml": ValidationResults{ + ValidationError{"", "zzzTop", "unknown field \"zzzTop\"", 8, 1}, + ValidationError{"", "description.en-GB.zzzDescription", "unknown field \"zzzDescription\"", 23, 1}, + ValidationError{"", "maintenance.contacts[0].zzzContact", "unknown field \"zzzContact\"", 51, 1}, + ValidationError{"", "zzzLast", "unknown field \"zzzLast\"", 58, 1}, + ValidationError{"", "description", "description must contain more than 0 items", 20, 1}, + ValidationError{"", "maintenance.type", "type is a required field", 47, 3}, + }, } dir := "testdata/v0/invalid/"