Testing multiple pods using label selector

This commit is contained in:
Amim Knabben 2021-01-04 21:05:31 -05:00
parent a1e310b200
commit 61f02b85d7
2 changed files with 44 additions and 0 deletions

View File

@ -309,6 +309,23 @@ var _ = SIGDescribeCopy("Netpol [LinuxOnly]", func() {
ValidateOrFail(k8s, model, &TestCase{ToPort: 80, Protocol: v1.ProtocolTCP, Reachability: reachability})
})
ginkgo.It("should enforce policy based on any PodSelectors [Feature:NetworkPolicy]", func() {
nsX, _, _, model, k8s := getK8SModel(f)
peers := []map[string]string{{"pod": "b"}, {"pod": "c"}}
policy := GetAllowIngressByAnyPod("allow-ns-x-pod-b-c", map[string]string{"pod": "a"}, peers)
CreatePolicy(k8s, policy, nsX)
reachability := NewReachability(model.AllPods(), true)
reachability.ExpectAllIngress(NewPodString(nsX, "a"), false)
// Connect Pods b and c to pod a from namespace nsX
reachability.Expect(NewPodString(nsX, "b"), NewPodString(nsX, "a"), true)
reachability.Expect(NewPodString(nsX, "c"), NewPodString(nsX, "a"), true)
ValidateOrFail(k8s, model, &TestCase{ToPort: 80, Protocol: v1.ProtocolTCP, Reachability: reachability})
})
ginkgo.It("should enforce policy to allow traffic only from a pod in a different namespace based on PodSelector and NamespaceSelector [Feature:NetworkPolicy]", func() {
nsX, nsY, _, model, k8s := getK8SModel(f)
allowedNamespaces := &metav1.LabelSelector{

View File

@ -322,6 +322,33 @@ func GetAllowIngressByNamespaceOrPod(name string, targetLabels map[string]string
return policy
}
// GetAllowIngressByAnyPod allows ingress for pods with matching multiple pod labels
func GetAllowIngressByAnyPod(name string, targetLabels map[string]string, peersLabel []map[string]string) *networkingv1.NetworkPolicy {
policyPeers := []networkingv1.NetworkPolicyPeer{}
for _, label := range peersLabel {
policyPeers = append(policyPeers, networkingv1.NetworkPolicyPeer{
PodSelector: &metav1.LabelSelector{MatchLabels: label},
})
}
policy := &networkingv1.NetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: networkingv1.NetworkPolicySpec{
PodSelector: metav1.LabelSelector{
MatchLabels: targetLabels,
},
Ingress: []networkingv1.NetworkPolicyIngressRule{
{
From: policyPeers,
},
},
},
}
return policy
}
// GetAllowIngressByNamespaceAndPod allows ingress for pods with matching namespace AND pod labels
func GetAllowIngressByNamespaceAndPod(name string, targetLabels map[string]string, peerNamespaceSelector *metav1.LabelSelector, peerPodSelector *metav1.LabelSelector) *networkingv1.NetworkPolicy {
policy := &networkingv1.NetworkPolicy{