Skip to content

Commit 98d5db2

Browse files
committed
Adding a token getter to get service account tokens
1 parent 872b7f7 commit 98d5db2

File tree

2 files changed

+205
-0
lines changed

2 files changed

+205
-0
lines changed
+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package authentication
2+
3+
import (
4+
"context"
5+
"sync"
6+
"time"
7+
8+
authv1 "k8s.io/api/authentication/v1"
9+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
10+
"k8s.io/apimachinery/pkg/types"
11+
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
12+
"k8s.io/utils/ptr"
13+
)
14+
15+
type TokenGetter struct {
16+
client corev1.ServiceAccountsGetter
17+
expirationSeconds int64
18+
tokens map[types.NamespacedName]*authv1.TokenRequestStatus
19+
tokenLocks keyLock[types.NamespacedName]
20+
mu sync.RWMutex
21+
}
22+
23+
// Returns a token getter that can fetch tokens given a service account.
24+
// The token getter also caches tokens which helps reduce the number of requests to the API Server.
25+
// In case a cached token is expiring a fresh token is created.
26+
func NewTokenGetter(client corev1.ServiceAccountsGetter, expirationSeconds int64) *TokenGetter {
27+
return &TokenGetter{
28+
client: client,
29+
expirationSeconds: expirationSeconds,
30+
tokens: map[types.NamespacedName]*authv1.TokenRequestStatus{},
31+
tokenLocks: newKeyLock[types.NamespacedName](),
32+
}
33+
}
34+
35+
type keyLock[K comparable] struct {
36+
locks map[K]*sync.Mutex
37+
mu sync.Mutex
38+
}
39+
40+
func newKeyLock[K comparable]() keyLock[K] {
41+
return keyLock[K]{locks: map[K]*sync.Mutex{}}
42+
}
43+
44+
func (k *keyLock[K]) Lock(key K) {
45+
k.getLock(key).Lock()
46+
}
47+
48+
func (k *keyLock[K]) Unlock(key K) {
49+
k.getLock(key).Unlock()
50+
}
51+
52+
func (k *keyLock[K]) getLock(key K) *sync.Mutex {
53+
k.mu.Lock()
54+
defer k.mu.Unlock()
55+
56+
lock, ok := k.locks[key]
57+
if !ok {
58+
lock = &sync.Mutex{}
59+
k.locks[key] = lock
60+
}
61+
return lock
62+
}
63+
64+
// Returns a token from the cache if available and not expiring, otherwise creates a new token and caches it.
65+
func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string, error) {
66+
t.tokenLocks.Lock(key)
67+
defer t.tokenLocks.Unlock(key)
68+
69+
t.mu.RLock()
70+
token, ok := t.tokens[key]
71+
t.mu.RUnlock()
72+
73+
expireTime := time.Time{}
74+
if ok {
75+
expireTime = token.ExpirationTimestamp.Time
76+
}
77+
78+
fiveMinutesAfterNow := metav1.Now().Add(5 * time.Minute)
79+
if expireTime.Before(fiveMinutesAfterNow) {
80+
var err error
81+
token, err = t.getToken(ctx, key)
82+
if err != nil {
83+
return "", err
84+
}
85+
t.mu.Lock()
86+
t.tokens[key] = token
87+
t.mu.Unlock()
88+
}
89+
90+
return token.Token, nil
91+
}
92+
93+
func (t *TokenGetter) getToken(ctx context.Context, key types.NamespacedName) (*authv1.TokenRequestStatus, error) {
94+
req, err := t.client.ServiceAccounts(key.Namespace).CreateToken(ctx, key.Name, &authv1.TokenRequest{Spec: authv1.TokenRequestSpec{ExpirationSeconds: ptr.To[int64](3600)}}, metav1.CreateOptions{})
95+
if err != nil {
96+
return nil, err
97+
}
98+
return &req.Status, nil
99+
}
+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package authentication
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
"time"
8+
9+
"github.com/stretchr/testify/assert"
10+
authv1 "k8s.io/api/authentication/v1"
11+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
12+
"k8s.io/apimachinery/pkg/runtime"
13+
"k8s.io/apimachinery/pkg/types"
14+
"k8s.io/client-go/kubernetes/fake"
15+
ctest "k8s.io/client-go/testing"
16+
)
17+
18+
func TestNewTokenGetter(t *testing.T) {
19+
fakeClient := fake.NewSimpleClientset()
20+
fakeClient.PrependReactor("create", "serviceaccounts/token", func(action ctest.Action) (handled bool, ret runtime.Object, err error) {
21+
act, ok := action.(ctest.CreateActionImpl)
22+
if !ok {
23+
return false, nil, nil
24+
}
25+
tokenRequest := act.GetObject().(*authv1.TokenRequest)
26+
if act.Name == "test-service-account-1" {
27+
tokenRequest.Status = authv1.TokenRequestStatus{
28+
Token: "test-token-1",
29+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(5 * time.Minute)),
30+
}
31+
}
32+
if act.Name == "test-service-account-2" {
33+
tokenRequest.Status = authv1.TokenRequestStatus{
34+
Token: "test-token-2",
35+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(1 * time.Second)),
36+
}
37+
}
38+
if act.Name == "test-service-account-3" {
39+
tokenRequest = nil
40+
err = fmt.Errorf("error when fetching token")
41+
}
42+
43+
return true, tokenRequest, err
44+
})
45+
tg := NewTokenGetter(fakeClient.CoreV1(), int64(5*time.Minute))
46+
t.Log("Testing NewTokenGetter with fake client")
47+
token, err := tg.Get(context.Background(), types.NamespacedName{
48+
Namespace: "test-namespace-1",
49+
Name: "test-service-account-1",
50+
})
51+
if err != nil {
52+
t.Fatalf("failed to get token: %v", err)
53+
return
54+
}
55+
t.Log("token:", token)
56+
if token != "test-token-1" {
57+
t.Errorf("token does not match")
58+
}
59+
t.Log("Testing getting token from cache")
60+
token, err = tg.Get(context.Background(), types.NamespacedName{
61+
Namespace: "test-namespace-1",
62+
Name: "test-service-account-1",
63+
})
64+
if err != nil {
65+
t.Fatalf("failed to get token from cache: %v", err)
66+
return
67+
}
68+
t.Log("token:", token)
69+
if token != "test-token-1" {
70+
t.Errorf("token does not match")
71+
}
72+
t.Log("Testing getting short lived token from fake client")
73+
token, err = tg.Get(context.Background(), types.NamespacedName{
74+
Namespace: "test-namespace-2",
75+
Name: "test-service-account-2",
76+
})
77+
if err != nil {
78+
t.Fatalf("failed to get token: %v", err)
79+
return
80+
}
81+
t.Log("token:", token)
82+
if token != "test-token-2" {
83+
t.Errorf("token does not match")
84+
}
85+
//wait for token to expire
86+
time.Sleep(1 * time.Second)
87+
t.Log("Testing getting expired token from cache")
88+
token, err = tg.Get(context.Background(), types.NamespacedName{
89+
Namespace: "test-namespace-2",
90+
Name: "test-service-account-2",
91+
})
92+
if err != nil {
93+
t.Fatalf("failed to refresh token: %v", err)
94+
return
95+
}
96+
t.Log("token:", token)
97+
if token != "test-token-2" {
98+
t.Errorf("token does not match")
99+
}
100+
t.Log("Testing error when getting token from fake client")
101+
token, err = tg.Get(context.Background(), types.NamespacedName{
102+
Namespace: "test-namespace-3",
103+
Name: "test-service-account-3",
104+
})
105+
assert.EqualError(t, err, "error when fetching token")
106+
}

0 commit comments

Comments
 (0)