Skip to content

Commit 7cc9872

Browse files
authored
Fixes and Improvements for TokenGetter (#1014)
1 parent 5c83e91 commit 7cc9872

File tree

2 files changed

+20
-30
lines changed

2 files changed

+20
-30
lines changed

internal/authentication/tokengetter.go

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,27 @@ import (
1313
)
1414

1515
type TokenGetter struct {
16-
client corev1.ServiceAccountsGetter
17-
expirationDuration time.Duration
18-
removeAfterExpiredDuration time.Duration
19-
tokens map[types.NamespacedName]*authenticationv1.TokenRequestStatus
20-
mu sync.RWMutex
16+
client corev1.ServiceAccountsGetter
17+
expirationDuration time.Duration
18+
tokens map[types.NamespacedName]*authenticationv1.TokenRequestStatus
19+
mu sync.RWMutex
2120
}
2221

2322
type TokenGetterOption func(*TokenGetter)
2423

2524
const (
26-
RotationThresholdPercentage = 10
27-
DefaultExpirationDuration = 5 * time.Minute
28-
DefaultRemoveAfterExpiredDuration = 90 * time.Minute
25+
rotationThresholdFraction = 0.1
26+
DefaultExpirationDuration = 5 * time.Minute
2927
)
3028

3129
// Returns a token getter that can fetch tokens given a service account.
3230
// The token getter also caches tokens which helps reduce the number of requests to the API Server.
3331
// In case a cached token is expiring a fresh token is created.
3432
func NewTokenGetter(client corev1.ServiceAccountsGetter, options ...TokenGetterOption) *TokenGetter {
3533
tokenGetter := &TokenGetter{
36-
client: client,
37-
expirationDuration: DefaultExpirationDuration,
38-
removeAfterExpiredDuration: DefaultRemoveAfterExpiredDuration,
39-
tokens: map[types.NamespacedName]*authenticationv1.TokenRequestStatus{},
34+
client: client,
35+
expirationDuration: DefaultExpirationDuration,
36+
tokens: map[types.NamespacedName]*authenticationv1.TokenRequestStatus{},
4037
}
4138

4239
for _, opt := range options {
@@ -52,12 +49,6 @@ func WithExpirationDuration(expirationDuration time.Duration) TokenGetterOption
5249
}
5350
}
5451

55-
func WithRemoveAfterExpiredDuration(removeAfterExpiredDuration time.Duration) TokenGetterOption {
56-
return func(tg *TokenGetter) {
57-
tg.removeAfterExpiredDuration = removeAfterExpiredDuration
58-
}
59-
}
60-
6152
// Get returns a token from the cache if available and not expiring, otherwise creates a new token
6253
func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string, error) {
6354
t.mu.RLock()
@@ -69,8 +60,8 @@ func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string
6960
expireTime = token.ExpirationTimestamp.Time
7061
}
7162

72-
// Create a new token if the cached token expires within DurationPercentage of expirationDuration from now
73-
rotationThresholdAfterNow := metav1.Now().Add(t.expirationDuration * (RotationThresholdPercentage / 100))
63+
// Create a new token if the cached token expires within rotationThresholdFraction of expirationDuration from now
64+
rotationThresholdAfterNow := metav1.Now().Add(time.Duration(float64(t.expirationDuration) * (rotationThresholdFraction)))
7465
if expireTime.Before(rotationThresholdAfterNow) {
7566
var err error
7667
token, err = t.getToken(ctx, key)
@@ -82,8 +73,8 @@ func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string
8273
t.mu.Unlock()
8374
}
8475

85-
// Delete tokens that have been expired for more than ExpiredDuration
86-
t.reapExpiredTokens(t.removeAfterExpiredDuration)
76+
// Delete tokens that have expired
77+
t.reapExpiredTokens()
8778

8879
return token.Token, nil
8980
}
@@ -92,19 +83,19 @@ func (t *TokenGetter) getToken(ctx context.Context, key types.NamespacedName) (*
9283
req, err := t.client.ServiceAccounts(key.Namespace).CreateToken(ctx,
9384
key.Name,
9485
&authenticationv1.TokenRequest{
95-
Spec: authenticationv1.TokenRequestSpec{ExpirationSeconds: ptr.To[int64](int64(t.expirationDuration))},
86+
Spec: authenticationv1.TokenRequestSpec{ExpirationSeconds: ptr.To[int64](int64(t.expirationDuration / time.Second))},
9687
}, metav1.CreateOptions{})
9788
if err != nil {
9889
return nil, err
9990
}
10091
return &req.Status, nil
10192
}
10293

103-
func (t *TokenGetter) reapExpiredTokens(expiredDuration time.Duration) {
94+
func (t *TokenGetter) reapExpiredTokens() {
10495
t.mu.Lock()
10596
defer t.mu.Unlock()
10697
for key, token := range t.tokens {
107-
if metav1.Now().Sub(token.ExpirationTimestamp.Time) > expiredDuration {
98+
if metav1.Now().Sub(token.ExpirationTimestamp.Time) > 0 {
10899
delete(t.tokens, key)
109100
}
110101
}

internal/authentication/tokengetter_test.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func TestTokenGetterGet(t *testing.T) {
4040
if act.Name == "test-service-account-3" {
4141
tokenRequest.Status = authenticationv1.TokenRequestStatus{
4242
Token: "test-token-3",
43-
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(-DefaultRemoveAfterExpiredDuration)),
43+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(-10 * time.Second)),
4444
}
4545
}
4646
if act.Name == "test-service-account-4" {
@@ -51,8 +51,7 @@ func TestTokenGetterGet(t *testing.T) {
5151
})
5252

5353
tg := NewTokenGetter(fakeClient.CoreV1(),
54-
WithExpirationDuration(DefaultExpirationDuration),
55-
WithRemoveAfterExpiredDuration(DefaultRemoveAfterExpiredDuration))
54+
WithExpirationDuration(DefaultExpirationDuration))
5655

5756
tests := []struct {
5857
testName string
@@ -67,9 +66,9 @@ func TestTokenGetterGet(t *testing.T) {
6766
"test-namespace-1", "test-token-1", "failed to get token"},
6867
{"Testing getting short lived token from fake client", "test-service-account-2",
6968
"test-namespace-2", "test-token-2", "failed to get token"},
70-
{"Testing getting expired token from cache", "test-service-account-2",
69+
{"Testing getting nearly expired token from cache", "test-service-account-2",
7170
"test-namespace-2", "test-token-2", "failed to refresh token"},
72-
{"Testing token that expired 90 minutes ago", "test-service-account-3",
71+
{"Testing token that expired 10 seconds ago", "test-service-account-3",
7372
"test-namespace-3", "test-token-3", "failed to get token"},
7473
{"Testing error when getting token from fake client", "test-service-account-4",
7574
"test-namespace-4", "error when fetching token", "error when fetching token"},

0 commit comments

Comments
 (0)