Network policy and namespace selector

Hi
I have a question about namespace selectors in network policies:

I was playing with killer coda

There are existing Pods in Namespace space1 and space2 .

We need a new NetworkPolicy named np that restricts all Pods in Namespace space1 to only have outgoing traffic to Pods in Namespace space2 . Incoming traffic not affected.

We also need a new NetworkPolicy named np that restricts all Pods in Namespace space2 to only have incoming traffic from Pods in Namespace space1 . Outgoing traffic not affected.

So I came up with a network policy such as:

 ingress:
   - from:
     - namespaceSelector:
        matchLabels:
         name: space1

But the right answer was :

 ingress:
   - from:
     - namespaceSelector:
        matchLabels:
         kubernetes.io/metadata.name: space1

Why the kubernetes.io/metadata. is necessary before the name

Hello @stephane.hordoir
The Kubernetes control plane sets an immutable label kubernetes.io/metadata.name on all namespaces, provided that the NamespaceDefaultLabelName feature gate is enabled. The value of the label is the namespace name.

While NetworkPolicy cannot target a namespace by its name with some object field, you can use the standardized label to target a specific namespace

controlplane $ kubectl get namespace space1 -o yaml | grep -A1 labels
  labels:
    kubernetes.io/metadata.name: space1
controlplane $ kubectl get namespace space2 -o yaml | grep -A1 labels
  labels:
    kubernetes.io/metadata.name: space2

Thank you so much for the answers ! makes sense !

Thank you so much, it is more clear

then in the kubernetes documentation
what does this mean:

  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              project: myproject

Say you want to apply the NetworkPolicy to both space1 and space2 namespaces?

controlplane $ kubectl label namespace space1 project=myproject
namespace/space1 labeled
controlplane $ kubectl label namespace space2 project=myproject
namespace/space2 labeled
controlplane $ kubectl get namespace space1 -o yaml | grep -A2 labels
  labels:
    kubernetes.io/metadata.name: space1
    project: myproject
controlplane $ kubectl get namespace space2 -o yaml | grep -A2 labels
  labels:
    kubernetes.io/metadata.name: space2
    project: myproject

Now this will match both namespaces:

  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              project: myproject