rebase: update kubernetes to 1.30

updating kubernetes to 1.30 release

Signed-off-by: Madhu Rajanna <madhupr007@gmail.com>
This commit is contained in:
Madhu Rajanna
2024-05-15 08:54:18 +02:00
committed by mergify[bot]
parent 62ddcf715b
commit e727bd351e
747 changed files with 73809 additions and 10436 deletions

87
vendor/k8s.io/apiserver/pkg/cel/cidr.go generated vendored Normal file
View File

@ -0,0 +1,87 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cel
import (
"fmt"
"math"
"net/netip"
"reflect"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
)
// CIDR provides a CEL representation of an network address.
type CIDR struct {
netip.Prefix
}
var (
CIDRType = cel.OpaqueType("net.CIDR")
)
// ConvertToNative implements ref.Val.ConvertToNative.
func (d CIDR) ConvertToNative(typeDesc reflect.Type) (any, error) {
if reflect.TypeOf(d.Prefix).AssignableTo(typeDesc) {
return d.Prefix, nil
}
if reflect.TypeOf("").AssignableTo(typeDesc) {
return d.Prefix.String(), nil
}
return nil, fmt.Errorf("type conversion error from 'CIDR' to '%v'", typeDesc)
}
// ConvertToType implements ref.Val.ConvertToType.
func (d CIDR) ConvertToType(typeVal ref.Type) ref.Val {
switch typeVal {
case CIDRType:
return d
case types.TypeType:
return CIDRType
case types.StringType:
return types.String(d.Prefix.String())
}
return types.NewErr("type conversion error from '%s' to '%s'", CIDRType, typeVal)
}
// Equal implements ref.Val.Equal.
func (d CIDR) Equal(other ref.Val) ref.Val {
otherD, ok := other.(CIDR)
if !ok {
return types.ValOrErr(other, "no such overload")
}
return types.Bool(d.Prefix == otherD.Prefix)
}
// Type implements ref.Val.Type.
func (d CIDR) Type() ref.Type {
return CIDRType
}
// Value implements ref.Val.Value.
func (d CIDR) Value() any {
return d.Prefix
}
// Size returns the size of the CIDR prefix address in bytes.
// Used in the size estimation of the runtime cost.
func (d CIDR) Size() ref.Val {
return types.Int(int(math.Ceil(float64(d.Prefix.Bits()) / 8)))
}

View File

@ -43,7 +43,7 @@ import (
// desirable because it means that CEL expressions are portable across a wider range
// of Kubernetes versions.
func DefaultCompatibilityVersion() *version.Version {
return version.MajorMinor(1, 28)
return version.MajorMinor(1, 29)
}
var baseOpts = []VersionedOptions{
@ -123,6 +123,13 @@ var baseOpts = []VersionedOptions{
ext.Sets(),
},
},
{
IntroducedVersion: version.MajorMinor(1, 30),
EnvOptions: []cel.EnvOption{
library.IP(),
library.CIDR(),
},
},
}
// MustBaseEnvSet returns the common CEL base environments for Kubernetes for Version, or panics

86
vendor/k8s.io/apiserver/pkg/cel/ip.go generated vendored Normal file
View File

