[Bug] NetworkPolicy analyzer matches same-label Pods from other namespaces
Expected Behavior
When analyzing NetworkPolicies across all namespaces, a policy's spec.podSelector should be evaluated only against Pods in the policy's own namespace. A Pod with matching labels in another namespace must not count as a selected Pod.
Current Behavior
NetworkPolicyAnalyzer passes the analysis namespace to the Pod lookup instead of the NetworkPolicy namespace. When analysis runs without --namespace, the analysis namespace is empty and the client lists Pods across namespaces. As a result, a policy in one namespace can be treated as applied because a same-label Pod exists in another namespace, suppressing the diagnostic that the policy selects no Pods in its own namespace.
Steps to Reproduce
- Create a NetworkPolicy in
team-awithspec.podSelector.matchLabels: {app: worker}and no matching Pod inteam-a. - Create a Pod with label
app: workeronly inteam-b. - Run the NetworkPolicy analyzer in cluster-wide mode by omitting
--namespace(or callNetworkPolicyAnalyzerwithcommon.Analyzer.Namespace == ""). - Observe that the
team-a/worker-policyresult is absent, even though the policy does not select any Pod inteam-a.
The same behavior is reproducible with the repository's fake client: a team-a NetworkPolicy and a same-label team-b Pod produce zero analyzer results when Namespace is empty.
Environment
- k8sgpt version: main
- Kubernetes version: networking.k8s.io/v1 NetworkPolicy semantics; not version-specific
- AI Backend/Provider: n/a
- OS/Platform: macOS / client-go fake client
Additional Context
The analyzer currently lists policies using the analysis namespace and then calls the Pod helper with a.Namespace, while NetworkPolicy podSelector is namespace-scoped by Kubernetes semantics. The CLI defaults --namespace to an empty value, so this affects the normal cluster-wide analysis path.
Kubernetes API reference: https://kubernetes.io/docs/reference/kubernetes-api/networking/network-policy-v1/
A temporary fake-client regression test failed deterministically on the current checkout. The focused scope of a possible fix is to evaluate the selector in policy.Namespace and add the regression test. Support for matchExpressions is a separate behavior and is intentionally out of scope for this issue.
I am willing to submit a focused PR after maintainer confirmation.
Source: k8sgpt-ai/k8sgpt