Skip to content

Commit 6e82b02

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

File tree

2 files changed

+171
-0
lines changed

2 files changed

+171
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
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+
expirationSeconds int64
18+
rotationThreshold time.Duration
19+
tokens map[types.NamespacedName]*authenticationv1.TokenRequestStatus
20+
mu sync.RWMutex
21+
}
22+
23+
type TokenGetterOption func(*TokenGetter)
24+
25+
// Returns a token getter that can fetch tokens given a service account.
26+
// The token getter also caches tokens which helps reduce the number of requests to the API Server.
27+
// In case a cached token is expiring a fresh token is created.
28+
func NewTokenGetter(client corev1.ServiceAccountsGetter, options ...TokenGetterOption) *TokenGetter {
29+
tokenGetter := &TokenGetter{
30+
client: client,
31+
expirationSeconds: int64(5 * time.Minute), // default token ttl
32+
rotationThreshold: 1 * time.Minute, // default rotation threshold
33+
tokens: map[types.NamespacedName]*authenticationv1.TokenRequestStatus{},
34+
}
35+
36+
for _, opt := range options {
37+
opt(tokenGetter)
38+
}
39+
40+
return tokenGetter
41+
}
42+
43+
func WithExpirationSeconds(expirationSeconds int64) TokenGetterOption {
44+
return func(tg *TokenGetter) {
45+
tg.expirationSeconds = expirationSeconds
46+
}
47+
}
48+
49+
func WithRotationThreshold(rotationThreshold time.Duration) TokenGetterOption {
50+
return func(tg *TokenGetter) {
51+
tg.rotationThreshold = rotationThreshold
52+
}
53+
}
54+
55+
// Get returns a token from the cache if available and not expiring, otherwise creates a new token
56+
func (t *TokenGetter) Get(ctx context.Context, key types.NamespacedName) (string, error) {
57+
t.mu.RLock()
58+
token, ok := t.tokens[key]
59+
t.mu.RUnlock()
60+
61+
expireTime := time.Time{}
62+
if ok {
63+
expireTime = token.ExpirationTimestamp.Time
64+
}
65+
66+
// Create a new token if the cached token expires within rotationThresholdSeconds seconds from now
67+
rotationThresholdAfterNow := metav1.Now().Add(t.rotationThreshold)
68+
if expireTime.Before(rotationThresholdAfterNow) {
69+
var err error
70+
token, err = t.getToken(ctx, key)
71+
if err != nil {
72+
return "", err
73+
}
74+
t.mu.Lock()
75+
t.tokens[key] = token
76+
t.mu.Unlock()
77+
}
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](t.expirationSeconds)},
87+
}, metav1.CreateOptions{})
88+
if err != nil {
89+
return nil, err
90+
}
91+
return &req.Status, nil
92+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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 TestNewTokenGetter(t *testing.T) {
19+
fakeClient := fake.NewSimpleClientset()
20+
fakeClient.PrependReactor("create", "serviceaccounts/token", func(action ctest.Action) (bool, runtime.Object, error) {
21+
act, ok := action.(ctest.CreateActionImpl)
22+
if !ok {
23+
return false, nil, nil
24+
}
25+
tokenRequest := act.GetObject().(*authenticationv1.TokenRequest)
26+
var err error
27+
if act.Name == "test-service-account-1" {
28+
tokenRequest.Status = authenticationv1.TokenRequestStatus{
29+
Token: "test-token-1",
30+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(5 * time.Minute)),
31+
}
32+
}
33+
if act.Name == "test-service-account-2" {
34+
tokenRequest.Status = authenticationv1.TokenRequestStatus{
35+
Token: "test-token-2",
36+
ExpirationTimestamp: metav1.NewTime(metav1.Now().Add(1 * time.Second)),
37+
}
38+
}
39+
if act.Name == "test-service-account-3" {
40+
tokenRequest = nil
41+
err = fmt.Errorf("error when fetching token")
42+
}
43+
return true, tokenRequest, err
44+
})
45+
46+
tg := NewTokenGetter(fakeClient.CoreV1(),
47+
WithExpirationSeconds(int64(5*time.Minute)),
48+
WithRotationThreshold(1*time.Minute))
49+
50+
tests := []struct {
51+
testName string
52+
serviceAccountName string
53+
namespace string
54+
want string
55+
errorMsg string
56+
}{
57+
{"Testing NewTokenGetter with fake client", "test-service-account-1",
58+
"test-namespace-1", "test-token-1", "failed to get token"},
59+
{"Testing getting token from cache", "test-service-account-1",
60+
"test-namespace-1", "test-token-1", "failed to get token from cache"},
61+
{"Testing getting short lived token from fake client", "test-service-account-2",
62+
"test-namespace-2", "test-token-2", "failed to get token"},
63+
{"Testing getting expired token from cache", "test-service-account-2",
64+
"test-namespace-2", "test-token-2", "failed to refresh token"},
65+
{"Testing error when getting token from fake client", "test-service-account-3",
66+
"test-namespace-3", "error when fetching token", "error when fetching token"},
67+
}
68+
69+
for _, tc := range tests {
70+
got, err := tg.Get(context.Background(), types.NamespacedName{Namespace: tc.namespace, Name: tc.serviceAccountName})
71+
if err != nil {
72+
t.Logf("%s: expected: %v, got: %v", tc.testName, tc.want, err)
73+
assert.EqualError(t, err, tc.errorMsg)
74+
} else {
75+
t.Logf("%s: expected: %v, got: %v", tc.testName, tc.want, got)
76+
assert.Equal(t, tc.want, got, tc.errorMsg)
77+
}
78+
}
79+
}

0 commit comments

Comments
 (0)