@ -0,0 +1,86 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cel
import (
"fmt"
"math"
"net/netip"
"reflect"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
)
// IP provides a CEL representation of an IP address.
type IP struct {
netip.Addr
}
var (
IPType = cel.OpaqueType("net.IP")
)
// ConvertToNative implements ref.Val.ConvertToNative.
func (d IP) ConvertToNative(typeDesc reflect.Type) (any, error) {
if reflect.TypeOf(d.Addr).AssignableTo(typeDesc) {
return d.Addr, nil
}
if reflect.TypeOf("").AssignableTo(typeDesc) {
return d.Addr.String(), nil
}
return nil, fmt.Errorf("type conversion error from 'IP' to '%v'", typeDesc)
}
// ConvertToType implements ref.Val.ConvertToType.
func (d IP) ConvertToType(typeVal ref.Type) ref.Val {
switch typeVal {
case IPType:
return d
case types.TypeType:
return IPType
case types.StringType:
return types.String(d.Addr.String())
}
return types.NewErr("type conversion error from '%s' to '%s'", IPType, typeVal)
}
// Equal implements ref.Val.Equal.
func (d IP) Equal(other ref.Val) ref.Val {
otherD, ok := other.(IP)
if !ok {
return types.ValOrErr(other, "no such overload")
}
return types.Bool(d.Addr == otherD.Addr)
}
// Type implements ref.Val.Type.
func (d IP) Type() ref.Type {
return IPType
}
// Value implements ref.Val.Value.
func (d IP) Value() any {
return d.Addr
}
// Size returns the size of the IP address in bytes.
// Used in the size estimation of the runtime cost.
func (d IP) Size() ref.Val {
return types.Int(int(math.Ceil(float64(d.Addr.BitLen()) / 8)))
}

287
vendor/k8s.io/apiserver/pkg/cel/library/cidr.go generated vendored Normal file
View File

