-
Notifications
You must be signed in to change notification settings - Fork 11
/
token_cache.go
221 lines (176 loc) · 4.68 KB
/
token_cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package aztokenprovider
import (
"context"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"google.golang.org/grpc/metadata"
)
const grafanaTenantId = "tenantID"
var (
// timeNow makes it possible to test usage of time
timeNow = time.Now
)
type AccessToken struct {
Token string
ExpiresOn time.Time
}
type TokenRetriever interface {
GetCacheKey(grafanaMultiTenantId string) string
Init() error
GetAccessToken(ctx context.Context, scopes []string) (*AccessToken, error)
GetExpiry() *time.Time
}
type ConcurrentTokenCache interface {
GetAccessToken(ctx context.Context, tokenRetriever TokenRetriever, scopes []string) (string, error)
}
func NewConcurrentTokenCache() ConcurrentTokenCache {
return &tokenCacheImpl{}
}
type tokenCacheImpl struct {
cache sync.Map // of *credentialCacheEntry
}
type credentialCacheEntry struct {
retriever TokenRetriever
expiry *time.Time
credInit uint32
credMutex sync.Mutex
cache sync.Map // of *scopesCacheEntry
}
type scopesCacheEntry struct {
retriever TokenRetriever
scopes []string
cond *sync.Cond
refreshing bool
accessToken *AccessToken
}
func (c *tokenCacheImpl) GetAccessToken(ctx context.Context, tokenRetriever TokenRetriever, scopes []string) (string, error) {
return c.getEntryFor(ctx, tokenRetriever).getAccessToken(ctx, scopes)
}
func (c *tokenCacheImpl) getEntryFor(ctx context.Context, credential TokenRetriever) *credentialCacheEntry {
var entry interface{}
var ok bool
tid := returnGrafanaMultiTenantId(ctx)
key := credential.GetCacheKey(tid)
entry, ok = c.cache.Load(key)
// Store new cache value if there isn't an existing one
if !ok {
entry, _ = c.cache.LoadOrStore(key, &credentialCacheEntry{
retriever: credential,
})
return entry.(*credentialCacheEntry)
}
expiry := entry.(*credentialCacheEntry).retriever.GetExpiry()
// Store new cache value if the current one has expired (only applies to OBO retriever)
if expiry != nil && !expiry.After(time.Now()) {
c.cache.Store(key, &credentialCacheEntry{
retriever: credential,
})
entry, _ = c.cache.Load(key)
}
return entry.(*credentialCacheEntry)
}
func (c *credentialCacheEntry) getAccessToken(ctx context.Context, scopes []string) (string, error) {
err := c.ensureInitialized()
if err != nil {
return "", err
}
return c.getEntryFor(scopes).getAccessToken(ctx)
}
func (c *credentialCacheEntry) ensureInitialized() error {
if atomic.LoadUint32(&c.credInit) == 0 {
c.credMutex.Lock()
defer c.credMutex.Unlock()
if c.credInit == 0 {
// Initialize retriever
err := c.retriever.Init()
if err != nil {
return err
}
atomic.StoreUint32(&c.credInit, 1)
}
}
return nil
}
func (c *credentialCacheEntry) getEntryFor(scopes []string) *scopesCacheEntry {
var entry interface{}
var ok bool
key := getKeyForScopes(scopes)
if entry, ok = c.cache.Load(key); !ok {
entry, _ = c.cache.LoadOrStore(key, &scopesCacheEntry{
retriever: c.retriever,
scopes: scopes,
cond: sync.NewCond(&sync.Mutex{}),
})
}
return entry.(*scopesCacheEntry)
}
func (c *scopesCacheEntry) getAccessToken(ctx context.Context) (string, error) {
var accessToken *AccessToken
var err error
shouldRefresh := false
c.cond.L.Lock()
for {
if c.accessToken != nil && c.accessToken.ExpiresOn.After(timeNow().Add(2*time.Minute)) {
// Use the cached token since it's available and not expired yet
accessToken = c.accessToken
break
}
if !c.refreshing {
// Start refreshing the token
c.refreshing = true
shouldRefresh = true
break
}
// Wait for the token to be refreshed
c.cond.Wait()
}
c.cond.L.Unlock()
if shouldRefresh {
accessToken, err = c.refreshAccessToken(ctx)
if err != nil {
return "", err
}
}
return accessToken.Token, nil
}
func (c *scopesCacheEntry) refreshAccessToken(ctx context.Context) (*AccessToken, error) {
var accessToken *AccessToken
// Safeguarding from panic caused by retriever implementation
defer func() {
c.cond.L.Lock()
c.refreshing = false
if accessToken != nil {
c.accessToken = accessToken
}
c.cond.Broadcast()
c.cond.L.Unlock()
}()
token, err := c.retriever.GetAccessToken(ctx, c.scopes)
if err != nil {
return nil, err
}
accessToken = token
return accessToken, nil
}
func getKeyForScopes(scopes []string) string {
if len(scopes) > 1 {
arr := make([]string, len(scopes))
copy(arr, scopes)
sort.Strings(arr)
scopes = arr
}
return strings.Join(scopes, " ")
}
func returnGrafanaMultiTenantId(ctx context.Context) (grafanaMultiTenantId string) {
md, exists := metadata.FromIncomingContext(ctx)
if exists {
tid := md.Get(grafanaTenantId)
if len(tid) > 0 && tid[0] != "" {
grafanaMultiTenantId = tid[0]
}
}
return grafanaMultiTenantId
}