Skip to content

Commit 1670ba5

Browse files
committed
Add token cache component
1 parent 15d8509 commit 1670ba5

File tree

7 files changed

+445
-0
lines changed

7 files changed

+445
-0
lines changed

staging/BUILD

+1
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ filegroup(
117117
"//staging/src/k8s.io/apiserver/pkg/authentication/request/websocket:all-srcs",
118118
"//staging/src/k8s.io/apiserver/pkg/authentication/request/x509:all-srcs",
119119
"//staging/src/k8s.io/apiserver/pkg/authentication/serviceaccount:all-srcs",
120+
"//staging/src/k8s.io/apiserver/pkg/authentication/token/cache:all-srcs",
120121
"//staging/src/k8s.io/apiserver/pkg/authentication/token/tokenfile:all-srcs",
121122
"//staging/src/k8s.io/apiserver/pkg/authentication/user:all-srcs",
122123
"//staging/src/k8s.io/apiserver/pkg/authorization/authorizer:all-srcs",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package(default_visibility = ["//visibility:public"])
2+
3+
licenses(["notice"])
4+
5+
load(
6+
"@io_bazel_rules_go//go:def.bzl",
7+
"go_library",
8+
"go_test",
9+
)
10+
11+
go_test(
12+
name = "go_default_test",
13+
srcs = [
14+
"cache_test.go",
15+
"cached_token_authenticator_test.go",
16+
],
17+
library = ":go_default_library",
18+
tags = ["automanaged"],
19+
deps = [
20+
"//vendor/github.com/pborman/uuid:go_default_library",
21+
"//vendor/k8s.io/apimachinery/pkg/util/clock:go_default_library",
22+
"//vendor/k8s.io/apiserver/pkg/authentication/authenticator:go_default_library",
23+
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
24+
],
25+
)
26+
27+
go_library(
28+
name = "go_default_library",
29+
srcs = [
30+
"cache_simple.go",
31+
"cache_striped.go",
32+
"cached_token_authenticator.go",
33+
],
34+
tags = ["automanaged"],
35+
deps = [
36+
"//vendor/k8s.io/apimachinery/pkg/util/cache:go_default_library",
37+
"//vendor/k8s.io/apimachinery/pkg/util/clock:go_default_library",
38+
"//vendor/k8s.io/apiserver/pkg/authentication/authenticator:go_default_library",
39+
"//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library",
40+
],
41+
)
42+
43+
filegroup(
44+
name = "package-srcs",
45+
srcs = glob(["**"]),
46+
tags = ["automanaged"],
47+
visibility = ["//visibility:private"],
48+
)
49+
50+
filegroup(
51+
name = "all-srcs",
52+
srcs = [":package-srcs"],
53+
tags = ["automanaged"],
54+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Copyright 2017 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cache
18+
19+
import (
20+
"time"
21+
22+
lrucache "k8s.io/apimachinery/pkg/util/cache"
23+
"k8s.io/apimachinery/pkg/util/clock"
24+
)
25+
26+
type simpleCache struct {
27+
lru *lrucache.LRUExpireCache
28+
}
29+
30+
func newSimpleCache(size int, clock clock.Clock) cache {
31+
return &simpleCache{lru: lrucache.NewLRUExpireCacheWithClock(size, clock)}
32+
}
33+
34+
func (c *simpleCache) get(key string) (*cacheRecord, bool) {
35+
record, ok := c.lru.Get(key)
36+
if !ok {
37+
return nil, false
38+
}
39+
value, ok := record.(*cacheRecord)
40+
return value, ok
41+
}
42+
43+
func (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) {
44+
c.lru.Add(key, value, ttl)
45+
}
46+
47+
func (c *simpleCache) remove(key string) {
48+
c.lru.Remove(key)
49+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Copyright 2017 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cache
18+
19+
import (
20+
"hash/fnv"
21+
"time"
22+
)
23+
24+
// split cache lookups across N striped caches
25+
type stripedCache struct {
26+
stripeCount uint32
27+
keyFunc func(string) uint32
28+
caches []cache
29+
}
30+
31+
type keyFunc func(string) uint32
32+
type newCacheFunc func() cache
33+
34+
func newStripedCache(stripeCount int, keyFunc keyFunc, newCacheFunc newCacheFunc) cache {
35+
caches := []cache{}
36+
for i := 0; i < stripeCount; i++ {
37+
caches = append(caches, newCacheFunc())
38+
}
39+
return &stripedCache{
40+
stripeCount: uint32(stripeCount),
41+
keyFunc: keyFunc,
42+
caches: caches,
43+
}
44+
}
45+
46+
func (c *stripedCache) get(key string) (*cacheRecord, bool) {
47+
return c.caches[c.keyFunc(key)%c.stripeCount].get(key)
48+
}
49+
func (c *stripedCache) set(key string, value *cacheRecord, ttl time.Duration) {
50+
c.caches[c.keyFunc(key)%c.stripeCount].set(key, value, ttl)
51+
}
52+
func (c *stripedCache) remove(key string) {
53+
c.caches[c.keyFunc(key)%c.stripeCount].remove(key)
54+
}
55+
56+
func fnvKeyFunc(key string) uint32 {
57+
f := fnv.New32()
58+
f.Write([]byte(key))
59+
return f.Sum32()
60+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
Copyright 2017 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cache
18+
19+
import (
20+
"math/rand"
21+
"testing"
22+
"time"
23+
24+
"k8s.io/apimachinery/pkg/util/clock"
25+
"k8s.io/apiserver/pkg/authentication/user"
26+
27+
"github.com/pborman/uuid"
28+
)
29+
30+
func TestSimpleCache(t *testing.T) {
31+
testCache(newSimpleCache(4096, clock.RealClock{}), t)
32+
}
33+
34+
func BenchmarkSimpleCache(b *testing.B) {
35+
benchmarkCache(newSimpleCache(4096, clock.RealClock{}), b)
36+
}
37+
38+
func TestStripedCache(t *testing.T) {
39+
testCache(newStripedCache(32, fnvKeyFunc, func() cache { return newSimpleCache(128, clock.RealClock{}) }), t)
40+
}
41+
42+
func BenchmarkStripedCache(b *testing.B) {
43+
benchmarkCache(newStripedCache(32, fnvKeyFunc, func() cache { return newSimpleCache(128, clock.RealClock{}) }), b)
44+
}
45+
46+
func benchmarkCache(cache cache, b *testing.B) {
47+
keys := []string{}
48+
for i := 0; i < b.N; i++ {
49+
key := uuid.NewRandom().String()
50+
keys = append(keys, key)
51+
}
52+
53+
b.ResetTimer()
54+
55+
b.SetParallelism(500)
56+
b.RunParallel(func(pb *testing.PB) {
57+
for pb.Next() {
58+
key := keys[rand.Intn(b.N)]
59+
_, ok := cache.get(key)
60+
if ok {
61+
cache.remove(key)
62+
} else {
63+
cache.set(key, &cacheRecord{}, time.Second)
64+
}
65+
}
66+
})
67+
}
68+
69+
func testCache(cache cache, t *testing.T) {
70+
if result, ok := cache.get("foo"); ok || result != nil {
71+
t.Errorf("Expected null, false, got %#v, %v", result, ok)
72+
}
73+
74+
record1 := &cacheRecord{user: &user.DefaultInfo{Name: "bob"}}
75+
record2 := &cacheRecord{user: &user.DefaultInfo{Name: "alice"}}
76+
77+
// when empty, record is stored
78+
cache.set("foo", record1, time.Hour)
79+
if result, ok := cache.get("foo"); !ok || result != record1 {
80+
t.Errorf("Expected %#v, true, got %#v, %v", record1, ok)
81+
}
82+
83+
// newer record overrides
84+
cache.set("foo", record2, time.Hour)
85+
if result, ok := cache.get("foo"); !ok || result != record2 {
86+
t.Errorf("Expected %#v, true, got %#v, %v", record2, ok)
87+
}
88+
89+
// removing the current value removes
90+
cache.remove("foo")
91+
if result, ok := cache.get("foo"); ok || result != nil {
92+
t.Errorf("Expected null, false, got %#v, %v", result, ok)
93+
}
94+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
Copyright 2017 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cache
18+
19+
import (
20+
"time"
21+
22+
utilclock "k8s.io/apimachinery/pkg/util/clock"
23+
"k8s.io/apiserver/pkg/authentication/authenticator"
24+
"k8s.io/apiserver/pkg/authentication/user"
25+
)
26+
27+
// cacheRecord holds the three return values of the authenticator.Token AuthenticateToken method
28+
type cacheRecord struct {
29+
user user.Info
30+
ok bool
31+
err error
32+
}
33+
34+
type cachedTokenAuthenticator struct {
35+
authenticator authenticator.Token
36+
37+
successTTL time.Duration
38+
failureTTL time.Duration
39+
40+
cache cache
41+
}
42+
43+
type cache interface {
44+
// given a key, return the record, and whether or not it existed
45+
get(key string) (value *cacheRecord, exists bool)
46+
// caches the record for the key
47+
set(key string, value *cacheRecord, ttl time.Duration)
48+
// removes the record for the key
49+
remove(key string)
50+
}
51+
52+
// New returns a token authenticator that caches the results of the specified authenticator. A ttl of 0 bypasses the cache.
53+
func New(authenticator authenticator.Token, successTTL, failureTTL time.Duration) authenticator.Token {
54+
return newWithClock(authenticator, successTTL, failureTTL, utilclock.RealClock{})
55+
}
56+
57+
func newWithClock(authenticator authenticator.Token, successTTL, failureTTL time.Duration, clock utilclock.Clock) authenticator.Token {
58+
return &cachedTokenAuthenticator{
59+
authenticator: authenticator,
60+
successTTL: successTTL,
61+
failureTTL: failureTTL,
62+
cache: newStripedCache(32, fnvKeyFunc, func() cache { return newSimpleCache(128, clock) }),
63+
}
64+
}
65+
66+
// AuthenticateToken implements authenticator.Token
67+
func (a *cachedTokenAuthenticator) AuthenticateToken(token string) (user.Info, bool, error) {
68+
if record, ok := a.cache.get(token); ok {
69+
return record.user, record.ok, record.err
70+
}
71+
72+
user, ok, err := a.authenticator.AuthenticateToken(token)
73+
74+
switch {
75+
case ok && a.successTTL > 0:
76+
a.cache.set(token, &cacheRecord{user: user, ok: ok, err: err}, a.successTTL)
77+
case !ok && a.failureTTL > 0:
78+
a.cache.set(token, &cacheRecord{user: user, ok: ok, err: err}, a.failureTTL)
79+
}
80+
81+
return user, ok, err
82+
}

0 commit comments

Comments
 (0)