Skip to content

Commit ea69383

Browse files
committed
Validate Except of IPBlock for NetworkPolicy spec
This patch enhances the validation of Except field that the values will be rejected if they are not strictly within the CIDR range.
1 parent d758fc3 commit ea69383

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

pkg/apis/networking/validation/validation.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,10 @@ func ValidateIPBlock(ipb *networking.IPBlock, fldPath *field.Path) field.ErrorLi
165165
allErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, "not a valid CIDR"))
166166
return allErrs
167167
}
168-
if !cidrIPNet.Contains(exceptCIDR.IP) {
169-
allErrs = append(allErrs, field.Invalid(exceptPath, exceptCIDR.IP, "not within CIDR range"))
168+
cidrMaskLen, _ := cidrIPNet.Mask.Size()
169+
exceptMaskLen, _ := exceptCIDR.Mask.Size()
170+
if !cidrIPNet.Contains(exceptCIDR.IP) || cidrMaskLen >= exceptMaskLen {
171+
allErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, "must be a strict subset of `cidr`"))
170172
}
171173
}
172174
return allErrs

pkg/apis/networking/validation/validation_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -715,6 +715,26 @@ func TestValidateNetworkPolicy(t *testing.T) {
715715
},
716716
},
717717
},
718+
"except IP is not strictly within CIDR range": {
719+
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
720+
Spec: networking.NetworkPolicySpec{
721+
PodSelector: metav1.LabelSelector{
722+
MatchLabels: map[string]string{"a": "b"},
723+
},
724+
Ingress: []networking.NetworkPolicyIngressRule{
725+
{
726+
From: []networking.NetworkPolicyPeer{
727+
{
728+
IPBlock: &networking.IPBlock{
729+
CIDR: "192.168.0.0/24",
730+
Except: []string{"192.168.0.0/24"},
731+
},
732+
},
733+
},
734+
},
735+
},
736+
},
737+
},
718738
"except IPv6 is outside of CIDR range": {
719739
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
720740
Spec: networking.NetworkPolicySpec{

0 commit comments

Comments
 (0)