Skip to content

Commit eca7ba0

Browse files
authored
fix(reconcile): reject unknown top-level fields in desired-state documents (#1888)
1 parent 1e7727e commit eca7ba0

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

‎internal/reconcile/reconcile.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,11 @@ var kindDependencies = map[string][]string{
6464
// Write `spec: []` to mean that on purpose.
6565
func parseDocuments(registry map[string]Reconciler, data []byte) ([]parsedDocument, error) {
6666
dec := yaml.NewDecoder(bytes.NewReader(data))
67+
// Reject unknown top-level keys (a stray "metadata:", a typo'd "apiVarsion")
68+
// instead of ignoring them, the same way entry decoding does. The document's
69+
// own spec content is decoded separately, so this only guards the outer
70+
// apiVersion/kind/spec envelope.
71+
dec.KnownFields(true)
6772
var docs []parsedDocument
6873
for {
6974
var doc document

‎internal/reconcile/reconcile_test.go‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,29 @@ func TestRun_SpecHandling(t *testing.T) {
112112
assert.NoError(t, err)
113113
assert.Equal(t, 1, rec.called)
114114
})
115+
116+
t.Run("a document with an unknown top-level field is rejected", func(t *testing.T) {
117+
rec := &fakeReconciler{}
118+
reg := map[string]Reconciler{KindPlatformUser: rec}
119+
120+
// A stray top-level key (here a typo of "spec") must fail the file rather
121+
// than being ignored, the same way entry decoding rejects unknown fields.
122+
_, err := Run(context.Background(), reg, []byte("kind: PlatformUser\nspec: []\nspce: oops\n"), false)
123+
assert.ErrorContains(t, err, "field spce not found")
124+
assert.Zero(t, rec.called)
125+
})
126+
127+
t.Run("an unknown field in a later document is rejected", func(t *testing.T) {
128+
rec := &fakeReconciler{}
129+
reg := map[string]Reconciler{KindPlatformUser: rec}
130+
131+
// The stray key sits in the second document. The check must fire on every
132+
// document, not only the first, which is the whole point of checking the file.
133+
file := []byte("kind: PlatformUser\nspec: []\n---\nkind: PlatformUser\nspec: []\nspce: oops\n")
134+
_, err := Run(context.Background(), reg, file, false)
135+
assert.ErrorContains(t, err, "field spce not found")
136+
assert.Zero(t, rec.called)
137+
})
115138
}
116139

117140
func TestExport_Errors(t *testing.T) {

0 commit comments

Comments
 (0)