Add validation.IsValidCIDR

Move apivalidation.ValidateCIDR to apimachinery, and rename it and
change its return value to match the other functions.

Also, add unit tests.

(Also, while updating NetworkPolicy validation for the API change, fix
a variable name that implied that IPBlock.Except[] is IP-valued rather
than CIDR-valued.)
This commit is contained in:
Dan Winship
2023-12-27 09:44:45 -05:00
parent 87fa400d9d
commit 7a56b6e3f7
4 changed files with 145 additions and 21 deletions

View File

@@ -216,27 +216,30 @@ func ValidateNetworkPolicyUpdate(update, old *networking.NetworkPolicy, opts Net
// ValidateIPBlock validates a cidr and the except fields of an IpBlock NetworkPolicyPeer
func ValidateIPBlock(ipb *networking.IPBlock, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if len(ipb.CIDR) == 0 || ipb.CIDR == "" {
if ipb.CIDR == "" {
allErrs = append(allErrs, field.Required(fldPath.Child("cidr"), ""))
return allErrs
}
cidrIPNet, err := apivalidation.ValidateCIDR(ipb.CIDR)
allErrs = append(allErrs, validation.IsValidCIDR(fldPath.Child("cidr"), ipb.CIDR)...)
_, cidrIPNet, err := netutils.ParseCIDRSloppy(ipb.CIDR)
if err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Child("cidr"), ipb.CIDR, "not a valid CIDR"))
// Implies validation would have failed so we already added errors for it.
return allErrs
}
exceptCIDR := ipb.Except
for i, exceptIP := range exceptCIDR {
for i, exceptCIDRStr := range ipb.Except {
exceptPath := fldPath.Child("except").Index(i)
exceptCIDR, err := apivalidation.ValidateCIDR(exceptIP)
allErrs = append(allErrs, validation.IsValidCIDR(exceptPath, exceptCIDRStr)...)
_, exceptCIDR, err := netutils.ParseCIDRSloppy(exceptCIDRStr)
if err != nil {
allErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, "not a valid CIDR"))
return allErrs
// Implies validation would have failed so we already added errors for it.
continue
}
cidrMaskLen, _ := cidrIPNet.Mask.Size()
exceptMaskLen, _ := exceptCIDR.Mask.Size()
if !cidrIPNet.Contains(exceptCIDR.IP) || cidrMaskLen >= exceptMaskLen {
allErrs = append(allErrs, field.Invalid(exceptPath, exceptIP, "must be a strict subset of `cidr`"))
allErrs = append(allErrs, field.Invalid(exceptPath, exceptCIDRStr, "must be a strict subset of `cidr`"))
}
}
return allErrs