Skip to content

Commit

Permalink
validation: block invalid maglev table sizes (istio#50750)
Browse files Browse the repository at this point in the history
  • Loading branch information
howardjohn authored Apr 30, 2024
1 parent 1c4dc50 commit f3f71b0
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
30 changes: 30 additions & 0 deletions pkg/config/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math"
"net"
"net/http"
"net/url"
Expand Down Expand Up @@ -1064,12 +1065,41 @@ func validateLoadBalancer(settings *networking.LoadBalancerSettings, outlier *ne
if consistentHash.MinimumRingSize != 0 && consistentHash.GetHashAlgorithm() != nil {
errs = AppendValidation(errs, fmt.Errorf("only one of MinimumRingSize or Maglev/Ringhash can be specified"))
}
if ml := consistentHash.GetMaglev(); ml != nil {
if ml.TableSize == 0 {
errs = AppendValidation(errs, fmt.Errorf("tableSize must be set for maglev"))
}
if ml.TableSize >= 5000011 {
errs = AppendValidation(errs, fmt.Errorf("tableSize must be less than 5000011 for maglev"))
}
if !isPrime(ml.TableSize) {
errs = AppendValidation(errs, fmt.Errorf("tableSize must be a prime number for maglev"))
}
}
}

errs = AppendValidation(errs, agent.ValidateLocalityLbSetting(settings.LocalityLbSetting, outlier))
return
}

// Copied from https://github.com/envoyproxy/envoy/blob/5451efd9b8f8a444431197050e45ba974ed4e9d8/source/common/common/utility.cc#L601-L615
// to ensure we 100% match Envoy's implementation
func isPrime(x uint64) bool {
if x != 0 && x < 4 {
return true // eliminates special-casing 2.
} else if (x & 1) == 0 {
return false // eliminates even numbers >2.
}

limit := uint64(math.Sqrt(float64(x)))
for factor := uint64(3); factor <= limit; factor += 2 {
if (x % factor) == 0 {
return false
}
}
return true
}

func validateSubset(subset *networking.Subset) error {
return appendErrors(validateSubsetName(subset.Name),
labels.Instance(subset.Labels).Validate(),
Expand Down
13 changes: 13 additions & 0 deletions pkg/config/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3195,6 +3195,19 @@ func TestValidateLoadBalancer(t *testing.T) {
},
valid: false,
},

{
name: "invalid load balancer with consistentHash load balancing, maglev not prime", in: &networking.LoadBalancerSettings{
LbPolicy: &networking.LoadBalancerSettings_ConsistentHash{
ConsistentHash: &networking.LoadBalancerSettings_ConsistentHashLB{
HashAlgorithm: &networking.LoadBalancerSettings_ConsistentHashLB_Maglev{
Maglev: &networking.LoadBalancerSettings_ConsistentHashLB_MagLev{TableSize: 1000},
},
},
},
},
valid: false,
},
}

for _, c := range cases {
Expand Down

0 comments on commit f3f71b0

Please sign in to comment.