[Feature]: Strict YAML decoding in internal/render, plus a hostile-label render test
Motivation
internal/render/render.go decodes rendered manifests with yamlDecoder.NewYAMLOrJSONDecoder (line 139), which uses non-strict yaml.YAMLToJSON. Duplicate mapping keys are resolved last-wins with no error, which is how a user label can silently replace an operand's app or component label (#3059). Any future template bug that emits a key twice will fail the same silent way.
Proposal
- Split rendered output into documents and convert each with
sigs.k8s.io/yaml.YAMLToJSONStrict, so duplicate keys become render errors surfaced as a failed state. - Add a unit test that renders every manifest under
manifests/andassets/with label and annotation maps containing reserved keys, asserting either an error or that the operator's values survive.
Related: #3059, #3067.
@CloneOfAlex
Could you provide more details about the problem you encountered and your proposed solution?
Thanks @francisguillier, here's the detail. Prototyping the change also turned up something the original proposal missed: turning on strict decoding as-is would break precompiled and OpenShift-DTK driver rendering on current main.
The problem
internal/render/render.go:139 decodes rendered manifests with yamlDecoder.NewYAMLOrJSONDecoder. That converts YAML with the non-strict yaml.YAMLToJSON, so a mapping key that appears twice resolves last-wins, with no error.
The templates append user-supplied maps right after operator-owned keys. For example, manifests/state-driver/0500_daemonset.yaml renders .Driver.Spec.Labels | yaml | nindent directly under app / app.kubernetes.io/component. A user label with a reserved key therefore silently replaces the operator's value. That's the root cause of #3059, which lists the downstream breakage: upgrade-controller lookup, orphaned-pod detection, the validator, and the selector mismatch for app.
To be transparent: found by code review. Here's a render-level repro against current main, using a template that mirrors the driver DaemonSet's label block:
--- FAIL: TestRenderRejectsDuplicateMappingKeys
duplicate key must be a render error, got labels
map[app:nvidia-driver-daemonset app.kubernetes.io/component:custom]
--- PASS: TestRenderAllowsDistinctUserLabels
internal/render/render_duplicate_keys_test.go
package render
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
// Mirrors manifests/state-driver/0500_daemonset.yaml: operator-owned labels
// followed by user-supplied spec.labels rendered with `yaml | nindent`.
const labelsAfterOperatorKeys = `apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nvidia-driver-daemonset
labels:
app: nvidia-driver-daemonset
app.kubernetes.io/component: nvidia-driver
{{- if .Labels }}
{{- .Labels | yaml | nindent 4 }}
{{- end }}
`
func renderLabels(t *testing.T, labels map[string]string) (map[string]string, error) {
t.Helper()
f := filepath.Join(t.TempDir(), "ds.yaml")
require.NoError(t, os.WriteFile(f, []byte(labelsAfterOperatorKeys), 0o600))
objs, err := NewRenderer([]string{f}).RenderObjects(&TemplatingData{Data: map[string]any{"Labels": labels}})
if err != nil {
return nil, err
}
require.Len(t, objs, 1)
return objs[0].GetLabels(), nil
}
// A user label that collides with an operator-owned key renders to YAML with a
// duplicate mapping key. The renderer must not silently let the user value win.
func TestRenderRejectsDuplicateMappingKeys(t *testing.T) {
got, err := renderLabels(t, map[string]string{"app.kubernetes.io/component": "custom"})
require.Error(t, err, "duplicate key must be a render error, got labels %v", got)
require.Contains(t, err.Error(), `key "app.kubernetes.io/component" already set in map`)
}
// Non-colliding user labels keep working.
func TestRenderAllowsDistinctUserLabels(t *testing.T) {
got, err := renderLabels(t, map[string]string{"team": "ml"})
require.NoError(t, err)
require.Equal(t, "nvidia-driver", got["app.kubernetes.io/component"])
require.Equal(t, "ml", got["team"])
}
Prototype: strict decoding
The change splits the rendered output with yaml.NewYAMLReader, converts each document with sigs.k8s.io/yaml.YAMLToJSONStrict, and unmarshals with k8s.io/apimachinery/pkg/util/json, which keeps integers as int64 the way unstructured expects. Empty and kind-less documents are still skipped.
Diff (internal/render/render.go)
diff --git a/internal/render/render.go b/internal/render/render.go
index b798160..0018a54 100644
--- a/internal/render/render.go
+++ b/internal/render/render.go
@@ -25,6 +25,7 @@ package render
*/
import (
+ "bufio"
"bytes"
"fmt"
"io"
@@ -36,16 +37,13 @@ import (
"github.com/Masterminds/sprig/v3"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+ k8sjson "k8s.io/apimachinery/pkg/util/json"
yamlDecoder "k8s.io/apimachinery/pkg/util/yaml"
yamlConverter "sigs.k8s.io/yaml"
"github.com/NVIDIA/gpu-operator/internal/utils"
)
-const (
- maxBufSizeForYamlDecode = 4096
-)
-
var ManifestFileSuffix = []string{"yaml", "yml", "json"}
// Renderer renders k8s objects from a manifest source dir and TemplatingData used by the templating engine
@@ -136,15 +134,26 @@ func (r *textTemplateRenderer) renderFile(filePath string, data *TemplatingData)
return out, nil
}
- decoder := yamlDecoder.NewYAMLOrJSONDecoder(&rendered, maxBufSizeForYamlDecode)
+ reader := yamlDecoder.NewYAMLReader(bufio.NewReader(&rendered))
for {
- u := unstructured.Unstructured{}
- if err := decoder.Decode(&u); err != nil {
+ doc, err := reader.Read()
+ if err != nil {
if err == io.EOF {
break
}
+ return nil, fmt.Errorf("failed to read manifest %s: %w", filePath, err)
+ }
+ // Strict conversion: duplicate mapping keys are an error instead of last-wins.
+ jsonDoc, err := yamlConverter.YAMLToJSONStrict(doc)
+ if err != nil {
+ return nil, fmt.Errorf("failed to unmarshal manifest %s: %w", filePath, err)
+ }
+ obj := map[string]any{}
+ // k8s.io/apimachinery/pkg/util/json decodes integers as int64, as unstructured expects.
+ if err := k8sjson.Unmarshal(jsonDoc, &obj); err != nil {
return nil, fmt.Errorf("failed to unmarshal manifest %s: %w", filePath, err)
}
+ u := unstructured.Unstructured{Object: obj}
// Ensure object is not empty by checking the object kind
if u.GetKind() == "" {
continue
With that applied, the repro test passes and the error reads key "app.kubernetes.io/component" already set in map. go build ./... and go vet are clean, and internal/render, controllers, and cmd/... all pass.
What it found: existing duplicate keys in the driver template
Three tests in internal/state fail under strict mode: TestGetManifestObjectsPrecompiled, TestGetManifestObjectsOpenshiftDTK, and …OpenshiftDTKMissingImageForNodePool. These go through the real node-pool path:
key "feature.node.kubernetes.io/kernel-version.full" already set in map (precompiled)
key "feature.node.kubernetes.io/system-os_release.OSTREE_VERSION" already set in map (OpenShift + DTK)
The driver DaemonSet's nodeSelector gets these keys twice:
spec.NodeSelector = nodePool.nodeSelector(internal/state/driver.go:588), which already contains them (nodepool.go:126,:137)0500_daemonset.yaml:80-85adds them again explicitly from.Precompiled.KernelVersion/.Openshift.RHCOSVersion
Both values come from the same node label, so they're identical and last-wins is harmless today. But strict mode would turn every precompiled and OpenShift-DTK driver deployment into a render error. So the template has to be fixed first:
- Remove the explicit lines at
0500_daemonset.yaml:80-85, since the node-pool selector already carries them. - Update four golden tests that build render data by hand and don't set
Spec.NodeSelectorthe way the node-pool path does:TestDriverPrecompiled,TestDriverOpenshiftDriverToolkit,TestDriverGDRCopyOpenShift,TestVGPUHostManagerDaemonsetOpenShift. I tried removing the lines: these four are the only failures, and in the one I inspected (TestDriverPrecompiled) the only diff is the now-missing selector key.
Correction to the second half of my proposal
I proposed a hostile-label render test over manifests/ and assets/. assets/ isn't Go-templated with user data. Those are static YAML files decoded into typed objects (controllers/resource_manager.go), and user labels are applied in Go, with reserved keys already protected (applyCommonDaemonsetLabel). So:
manifests/: render tests with label/annotation/nodeSelector maps containing reserved keys, asserting a render error, or that operator values survive once #3059's filtering lands.assets/: a static check that every document passesYAMLToJSONStrict. I ran that scan: 144 documents, 0 duplicates, so it's a cheap guard with nothing to fix today.
Proposed order
- Fix the duplicate
nodeSelectorkeys instate-driverand update the four golden tests. No behavior change. - Switch
internal/renderto strict decoding, add the duplicate-key render test, and add theassets/scan. - #3059's reserved-key filtering and CEL validation stays the user-facing fix. Strict decoding is defense in depth: a colliding label becomes a clear failed state instead of a silently mislabeled DaemonSet, but it still doesn't deploy, so filtering is what actually makes those specs work.
I'm happy to open PRs for 1 and 2.
@CloneOfAlex
I’m not sure I understand the deployment problem you’re trying to solve. Could you please provide:
- Issue summary: What is happening, and what behavior do you expect?
- Steps to reproduce: Include the relevant environment details and configuration.
- Proposed fix: Explain how the fix addresses the problem. Without these details, we won’t be able to assess the issue and will close it. Thanks
@francisguillier honestly, there's no standalone deployment problem here. Strict decoding is defense in depth: it turns a silently overridden key into a render error. The one user-facing case it would surface is the GPUCluster label collision in #3067, and that's better fixed by filtering/CEL there. Strict mode alone still wouldn't make that spec deploy.
The one concrete finding was that the driver template emits duplicate nodeSelector keys for precompiled and OpenShift-DTK pools. Those are harmless today because both values come from the same node label.
I'll close this and track the remaining work under #3067.