@ -0,0 +1,287 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package library
import (
"fmt"
"net/netip"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
apiservercel "k8s.io/apiserver/pkg/cel"
)
// CIDR provides a CEL function library extension of CIDR notation parsing functions.
//
// cidr
//
// Converts a string in CIDR notation to a network address representation or results in an error if the string is not a valid CIDR notation.
// The CIDR must be an IPv4 or IPv6 subnet address with a mask.
// Leading zeros in IPv4 address octets are not allowed.
// IPv4-mapped IPv6 addresses (e.g. ::ffff:1.2.3.4/24) are not allowed.
//
// cidr(<string>) <CIDR>
//
// Examples:
//
// cidr('192.168.0.0/16') // returns an IPv4 address with a CIDR mask
// cidr('::1/128') // returns an IPv6 address with a CIDR mask
// cidr('192.168.0.0/33') // error
// cidr('::1/129') // error
// cidr('192.168.0.1/16') // error, because there are non-0 bits after the prefix
//
// isCIDR
//
// Returns true if a string is a valid CIDR notation respresentation of a subnet with mask.
// The CIDR must be an IPv4 or IPv6 subnet address with a mask.
// Leading zeros in IPv4 address octets are not allowed.
// IPv4-mapped IPv6 addresses (e.g. ::ffff:1.2.3.4/24) are not allowed.
//
// isCIDR(<string>) <bool>
//
// Examples:
//
// isCIDR('192.168.0.0/16') // returns true
// isCIDR('::1/128') // returns true
// isCIDR('192.168.0.0/33') // returns false
// isCIDR('::1/129') // returns false
//
// containsIP / containerCIDR / ip / masked / prefixLength
//
// - containsIP: Returns true if a the CIDR contains the given IP address.
// The IP address must be an IPv4 or IPv6 address.
// May take either a string or IP address as an argument.
//
// - containsCIDR: Returns true if a the CIDR contains the given CIDR.
// The CIDR must be an IPv4 or IPv6 subnet address with a mask.
// May take either a string or CIDR as an argument.
//
// - ip: Returns the IP address representation of the CIDR.
//
// - masked: Returns the CIDR representation of the network address with a masked prefix.
// This can be used to return the canonical form of the CIDR network.
//
// - prefixLength: Returns the prefix length of the CIDR in bits.
// This is the number of bits in the mask.
//
// Examples:
//
// cidr('192.168.0.0/24').containsIP(ip('192.168.0.1')) // returns true
// cidr('192.168.0.0/24').containsIP(ip('192.168.1.1')) // returns false
// cidr('192.168.0.0/24').containsIP('192.168.0.1') // returns true
// cidr('192.168.0.0/24').containsIP('192.168.1.1') // returns false
// cidr('192.168.0.0/16').containsCIDR(cidr('192.168.10.0/24')) // returns true
// cidr('192.168.1.0/24').containsCIDR(cidr('192.168.2.0/24')) // returns false
// cidr('192.168.0.0/16').containsCIDR('192.168.10.0/24') // returns true
// cidr('192.168.1.0/24').containsCIDR('192.168.2.0/24') // returns false
// cidr('192.168.0.1/24').ip() // returns ipAddr('192.168.0.1')
// cidr('192.168.0.1/24').ip().family() // returns '4'
// cidr('::1/128').ip() // returns ipAddr('::1')
// cidr('::1/128').ip().family() // returns '6'
// cidr('192.168.0.0/24').masked() // returns cidr('192.168.0.0/24')
// cidr('192.168.0.1/24').masked() // returns cidr('192.168.0.0/24')
// cidr('192.168.0.0/24') == cidr('192.168.0.0/24').masked() // returns true, CIDR was already in canonical format
// cidr('192.168.0.1/24') == cidr('192.168.0.1/24').masked() // returns false, CIDR was not in canonical format
// cidr('192.168.0.0/16').prefixLength() // returns 16
// cidr('::1/128').prefixLength() // returns 128
func CIDR() cel.EnvOption {
return cel.Lib(cidrsLib)
}
var cidrsLib = &cidrs{}
type cidrs struct{}
func (*cidrs) LibraryName() string {
return "net.cidr"
}
var cidrLibraryDecls = map[string][]cel.FunctionOpt{
"cidr": {
cel.Overload("string_to_cidr", []*cel.Type{cel.StringType}, apiservercel.CIDRType,
cel.UnaryBinding(stringToCIDR)),
},
"containsIP": {
cel.MemberOverload("cidr_contains_ip_string", []*cel.Type{apiservercel.CIDRType, cel.StringType}, cel.BoolType,
cel.BinaryBinding(cidrContainsIPString)),
cel.MemberOverload("cidr_contains_ip_ip", []*cel.Type{apiservercel.CIDRType, apiservercel.IPType}, cel.BoolType,
cel.BinaryBinding(cidrContainsIP)),
},
"containsCIDR": {
cel.MemberOverload("cidr_contains_cidr_string", []*cel.Type{apiservercel.CIDRType, cel.StringType}, cel.BoolType,
cel.BinaryBinding(cidrContainsCIDRString)),
cel.MemberOverload("cidr_contains_cidr", []*cel.Type{apiservercel.CIDRType, apiservercel.CIDRType}, cel.BoolType,
cel.BinaryBinding(cidrContainsCIDR)),
},
"ip": {
cel.MemberOverload("cidr_ip", []*cel.Type{apiservercel.CIDRType}, apiservercel.IPType,
cel.UnaryBinding(cidrToIP)),
},
"prefixLength": {
cel.MemberOverload("cidr_prefix_length", []*cel.Type{apiservercel.CIDRType}, cel.IntType,
cel.UnaryBinding(prefixLength)),
},
"masked": {
cel.MemberOverload("cidr_masked", []*cel.Type{apiservercel.CIDRType}, apiservercel.CIDRType,
cel.UnaryBinding(masked)),
},
"isCIDR": {
cel.Overload("is_cidr", []*cel.Type{cel.StringType}, cel.BoolType,
cel.UnaryBinding(isCIDR)),
},
"string": {
cel.Overload("cidr_to_string", []*cel.Type{apiservercel.CIDRType}, cel.StringType,
cel.UnaryBinding(cidrToString)),
},
}
func (*cidrs) CompileOptions() []cel.EnvOption {
options := []cel.EnvOption{cel.Types(apiservercel.CIDRType),
cel.Variable(apiservercel.CIDRType.TypeName(), types.NewTypeTypeWithParam(apiservercel.CIDRType)),
}
for name, overloads := range cidrLibraryDecls {
options = append(options, cel.Function(name, overloads...))
}
return options
}
func (*cidrs) ProgramOptions() []cel.ProgramOption {
return []cel.ProgramOption{}
}
func stringToCIDR(arg ref.Val) ref.Val {
s, ok := arg.Value().(string)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
net, err := parseCIDR(s)
if err != nil {
return types.NewErr("network address parse error during conversion from string: %v", err)
}
return apiservercel.CIDR{
Prefix: net,
}
}
func cidrToString(arg ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.String(cidr.Prefix.String())
}
func cidrContainsIPString(arg ref.Val, other ref.Val) ref.Val {
return cidrContainsIP(arg, stringToIP(other))
}
func cidrContainsCIDRString(arg ref.Val, other ref.Val) ref.Val {
return cidrContainsCIDR(arg, stringToCIDR(other))
}
func cidrContainsIP(arg ref.Val, other ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(other)
}
ip, ok := other.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(cidr.Contains(ip.Addr))
}
func cidrContainsCIDR(arg ref.Val, other ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
containsCIDR, ok := other.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(other)
}
equalMasked := cidr.Prefix.Masked() == netip.PrefixFrom(containsCIDR.Prefix.Addr(), cidr.Prefix.Bits())
return types.Bool(equalMasked && cidr.Prefix.Bits() <= containsCIDR.Prefix.Bits())
}
func prefixLength(arg ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Int(cidr.Prefix.Bits())
}
func isCIDR(arg ref.Val) ref.Val {
s, ok := arg.Value().(string)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
_, err := parseCIDR(s)
return types.Bool(err == nil)
}
func cidrToIP(arg ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return apiservercel.IP{
Addr: cidr.Prefix.Addr(),
}
}
func masked(arg ref.Val) ref.Val {
cidr, ok := arg.(apiservercel.CIDR)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
maskedCIDR := cidr.Prefix.Masked()
return apiservercel.CIDR{
Prefix: maskedCIDR,
}
}
// parseCIDR parses a string into an CIDR.
// We use this function to parse CIDR notation in the CEL library
// so that we can share the common logic of rejecting strings
// that IPv4-mapped IPv6 addresses or contain non-zero bits after the mask.
func parseCIDR(raw string) (netip.Prefix, error) {
net, err := netip.ParsePrefix(raw)
if err != nil {
return netip.Prefix{}, fmt.Errorf("network address parse error during conversion from string: %v", err)
}
if net.Addr().Is4In6() {
return netip.Prefix{}, fmt.Errorf("IPv4-mapped IPv6 address %q is not allowed", raw)
}
return net, nil
}

