Skip to content

fix(cli): prevent setting default namespace on cluster-scoped resources

Description

Fixes #14207

Problem

The Kyverno CLI was incorrectly setting namespace='default' on all resources that didn't have a namespace specified, including cluster-scoped resources like Namespaces, Nodes, ClusterRoles, etc.

This caused kyverno test command to fail when testing mutation policies on Namespace resources because:

  1. Namespace resources were being loaded with namespace='default'
  2. The resource key used for matching became incorrect: v1,Namespace,default,name instead of v1,Namespace,,name
  3. Target resources in mutate-existing tests failed to match, resulting in "Not found" errors

Solution

Added logic to detect cluster-scoped resources before setting the default namespace:

  • New function: isClusterScopedResource() - checks if a resource kind is cluster-scoped
  • Modified: YamlToUnstructured() - only sets default namespace for namespaced resources
  • Added tests: Comprehensive test coverage for both cluster-scoped and namespaced resources

The function includes detection for common cluster-scoped resources:

  • Core resources: Namespace, Node, PersistentVolume
  • RBAC: ClusterRole, ClusterRoleBinding
  • Policy resources: ClusterPolicy, ValidatingAdmissionPolicy, etc.
  • Storage: StorageClass, CSIDriver, CSINode, VolumeAttachment
  • And more...

Testing

  1. Added unit tests with 100% coverage on new code
  2. Tested with the reproduction case from issue #14207
  3. All existing tests continue to pass

Test Case Example:

# Policy with mutateExistingOnPolicyUpdate targeting Namespaces
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-label-to-namespace
spec:
  rules:
    - name: add-label
      match:
        all:
          - resources:
              kinds:
                - Namespace
      mutate:
        patchStrategicMerge:
          metadata:
            labels:
              managed: "true"
        mutateExistingOnPolicyUpdate: true
        targets:
          - apiVersion: v1
            kind: Namespace

Before: Test fails with "Not found" error
After: Test passes correctly

Checklist

  • Issue reference included (Fixes #14207)
  • Unit tests added with 100% coverage on new code
  • All tests passing (make test-unit)
  • Code formatted (make fmt-check)
  • Imports checked (make imports-check)
  • Go vet clean (make vet)
  • Build successful (go build ./...)
  • Unused packages checked

Related Issues

Closes #14207

Merge request reports

Loading