Sort idpcache keys to make things as deterministic as possible.

Signed-off-by: Matt Moyer <moyerm@vmware.com>
This commit is contained in:
Matt Moyer 2020-09-22 09:50:34 -05:00
parent 9beb3855b5
commit 16ef2baf8a
No known key found for this signature in database
GPG Key ID: EAE88AD172C5AE2D
2 changed files with 28 additions and 0 deletions

View File

@ -7,6 +7,7 @@ package idpcache
import ( import (
"context" "context"
"fmt" "fmt"
"sort"
"sync" "sync"
"k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/pkg/authentication/authenticator"
@ -68,6 +69,14 @@ func (c *Cache) Keys() []Key {
result = append(result, key.(Key)) result = append(result, key.(Key))
return true return true
}) })
// Sort the results for consistency.
sort.Slice(result, func(i, j int) bool {
return result[i].APIGroup < result[j].APIGroup ||
result[i].Kind < result[j].Kind ||
result[i].Namespace < result[j].Namespace ||
result[i].Name < result[j].Name
})
return result return result
} }

View File

@ -6,6 +6,7 @@ package idpcache
import ( import (
"context" "context"
"fmt" "fmt"
"math/rand"
"testing" "testing"
"time" "time"
@ -46,6 +47,24 @@ func TestCache(t *testing.T) {
cache.Delete(key) cache.Delete(key)
} }
require.Zero(t, len(cache.Keys())) require.Zero(t, len(cache.Keys()))
// Fill the cache back up with a fixed set of keys, but inserted in shuffled order.
keysInExpectedOrder := []Key{
{APIGroup: "a", Kind: "a", Namespace: "a", Name: "a"},
{APIGroup: "b", Kind: "a", Namespace: "a", Name: "a"},
{APIGroup: "b", Kind: "b", Namespace: "a", Name: "a"},
{APIGroup: "b", Kind: "b", Namespace: "b", Name: "a"},
{APIGroup: "b", Kind: "b", Namespace: "b", Name: "b"},
}
for tries := 0; tries < 10; tries++ {
cache := New()
for _, i := range rand.Perm(len(keysInExpectedOrder)) {
cache.Store(keysInExpectedOrder[i], nil)
}
// Expect that they come back out in sorted order.
require.Equal(t, keysInExpectedOrder, cache.Keys())
}
} }
func TestAuthenticateTokenCredentialRequest(t *testing.T) { func TestAuthenticateTokenCredentialRequest(t *testing.T) {