View File

@ -79,6 +79,82 @@ func (l *CostEstimator) CallCost(function, overloadId string, args []ref.Val, re
cost := strCost * regexCost
return &cost
}
case "cidr", "isIP", "isCIDR":
// IP and CIDR parsing is a string traversal.
if len(args) >= 1 {
cost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))
return &cost
}
case "ip":
// IP and CIDR parsing is a string traversal.
if len(args) >= 1 {
if overloadId == "cidr_ip" {
// The IP member of the CIDR object is just accessing a field.
// Nominal cost.
cost := uint64(1)
return &cost
}
cost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))
return &cost
}
case "ip.isCanonical":
if len(args) >= 1 {
// We have to parse the string and then compare the parsed string to the original string.
// So we double the cost of parsing the string.
cost := uint64(math.Ceil(float64(actualSize(args[0])) * 2 * common.StringTraversalCostFactor))
return &cost
}
case "masked", "prefixLength", "family", "isUnspecified", "isLoopback", "isLinkLocalMulticast", "isLinkLocalUnicast":
// IP and CIDR accessors are nominal cost.
cost := uint64(1)
return &cost
case "containsIP":
if len(args) >= 2 {
cidrSize := actualSize(args[0])
otherSize := actualSize(args[1])
// This is the base cost of comparing two byte lists.
// We will compare only up to the length of the CIDR prefix in bytes, so use the cidrSize twice.
cost := uint64(math.Ceil(float64(cidrSize+cidrSize) * common.StringTraversalCostFactor))
if overloadId == "cidr_contains_ip_string" {
// If we are comparing a string, we must parse the string to into the right type, so add the cost of traversing the string again.
cost += uint64(math.Ceil(float64(otherSize) * common.StringTraversalCostFactor))
}
return &cost
}
case "containsCIDR":
if len(args) >= 2 {
cidrSize := actualSize(args[0])
otherSize := actualSize(args[1])
// This is the base cost of comparing two byte lists.
// We will compare only up to the length of the CIDR prefix in bytes, so use the cidrSize twice.
cost := uint64(math.Ceil(float64(cidrSize+cidrSize) * common.StringTraversalCostFactor))
// As we are comparing if a CIDR is within another CIDR, we first mask the base CIDR and
// also compare the CIDR bits.
// This has an additional cost of the length of the IP being traversed again, plus 1.
cost += uint64(math.Ceil(float64(cidrSize)*common.StringTraversalCostFactor)) + 1
if overloadId == "cidr_contains_cidr_string" {
// If we are comparing a string, we must parse the string to into the right type, so add the cost of traversing the string again.
cost += uint64(math.Ceil(float64(otherSize) * common.StringTraversalCostFactor))
}
return &cost
}
case "quantity", "isQuantity":
if len(args) >= 1 {
cost := uint64(math.Ceil(float64(actualSize(args[0])) * common.StringTraversalCostFactor))
return &cost
}
case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub":
cost := uint64(1)
return &cost
}
return nil
}
@ -225,6 +301,80 @@ func (l *CostEstimator) EstimateCallCost(function, overloadId string, target *ch
// worst case size of result is that every char is returned as separate find result.
return &checker.CallEstimate{CostEstimate: strCost.Multiply(regexCost), ResultSize: &checker.SizeEstimate{Min: 0, Max: sz.Max}}
}
case "cidr", "isIP", "isCIDR":
if target != nil {
sz := l.sizeEstimate(args[0])
return &checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor)}
}
case "ip":
if target != nil && len(args) >= 1 {
if overloadId == "cidr_ip" {
// The IP member of the CIDR object is just accessing a field.
// Nominal cost.
return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}}
}
sz := l.sizeEstimate(args[0])
return &checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor)}
} else if target != nil {
// The IP member of a CIDR is a just accessing a field, nominal cost.
return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}}
}
case "ip.isCanonical":
if target != nil && len(args) >= 1 {
sz := l.sizeEstimate(args[0])
// We have to parse the string and then compare the parsed string to the original string.
// So we double the cost of parsing the string.
return &checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(2 * common.StringTraversalCostFactor)}
}
case "masked", "prefixLength", "family", "isUnspecified", "isLoopback", "isLinkLocalMulticast", "isLinkLocalUnicast":
// IP and CIDR accessors are nominal cost.
return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}}
case "containsIP":
if target != nil && len(args) >= 1 {
// The base cost of the function is the cost of comparing two byte lists.
// The byte lists will be either ipv4 or ipv6 so will have a length of 4, or 16 bytes.
sz := checker.SizeEstimate{Min: 4, Max: 16}
// We have to compare the two strings to determine if the CIDR/IP is in the other CIDR.
ipCompCost := sz.Add(sz).MultiplyByCostFactor(common.StringTraversalCostFactor)
if overloadId == "cidr_contains_ip_string" {
// If we are comparing a string, we must parse the string to into the right type, so add the cost of traversing the string again.
ipCompCost = ipCompCost.Add(checker.CostEstimate(l.sizeEstimate(args[0])).MultiplyByCostFactor(common.StringTraversalCostFactor))
}
return &checker.CallEstimate{CostEstimate: ipCompCost}
}
case "containsCIDR":
if target != nil && len(args) >= 1 {
// The base cost of the function is the cost of comparing two byte lists.
// The byte lists will be either ipv4 or ipv6 so will have a length of 4, or 16 bytes.
sz := checker.SizeEstimate{Min: 4, Max: 16}
// We have to compare the two strings to determine if the CIDR/IP is in the other CIDR.
ipCompCost := sz.Add(sz).MultiplyByCostFactor(common.StringTraversalCostFactor)
// As we are comparing if a CIDR is within another CIDR, we first mask the base CIDR and
// also compare the CIDR bits.
// This has an additional cost of the length of the IP being traversed again, plus 1.
ipCompCost = ipCompCost.Add(sz.MultiplyByCostFactor(common.StringTraversalCostFactor))
ipCompCost = ipCompCost.Add(checker.CostEstimate{Min: 1, Max: 1})
if overloadId == "cidr_contains_cidr_string" {
// If we are comparing a string, we must parse the string to into the right type, so add the cost of traversing the string again.
ipCompCost = ipCompCost.Add(checker.CostEstimate(l.sizeEstimate(args[0])).MultiplyByCostFactor(common.StringTraversalCostFactor))
}
return &checker.CallEstimate{CostEstimate: ipCompCost}
}
case "quantity", "isQuantity":
if target != nil {
sz := l.sizeEstimate(args[0])
return &checker.CallEstimate{CostEstimate: sz.MultiplyByCostFactor(common.StringTraversalCostFactor)}
}
case "sign", "asInteger", "isInteger", "asApproximateFloat", "isGreaterThan", "isLessThan", "compareTo", "add", "sub":
return &checker.CallEstimate{CostEstimate: checker.CostEstimate{Min: 1, Max: 1}}
}
return nil
}

