diff --git a/pkg/analyze/mutation.go b/pkg/analyze/mutation.go index 8f2f765..987ccbe 100644 --- a/pkg/analyze/mutation.go +++ b/pkg/analyze/mutation.go @@ -49,6 +49,12 @@ func diffMap(prefix string, want, got map[string]any, changed *[]string) { } gotValue, ok := got[key] if !ok { + // The API server serialises with omitempty, so a manifest field set + // to "" (or an empty map/list) comes back absent. That is the same + // value, not a mutation. + if isEmptyValue(wantValue) { + continue + } *changed = append(*changed, path) continue } @@ -87,6 +93,27 @@ func diffValue(path string, want, got any, changed *[]string) { } } +// isEmptyValue reports whether v is a value omitempty drops on the wire: nil, +// an empty string, or a map/list whose entries are all themselves empty. +func isEmptyValue(v any) bool { + switch typed := v.(type) { + case nil: + return true + case string: + return typed == "" + case map[string]any: + for _, inner := range typed { + if !isEmptyValue(inner) { + return false + } + } + return true + case []any: + return len(typed) == 0 + } + return false +} + // ignoredPath drops fields whose divergence is never a mutation. status is // server-owned, and a manifest round-tripped through `kubectl get` carries a // null creationTimestamp that the server always replaces. diff --git a/pkg/analyze/mutation_test.go b/pkg/analyze/mutation_test.go index f69e036..fca8066 100644 --- a/pkg/analyze/mutation_test.go +++ b/pkg/analyze/mutation_test.go @@ -253,3 +253,28 @@ func TestDiffSetPathsNumericOperandTypes(t *testing.T) { t.Fatalf("got %v, want [n]", got) } } + +// The API server drops empty strings on the way back (omitempty), so a probe +// that sets seLinuxOptions to "" must not be reported as mutated. This is the +// shape of the initcontainer-read-only-root-filesystem probe, whose real +// violation (readOnlyRootFilesystem: false) is admitted untouched. +func TestDiffSetPathsTreatsOmittedEmptyValuesAsUnchanged(t *testing.T) { + submitted := object(t, `{"spec":{"initContainers":[{"securityContext":{ + "readOnlyRootFilesystem": false, + "seLinuxOptions": {"user": "", "role": "", "type": ""}}}]}}`) + returned := object(t, `{"spec":{"initContainers":[{"securityContext":{ + "readOnlyRootFilesystem": false, + "seLinuxOptions": {}}}]}}`) + + if got := analyze.DiffSetPaths(submitted, returned); len(got) != 0 { + t.Fatalf("got %v, want no mutations", got) + } + + // A non-empty value that disappears is still a mutation. + submitted = object(t, `{"spec":{"securityContext":{"seLinuxOptions":{"type":"spc_t"}}}}`) + returned = object(t, `{"spec":{"securityContext":{"seLinuxOptions":{}}}}`) + want := []string{"spec.securityContext.seLinuxOptions.type"} + if got := analyze.DiffSetPaths(submitted, returned); !reflect.DeepEqual(got, want) { + t.Fatalf("got %v, want %v", got, want) + } +}