Skip to content

Commit d3c041f

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

File tree

2 files changed

+189
-0
lines changed

2 files changed

+189
-0
lines changed
+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package authentication
2+
3+
import (
4+
"context"
5+
"sync"
6+
"time"
7+
8+
authenticationv1 "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+
expirationDuration time.Duration
18+
tokens map[types.NamespacedName]*authenticationv1.TokenRequestStatus
19+
mu sync.RWMutex
20+
}
21+
22+
type TokenGetterOption func(*TokenGetter)
23+
24+
const (
25+
DurationPercentage = 10
26+
ExpiredDuration = 90 * time.Minute
27+
)
28+
29+
// Returns a token getter that can fetch tokens given a service account.
30+
// The token getter also caches tokens which helps reduce the number of requests to the API Server.
31+
// In case a cached token is expiring a fresh token is created.
32+
func NewTokenGetter(client corev1.ServiceAccountsGetter, options ...TokenGetterOption) *TokenGetter {
33+
tokenGetter := &TokenGetter{
34+
client: client,
35+
expirationDuration: 5 * time.Minute, // default token ttl
36+
tokens: map[types.NamespacedName]*authenticationv1.TokenRequestStatus{},
37+
}
38+
39+
for _, opt := range options {
40+
opt(tokenGetter)
41+
}
42+
43+
return tokenGetter
44+
}
45+
46+
func WithExpirationDuration(expirationDuration time.Duration) TokenGetterOption {
47+
return func(tg *TokenGetter) {
48+
tg.expirationDuration = expirationDuration
49+
}
50+
}
51+
52+
// Get returns a token from the cache if available and not expiring, otherwise creates a new token
53+
func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string, error) {
54+
t.mu.RLock()
55+
token, ok := t.tokens[key]
56+
t.mu.RUnlock()
57+
58+
expireTime := time.Time{}
59+
if ok {
60+
expireTime = token.ExpirationTimestamp.Time
61+
}
62+
63+
// Create a new token if the cached token expires within DurationPercentage of expirationDuration from now
64+
rotationThresholdAfterNow := metav1.Now().Add(t.expirationDuration * (DurationPercentage / 100))
65+
if expireTime.Before(rotationThresholdAfterNow) {
66+
var err error
67+
token, err = t.getToken(ctx, key)
68+
if err != nil {
69+
return "", err
70+
}
71+
t.mu.Lock()
72+
t.tokens[key] = token
73+
t.mu.Unlock()
74+
}
75+
76+
// Delete tokens that have been expired for more than ExpiredDuration
77+
t.reapExpiredTokens(ExpiredDuration)
78+
79+
return token.Token, nil
80+
}
81+
82+
func (t *TokenGetter) getToken(ctx context.Context, key types.NamespacedName) (*authenticationv1.TokenRequestStatus, error) {
83+
req, err := t.client.ServiceAccounts(key.Namespace).CreateToken(ctx,
84+
key.Name,
85+
&authenticationv1.TokenRequest{
86+
Spec: authenticationv1.TokenRequestSpec{ExpirationSeconds: ptr.To[int64](int64(t.expirationDuration))},
87+
}, metav1.CreateOptions{})
88+
if err != nil {
89+
return nil, err
90+
}
91+
return &req.Status, nil
92+
}
93+
94+
func (t *TokenGetter) reapExpiredTokens(expiredDuration time.Duration) {
95+
t.mu.Lock()
96+
defer t.mu.Unlock()
97+
for key, token := range t.tokens {
98+
if metav1.Now().Sub(token.ExpirationTimestamp.Time) > expiredDuration {
99+
delete(t.tokens, key)
100+
}
101+
}
102+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package authentication
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
"time"
8+
9+
"github.com/stretchr/testify/assert"
10+
authenticationv1 "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 TestTokenGetterGet(t *testing.T) {
19+
fakeClient := fake.NewSimpleClientset()
20+
fakeClient.PrependReactor("create", "serviceaccounts/token",
21+
func(action ctest.Action) (bool, runtime.Object, error) {
22+
act, ok := action.(ctest.CreateActionImpl)
23+
if !ok {
24+
return false, nil, nil
25+
}
26+
tokenRequest := act.GetObject().(*authenticationv1.TokenRequest)
27+
var err error
28+
if act.Name == "test-service-account-1" {
29+
tokenRequest.Status = authenticationv1.TokenRequestStatus{
30+
Token: "test-token-1",
31+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(5 * time.Minute)),
32+
}
33+
}
34+
if act.Name == "test-service-account-2" {
35+
tokenRequest.Status = authenticationv1.TokenRequestStatus{
36+
Token: "test-token-2",
37+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(1 * time.Second)),
38+
}
39+
}
40+
if act.Name == "test-service-account-3" {
41+
tokenRequest.Status = authenticationv1.TokenRequestStatus{
42+
Token: "test-token-3",
43+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(-ExpiredDuration)),
44+
}
45+
}
46+
if act.Name == "test-service-account-4" {
47+
tokenRequest = nil
48+
err = fmt.Errorf("error when fetching token")
49+
}
50+
return true, tokenRequest, err
51+
})
52+
53+
tg := NewTokenGetter(fakeClient.CoreV1(),
54+
WithExpirationDuration(5*time.Minute))
55+
56+
tests := []struct {
57+
testName string
58+
serviceAccountName string
59+
namespace string
60+
want string
61+
errorMsg string
62+
}{
63+
{"Testing getting token with fake client", "test-service-account-1",
64+
"test-namespace-1", "test-token-1", "failed to get token"},
65+
{"Testing getting token from cache", "test-service-account-1",
66+
"test-namespace-1", "test-token-1", "failed to get token"},
67+
{"Testing getting short lived token from fake client", "test-service-account-2",
68+
"test-namespace-2", "test-token-2", "failed to get token"},
69+
{"Testing getting expired token from cache", "test-service-account-2",
70+
"test-namespace-2", "test-token-2", "failed to refresh token"},
71+
{"Testing token that expired 90 minutes ago", "test-service-account-3",
72+
"test-namespace-3", "test-token-3", "failed to get token"},
73+
{"Testing error when getting token from fake client", "test-service-account-4",
74+
"test-namespace-4", "error when fetching token", "error when fetching token"},
75+
}
76+
77+
for _, tc := range tests {
78+
got, err := tg.Get(context.Background(), types.NamespacedName{Namespace: tc.namespace, Name: tc.serviceAccountName})
79+
if err != nil {
80+
t.Logf("%s: expected: %v, got: %v", tc.testName, tc.want, err)
81+
assert.EqualError(t, err, tc.errorMsg)
82+
} else {
83+
t.Logf("%s: expected: %v, got: %v", tc.testName, tc.want, got)
84+
assert.Equal(t, tc.want, got, tc.errorMsg)
85+
}
86+
}
87+
}

0 commit comments

Comments
 (0)