329
vendor/k8s.io/apiserver/pkg/cel/library/ip.go generated vendored Normal file
View File

@ -0,0 +1,329 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package library
import (
"fmt"
"net/netip"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
apiservercel "k8s.io/apiserver/pkg/cel"
)
// IP provides a CEL function library extension of IP address parsing functions.
//
// ip
//
// Converts a string to an IP address or results in an error if the string is not a valid IP address.
// The IP address must be an IPv4 or IPv6 address.
// IPv4-mapped IPv6 addresses (e.g. ::ffff:1.2.3.4) are not allowed.
// IP addresses with zones (e.g. fe80::1%eth0) are not allowed.
// Leading zeros in IPv4 address octets are not allowed.
//
// ip(<string>) <IPAddr>
//
// Examples:
//
// ip('127.0.0.1') // returns an IPv4 address
// ip('::1') // returns an IPv6 address
// ip('127.0.0.256') // error
// ip(':::1') // error
//
// isIP
//
// Returns true if a string is a valid IP address.
// The IP address must be an IPv4 or IPv6 address.
// IPv4-mapped IPv6 addresses (e.g. ::ffff:1.2.3.4) are not allowed.
// IP addresses with zones (e.g. fe80::1%eth0) are not allowed.
// Leading zeros in IPv4 address octets are not allowed.
//
// isIP(<string>) <bool>
//
// Examples:
//
// isIP('127.0.0.1') // returns true
// isIP('::1') // returns true
// isIP('127.0.0.256') // returns false
// isIP(':::1') // returns false
//
// ip.isCanonical
//
// Returns true if the IP address is in its canonical form.
// There is exactly one canonical form for every IP address, so fields containing
// IPs in canonical form can just be treated as strings when checking for equality or uniqueness.
//
// ip.isCanonical(<string>) <bool>
//
// Examples:
//
// ip.isCanonical('127.0.0.1') // returns true; all valid IPv4 addresses are canonical
// ip.isCanonical('2001:db8::abcd') // returns true
// ip.isCanonical('2001:DB8::ABCD') // returns false
// ip.isCanonical('2001:db8::0:0:0:abcd') // returns false
//
// family / isUnspecified / isLoopback / isLinkLocalMulticast / isLinkLocalUnicast / isGlobalUnicast
//
// - family: returns the IP addresses' family (IPv4 or IPv6) as an integer, either '4' or '6'.
//
// - isUnspecified: returns true if the IP address is the unspecified address.
// Either the IPv4 address "0.0.0.0" or the IPv6 address "::".
//
// - isLoopback: returns true if the IP address is the loopback address.
// Either an IPv4 address with a value of 127.x.x.x or an IPv6 address with a value of ::1.
//
// - isLinkLocalMulticast: returns true if the IP address is a link-local multicast address.
// Either an IPv4 address with a value of 224.0.0.x or an IPv6 address in the network ff00::/8.
//
// - isLinkLocalUnicast: returns true if the IP address is a link-local unicast address.
// Either an IPv4 address with a value of 169.254.x.x or an IPv6 address in the network fe80::/10.
//
// - isGlobalUnicast: returns true if the IP address is a global unicast address.
// Either an IPv4 address that is not zero or 255.255.255.255 or an IPv6 address that is not a link-local unicast, loopback or multicast address.
//
// Examples:
//
// ip('127.0.0.1').family() // returns '4”
// ip('::1').family() // returns '6'
// ip('127.0.0.1').family() == 4 // returns true
// ip('::1').family() == 6 // returns true
// ip('0.0.0.0').isUnspecified() // returns true
// ip('127.0.0.1').isUnspecified() // returns false
// ip('::').isUnspecified() // returns true
// ip('::1').isUnspecified() // returns false
// ip('127.0.0.1').isLoopback() // returns true
// ip('192.168.0.1').isLoopback() // returns false
// ip('::1').isLoopback() // returns true
// ip('2001:db8::abcd').isLoopback() // returns false
// ip('224.0.0.1').isLinkLocalMulticast() // returns true
// ip('224.0.1.1').isLinkLocalMulticast() // returns false
// ip('ff02::1').isLinkLocalMulticast() // returns true
// ip('fd00::1').isLinkLocalMulticast() // returns false
// ip('169.254.169.254').isLinkLocalUnicast() // returns true
// ip('192.168.0.1').isLinkLocalUnicast() // returns false
// ip('fe80::1').isLinkLocalUnicast() // returns true
// ip('fd80::1').isLinkLocalUnicast() // returns false
// ip('192.168.0.1').isGlobalUnicast() // returns true
// ip('255.255.255.255').isGlobalUnicast() // returns false
// ip('2001:db8::abcd').isGlobalUnicast() // returns true
// ip('ff00::1').isGlobalUnicast() // returns false
func IP() cel.EnvOption {
return cel.Lib(ipLib)
}
var ipLib = &ip{}
type ip struct{}
func (*ip) LibraryName() string {
return "net.ip"
}
var ipLibraryDecls = map[string][]cel.FunctionOpt{
"ip": {
cel.Overload("string_to_ip", []*cel.Type{cel.StringType}, apiservercel.IPType,
cel.UnaryBinding(stringToIP)),
},
"family": {
cel.MemberOverload("ip_family", []*cel.Type{apiservercel.IPType}, cel.IntType,
cel.UnaryBinding(family)),
},
"ip.isCanonical": {
cel.Overload("ip_is_canonical", []*cel.Type{cel.StringType}, cel.BoolType,
cel.UnaryBinding(ipIsCanonical)),
},
"isUnspecified": {
cel.MemberOverload("ip_is_unspecified", []*cel.Type{apiservercel.IPType}, cel.BoolType,
cel.UnaryBinding(isUnspecified)),
},
"isLoopback": {
cel.MemberOverload("ip_is_loopback", []*cel.Type{apiservercel.IPType}, cel.BoolType,
cel.UnaryBinding(isLoopback)),
},
"isLinkLocalMulticast": {
cel.MemberOverload("ip_is_link_local_multicast", []*cel.Type{apiservercel.IPType}, cel.BoolType,
cel.UnaryBinding(isLinkLocalMulticast)),
},
"isLinkLocalUnicast": {
cel.MemberOverload("ip_is_link_local_unicast", []*cel.Type{apiservercel.IPType}, cel.BoolType,
cel.UnaryBinding(isLinkLocalUnicast)),
},
"isGlobalUnicast": {
cel.MemberOverload("ip_is_global_unicast", []*cel.Type{apiservercel.IPType}, cel.BoolType,
cel.UnaryBinding(isGlobalUnicast)),
},
"isIP": {
cel.Overload("is_ip", []*cel.Type{cel.StringType}, cel.BoolType,
cel.UnaryBinding(isIP)),
},
"string": {
cel.Overload("ip_to_string", []*cel.Type{apiservercel.IPType}, cel.StringType,
cel.UnaryBinding(ipToString)),
},
}
func (*ip) CompileOptions() []cel.EnvOption {
options := []cel.EnvOption{cel.Types(apiservercel.IPType),
cel.Variable(apiservercel.IPType.TypeName(), types.NewTypeTypeWithParam(apiservercel.IPType)),
}
for name, overloads := range ipLibraryDecls {
options = append(options, cel.Function(name, overloads...))
}
return options
}
func (*ip) ProgramOptions() []cel.ProgramOption {
return []cel.ProgramOption{}
}
func stringToIP(arg ref.Val) ref.Val {
s, ok := arg.Value().(string)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
addr, err := parseIPAddr(s)
if err != nil {
// Don't add context, we control the error message already.
return types.NewErr("%v", err)
}
return apiservercel.IP{
Addr: addr,
}
}
func ipToString(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.String(ip.Addr.String())
}
func family(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
switch {
case ip.Addr.Is4():
return types.Int(4)
case ip.Addr.Is6():
return types.Int(6)
default:
return types.NewErr("IP address %q is not an IPv4 or IPv6 address", ip.Addr.String())
}
}
func ipIsCanonical(arg ref.Val) ref.Val {
s, ok := arg.Value().(string)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
addr, err := parseIPAddr(s)
if err != nil {
// Don't add context, we control the error message already.
return types.NewErr("%v", err)
}
// Addr.String() always returns the canonical form of the IP address.
// Therefore comparing this with the original string representation
// will tell us if the IP address is in its canonical form.
return types.Bool(addr.String() == s)
}
func isIP(arg ref.Val) ref.Val {
s, ok := arg.Value().(string)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
_, err := parseIPAddr(s)
return types.Bool(err == nil)
}
func isUnspecified(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(ip.Addr.IsUnspecified())
}
func isLoopback(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(ip.Addr.IsLoopback())
}
func isLinkLocalMulticast(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(ip.Addr.IsLinkLocalMulticast())
}
func isLinkLocalUnicast(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(ip.Addr.IsLinkLocalUnicast())
}
func isGlobalUnicast(arg ref.Val) ref.Val {
ip, ok := arg.(apiservercel.IP)
if !ok {
return types.MaybeNoSuchOverloadErr(arg)
}
return types.Bool(ip.Addr.IsGlobalUnicast())
}
// parseIPAddr parses a string into an IP address.
// We use this function to parse IP addresses in the CEL library
// so that we can share the common logic of rejecting IP addresses
// that contain zones or are IPv4-mapped IPv6 addresses.
func parseIPAddr(raw string) (netip.Addr, error) {
addr, err := netip.ParseAddr(raw)
if err != nil {
return netip.Addr{}, fmt.Errorf("IP Address %q parse error during conversion from string: %v", raw, err)
}
if addr.Zone() != "" {
return netip.Addr{}, fmt.Errorf("IP address %q with zone value is not allowed", raw)
}
if addr.Is4In6() {
return netip.Addr{}, fmt.Errorf("IPv4-mapped IPv6 address %q is not allowed", raw)
}
return addr, nil
}