Repository: kubernetes-sigs/controller-runtime

Issue:
Namespaced Client unable to List non-namespaced objects
In the `List` function, the client's namespace is appended to the ListOptions regardless of the scope of the objects:
https://github.com/kubernetes-sigs/controller-runtime/blob/c8a5a35177d3efc56918023f5253ffd57dc943ad/pkg/client/namespaced_client.go#L224-L226

This makes it unusable with objects that have a cluster-wide scope, as it will never find anything.

It is also inconsistent with the `Get` implementation, where there is a check if the object is namepaced or not, before setting the namespace:
https://github.com/kubernetes-sigs/controller-runtime/blob/c8a5a35177d3efc56918023f5253ffd57dc943ad/pkg/client/namespaced_client.go#L209-L218

Hints from issue comments:
@sbueringer: Sounds like a bug

Solution patch:
diff --git a/pkg/client/namespaced_client.go b/pkg/client/namespaced_client.go
index 445e91b9..ebbbc4fd 100644
--- a/pkg/client/namespaced_client.go
+++ b/pkg/client/namespaced_client.go
@@ -221,7 +221,12 @@ func (n *namespacedClient) Get(ctx context.Context, key ObjectKey, obj Object, o
 
 // List implements client.Client.
 func (n *namespacedClient) List(ctx context.Context, obj ObjectList, opts ...ListOption) error {
-	if n.namespace != "" {
+	isNamespaceScoped, err := n.IsObjectNamespaced(obj)
+	if err != nil {
+		return fmt.Errorf("error finding the scope of the object: %w", err)
+	}
+
+	if isNamespaceScoped && n.namespace != "" {
 		opts = append(opts, InNamespace(n.namespace))
 	}
 	return n.client.List(ctx, obj, opts...)



Test patch:
diff --git a/pkg/client/namespaced_client_test.go b/pkg/client/namespaced_client_test.go
index deae881d..7060f323 100644
--- a/pkg/client/namespaced_client_test.go
+++ b/pkg/client/namespaced_client_test.go
@@ -54,6 +54,8 @@ var _ = Describe("NamespacedClient", func() {
 
 		err := rbacv1.AddToScheme(sch)
 		Expect(err).ToNot(HaveOccurred())
+		err = corev1.AddToScheme(sch)
+		Expect(err).ToNot(HaveOccurred())
 		err = appsv1.AddToScheme(sch)
 		Expect(err).ToNot(HaveOccurred())
 
@@ -147,6 +149,13 @@ var _ = Describe("NamespacedClient", func() {
 			Expect(result.Items[0]).To(BeEquivalentTo(*dep))
 		})
 
+		It("should successfully List objects when object is not namespaced scoped", func(ctx SpecContext) {
+			result := &corev1.NodeList{}
+			opts := &client.ListOptions{}
+			Expect(getClient().List(ctx, result, opts)).NotTo(HaveOccurred())
+			Expect(result.Items).NotTo(BeEmpty())
+		})
+
 		It("should List objects from the namespace specified in the client", func(ctx SpecContext) {
 			result := &appsv1.DeploymentList{}
 			opts := client.InNamespace("non-default")