Skip to content

Commit

Permalink
Merge #294
Browse files Browse the repository at this point in the history
294: score/networkpolicy: handle empty podSelector properly in the pod-has-networkpolicy test r=zegl a=zegl

This is done by adopting the Kubernetes-provided metav1.LabelSelector, as is already used by the networkpolicy-targets-pod test.

```
RELNOTE: Support empty podSelectors in the "Pod has NetworkPolicy" test
```

This fixes #293 

Co-authored-by: Gustav Westling <[email protected]>
  • Loading branch information
bors[bot] and zegl authored Aug 11, 2020
2 parents d344a14 + e6840aa commit e6bad3b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
6 changes: 2 additions & 4 deletions score/networkpolicy/networkpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ func podHasNetworkPolicy(allNetpols []networkingv1.NetworkPolicy) func(spec core
continue
}

matchLabels := netPol.Spec.PodSelector.MatchLabels

for labelKey, labelVal := range matchLabels {
if podLabelVal, ok := podSpec.Labels[labelKey]; ok && podLabelVal == labelVal {
if selector, err := metav1.LabelSelectorAsSelector(&netPol.Spec.PodSelector); err == nil {
if selector.Matches(internal.MapLables(podSpec.Labels)) {

// Documentation of PolicyTypes
//
Expand Down
6 changes: 6 additions & 0 deletions score/networkpolicy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,9 @@ func TestNetworkPolicyCronJobNamespaceNotMatchingSelector(t *testing.T) {
testExpectedScore(t, "networkpolicy-cronjob-not-matching-selector.yaml", "NetworkPolicy targets Pod", scorecard.GradeCritical)
testExpectedScore(t, "networkpolicy-cronjob-not-matching-selector.yaml", "Pod NetworkPolicy", scorecard.GradeCritical)
}

func TestNetworkPolicyEmptyPodSelector(t *testing.T) {
t.Parallel()
testExpectedScore(t, "networkpolicy-targets-all-pods.yaml", "NetworkPolicy targets Pod", scorecard.GradeAllOK)
testExpectedScore(t, "networkpolicy-targets-all-pods.yaml", "Pod NetworkPolicy", scorecard.GradeAllOK)
}
26 changes: 26 additions & 0 deletions score/testdata/networkpolicy-targets-all-pods.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: testapp-netpol
namespace: testspace
spec:
podSelector: {}
ingress:
- {}
egress:
- {}
policyTypes:
- Ingress
- Egress
---
apiVersion: v1
kind: Pod
metadata:
name: pod-test-1
namespace: testspace
labels:
app: testapp
spec:
containers:
- name: foobar
image: foo/bar:latest

0 comments on commit e6bad3b

Please sign in to comment.