Exemplo
gopkg.in/yaml.v3 v3.0.1: Enabling Decoder.KnownFields(true) returns a yaml.TypeError when unmarshaling unknown keys, embedded struct fields missing yaml:",inline", or yaml:"-" ignored fields.
Amostra verificada para golang gopkg.in/yaml.v3 v3.0.1: Enabling Decoder.KnownFields(true) returns a yaml.TypeError when unmarshaling unknown keys, embedded…
sha256:b6ff37d02e3e29da45e029812c5d21bf74b02359da326c1e17829bd0fc6a7bf6
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 2
- Chaves de assinatura que o compilaram
- 2
Ambiente declarado
go linux x64 go go go
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-17 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Enabling Decoder.KnownFields(true) returns a yaml.TypeError when unmarshaling unknown keys, embedded struct fields missing yaml:",inline", or yaml:"-" ignored fields.
- Pacotes
- Símbolos
-
- yaml.Decoder.KnownFields
- Ambiente
- go
- Criado
- 2026-08-17T17:07:23Z
Contrato
- Enabling yaml.Decoder.KnownFields(true) returns a *yaml.TypeError reporting 'field <name> not found' for undeclared keys, un-inlined embedded struct fields, and yaml:"-" ignored fields, whereas default decoding silently discards them without error.
- Default yaml.Unmarshal or Decoder without KnownFields silently drops unknown keys and un-tagged embedded fields, returning a nil error.
- Decoder.Decode with KnownFields(true) returns a *yaml.TypeError containing line numbers and field names when encountering unknown keys.
- Embedded anonymous structs require an explicit yaml:",inline" tag to be decoded under KnownFields(true), otherwise their fields are rejected as unknown fields.
- Fields tagged with yaml:"-" are treated as unknown fields and rejected under KnownFields(true) when present in YAML input.
- Field tag matching under KnownFields(true) is case-sensitive, rejecting uppercase or mismatched keys with a *yaml.TypeError.
Arquivos
- NOTES.md
- csx.json
- go.mod
- go.sum
- yaml_config_test.go
Código-fonte
# gopkg.in/yaml.v3: Strict Field Decoding with Decoder.KnownFields
## Network Search Results
A search in the network cache returned existing samples for `gopkg.in/yaml.v3`:
- `sha256:3e3c90ab3467dde3f25d4c07c6621cca34370de7628e6c07fe6b636090ebac3a` (unmarshaling commented block sequences without nil pointer dereference panics).
- `sha256:e48bea588f5dd5489beab783c6a88de0ad1b37a153accb93af38e0689dfd3a1d` (manipulating AST nodes and document comments).
This sample investigates a different setting: strict field validation via `yaml.Decoder.KnownFields(true)`.
## Pinned Release
- `gopkg.in/yaml.v3` version `v3.0.1`
## Observed Behaviour and Failure Modes
### 1. Default Decoding Discards Unknown Fields Silently
By default, standard `yaml.Unmarshal` and `yaml.NewDecoder(r).Decode(&target)` silently discard mapping keys that do not correspond to mapped struct fields. Unrecognized keys return a `nil` error and leave unmapped struct fields at their zero values.
### 2. Strict Decoding via `Decoder.KnownFields(true)`
Calling `dec.KnownFields(true)` switches the decoder into strict mode:
- Any YAML key that does not map to an accessible field on the target struct triggers a `*yaml.TypeError`.
- The error contains the line number and message: `line <N>: field <name> not found in type <TargetType>`.
- Struct fields tagged with `yaml:"-"` are treated as unrecognized keys if present in the YAML input, causing decoding to fail with a `*yaml.TypeError`.
- Field tag matching against struct tags is case-sensitive under `KnownFields(true)`. An uppercase key (`HOST`) against a lowercase tag (`yaml:"host"`) produces a `*yaml.TypeError`.
### 3. The Embedded Anonymous Struct Trap
In the Go standard library `encoding/json`, anonymous embedded struct fields are promoted and inlined automatically during unmarshaling.
In `gopkg.in/yaml.v3`, anonymous embedded structs are not inlined by default; instead, the library expects a nested mapping key matching the embedded type name.
- **Silent failure under default unmarshaling**: If a YAML document provides flat, top-level keys for an embedded struct that lacks a `yaml:",inline"` tag, `yaml.Unmarshal` returns a `nil` error with a green build, while silently leaving the embedded fields empty (zero-valued).
- **Loud failure under `KnownFields(true)`**: When `KnownFields(true)` is enabled, the decoder treats those top-level keys as unknown fields and returns a `*yaml.TypeError` (`field <name> not found in type ...`).
- **Resolution**: The embedded struct must be explicitly tagged with `yaml:",inline"` for flat keys to unmarshal correctly into embedded fields under strict mode.
{"case":{"believed":"yaml.Decoder.Decode ignores unrecognized keys by default, and developers expecting encoding/json semantics assume embedded anonymous struct fields are automatically inlined without explicit tags.","caseId":"case:sha256:007889538fd3e188aebe6c9f3f71349bf3002889a8692b4c13de1f09538dd1d1","contract":["Enabling yaml.Decoder.KnownFields(true) returns a *yaml.TypeError reporting 'field \u003cname\u003e not found' for undeclared keys, un-inlined embedded struct fields, and yaml:\"-\" ignored fields, whereas default decoding silently discards them without error.","Default yaml.Unmarshal or Decoder without KnownFields silently drops unknown keys and un-tagged embedded fields, returning a nil error.","Decoder.Decode with KnownFields(true) returns a *yaml.TypeError containing line numbers and field names when encountering unknown keys.","Embedded anonymous structs require an explicit yaml:\",inline\" tag to be decoded under KnownFields(true), otherwise their fields are rejected as unknown fields.","Fields tagged with yaml:\"-\" are treated as unknown fields and rejected under KnownFields(true) when present in YAML input.","Field tag matching under KnownFields(true) is case-sensitive, rejecting uppercase or mismatched keys with a *yaml.TypeError."],"goal":"Enabling Decoder.KnownFields(true) returns a yaml.TypeError when unmarshaling unknown keys, embedded struct fields missing yaml:\",inline\", or yaml:\"-\" ignored fields.","kind":"HOW","packages":["pkg:golang/gopkg.in/yaml.v3@v3.0.1"],"schemaVersion":1,"symbols":["yaml.Decoder.KnownFields"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/gopkg.in/yaml.v3@v3.0.1"],"schemaVersion":1,"symbols":["yaml.Decoder.KnownFields"],"verifierAdapter":"golang@1"}
module example.com/testyaml
go 1.26.5
require gopkg.in/yaml.v3 v3.0.1
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
package yamlconfig_test
import (
"errors"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
type ServerConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type InlineAppConfig struct {
ServerConfig `yaml:",inline"`
Name string `yaml:"name"`
}
type NonInlineAppConfig struct {
ServerConfig
Name string `yaml:"name"`
}
type IgnoredFieldConfig struct {
Name string `yaml:"name"`
Secret string `yaml:"-"`
}
func TestKnownFieldsSetting(t *testing.T) {
t.Run("default unmarshaler silently ignores unknown fields and un-inlined embedded structs", func(t *testing.T) {
// 1. Unknown fields are ignored by default
yamlWithExtra := "host: example.com\nport: 8080\nextra_setting: debug\n"
var srv ServerConfig
if err := yaml.Unmarshal([]byte(yamlWithExtra), &srv); err != nil {
t.Fatalf("expected nil error on default unmarshal with extra fields, got: %v", err)
}
if srv.Host != "example.com" || srv.Port != 8080 {
t.Fatalf("expected srv to be populated, got: %+v", srv)
}
// 2. Embedded structs without `yaml:\",inline\"` are silently ignored when top-level keys are supplied
yamlFlat := "host: example.com\nport: 8080\nname: myapp\n"
var nonInline NonInlineAppConfig
if err := yaml.Unmarshal([]byte(yamlFlat), &nonInline); err != nil {
t.Fatalf("expected nil error on non-inlined unmarshal, got: %v", err)
}
if nonInline.Name != "myapp" {
t.Fatalf("expected name to be myapp, got: %s", nonInline.Name)
}
if nonInline.Host != "" || nonInline.Port != 0 {
t.Fatalf("expected un-tagged embedded fields to remain zero-valued, got: Host=%s, Port=%d", nonInline.Host, nonInline.Port)
}
// 3. Ignored fields (yaml:"-") are silently skipped
yamlIgnored := "name: myapp\nsecret: hidden_token\n"
var ignored IgnoredFieldConfig
if err := yaml.Unmarshal([]byte(yamlIgnored), &ignored); err != nil {
t.Fatalf("expected nil error on ignored field unmarshal, got: %v", err)
}
if ignored.Secret != "" {
t.Fatalf("expected secret to remain empty, got: %s", ignored.Secret)
}
})
t.Run("KnownFields(true) returns TypeError for unknown fields", func(t *testing.T) {
yamlWithExtra := "host: example.com\nport: 8080\nextra_setting: debug\n"
var srv ServerConfig
dec := yaml.NewDecoder(strings.NewReader(yamlWithExtra))
dec.KnownFields(true)
err := dec.Decode(&srv)
if err == nil {
t.Fatal("expected error with KnownFields(true) on unknown field, got nil")
}
var typeErr *yaml.TypeError
if !errors.As(err, &typeErr) {
t.Fatalf("expected *yaml.TypeError, got: %T (%v)", err, err)
}
expectedSnippet := "field extra_setting not found in type yamlconfig_test.ServerConfig"
if !strings.Contains(err.Error(), expectedSnippet) {
t.Fatalf("expected error containing %q, got: %q", expectedSnippet, err.Error())
}
})
t.Run("KnownFields(true) fails on embedded structs missing yaml:\",inline\"", func(t *testing.T) {
yamlFlat := "host: example.com\nport: 8080\nname: myapp\n"
var nonInline NonInlineAppConfig
dec := yaml.NewDecoder(strings.NewReader(yamlFlat))
dec.KnownFields(true)
err := dec.Decode(&nonInline)
if err == nil {
t.Fatal("expected error with KnownFields(true) when struct lacks inline tag, got nil")
}
var typeErr *yaml.TypeError
if !errors.As(err, &typeErr) {
t.Fatalf("expected *yaml.TypeError, got: %T (%v)", err, err)
}
if !strings.Contains(err.Error(), "field host not found in type yamlconfig_test.NonInlineAppConfig") {
t.Fatalf("expected error about field host, got: %q", err.Error())
}
})
t.Run("KnownFields(true) succeeds when embedded struct is tagged with yaml:\",inline\"", func(t *testing.T) {
yamlFlat := "host: example.com\nport: 8080\nname: myapp\n"
var inline InlineAppConfig
dec := yaml.NewDecoder(strings.NewReader(yamlFlat))
dec.KnownFields(true)
if err := dec.Decode(&inline); err != nil {
t.Fatalf("expected success with KnownFields(true) and inline tag, got: %v", err)
}
if inline.Host != "example.com" || inline.Port != 8080 || inline.Name != "myapp" {
t.Fatalf("unexpected decoded struct values: %+v", inline)
}
})
t.Run("KnownFields(true) rejects ignored yaml:\"-\" fields as unknown", func(t *testing.T) {
yamlIgnored := "name: myapp\nsecret: hidden_token\n"
var ignored IgnoredFieldConfig
dec := yaml.NewDecoder(strings.NewReader(yamlIgnored))
dec.KnownFields(true)
err := dec.Decode(&ignored)
if err == nil {
t.Fatal("expected error with KnownFields(true) on yaml:\"-\" field, got nil")
}
var typeErr *yaml.TypeError
if !errors.As(err, &typeErr) {
t.Fatalf("expected *yaml.TypeError, got: %T (%v)", err, err)
}
if !strings.Contains(err.Error(), "field secret not found in type yamlconfig_test.IgnoredFieldConfig") {
t.Fatalf("expected error about field secret, got: %q", err.Error())
}
})
t.Run("KnownFields(true) enforces case-sensitive tag matching", func(t *testing.T) {
yamlUpper := "HOST: example.com\nport: 8080\n"
var srv ServerConfig
dec := yaml.NewDecoder(strings.NewReader(yamlUpper))
dec.KnownFields(true)
err := dec.Decode(&srv)
if err == nil {
t.Fatal("expected error with KnownFields(true) on case mismatch against struct tag, got nil")
}
var typeErr *yaml.TypeError
if !errors.As(err, &typeErr) {
t.Fatalf("expected *yaml.TypeError, got: %T (%v)", err, err)
}
if !strings.Contains(err.Error(), "field HOST not found in type yamlconfig_test.ServerConfig") {
t.Fatalf("expected error about field HOST, got: %q", err.Error())
}
})
}