-
Notifications
You must be signed in to change notification settings - Fork 1
/
cachemap_test.go
360 lines (294 loc) · 9.05 KB
/
cachemap_test.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package jwt
import (
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"github.com/sirupsen/logrus"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"io"
"testing"
"time"
)
func getMapTokenFunction() func(ctx context.Context, key string) (string, error) {
now := time.Now()
iat := now.Add(-time.Hour)
exp := now.Add(time.Hour)
return func(ctx context.Context, key string) (string, error) {
return getJwt(map[string]interface{}{
jwt.IssuedAtKey: iat.UTC(),
jwt.ExpirationKey: exp.UTC(),
})
}
}
func getMapTokenFunctionWithoutIat() func(ctx context.Context, key string) (string, error) {
return func(ctx context.Context, key string) (string, error) {
return getJwt(map[string]interface{}{
jwt.ExpirationKey: time.Now().Add(time.Hour).UTC(),
})
}
}
func getMapExpiredTokenFunction() func(ctx context.Context, key string) (string, error) {
now := time.Now()
return func(ctx context.Context, key string) (string, error) {
return getJwt(map[string]interface{}{
jwt.IssuedAtKey: now.Add(-time.Hour).UTC(),
jwt.ExpirationKey: now.Add(-time.Hour).UTC(),
})
}
}
func getMapTokenFunctionWithoutExp() func(ctx context.Context, key string) (string, error) {
return func(ctx context.Context, key string) (string, error) {
return getJwt(map[string]interface{}{
jwt.IssuedAtKey: time.Now().Add(-time.Hour).UTC(),
})
}
}
// Tests that a new cache uses the correct defaults
func Test_CacheMap_Defaults(t *testing.T) {
// when
cache := NewCacheMap()
// then
if cache.name != "" {
t.Error("default name not correctly applied")
}
if cache.logger != logrus.StandardLogger() {
t.Error("default logger not correctly applied")
}
if cache.headroom != time.Second {
t.Error("default headroom not correctly applied")
}
if _, err := cache.tokenFunc(context.Background(), "somekey"); err != ErrNotImplemented {
t.Error("default token function not correctly applied")
}
if len(cache.parseOptions) != 0 {
t.Error("default parser options not correctly applied")
}
if cache.rejectUnparsable {
t.Error("default reject unparsable flag not correctly applied")
}
}
// Tests that EnsureToken returns the exact error, if any occurred
// while retrieving a new token.
func Test_CacheMap_EnsureToken_TokenError(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
expectedErr := errors.New("expected error")
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(func(ctx context.Context, key string) (s string, e error) {
return "", expectedErr
}),
)
// when
token, err := cache.EnsureToken(context.Background(), "some-key")
// then
if err != expectedErr {
t.Errorf("unexpected error while token function invocation: %s", err)
}
if token != "" {
t.Errorf("expected empty token, but received: %s", token)
}
}
// Tests that EnsureToken correctly caches the token, and does not
// call the token function multiple times. However, a different key
// does warrant a new token again.
func Test_CacheMap_EnsureToken_Cache(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(getMapTokenFunction()),
)
// when
firstToken, firstErr := cache.EnsureToken(context.Background(), "some-key")
secondToken, secondErr := cache.EnsureToken(context.Background(), "some-key")
thirdToken, thirdErr := cache.EnsureToken(context.Background(), "another-key")
fourthToken, fourthErr := cache.EnsureToken(context.Background(), "another-key")
// then
if firstErr != nil {
t.Errorf("error while first token function invocation: %s", firstErr)
}
if secondErr != nil {
t.Errorf("error while second token function invocation: %s", secondErr)
}
if thirdErr != nil {
t.Errorf("error while third token function invocation: %s", secondErr)
}
if fourthErr != nil {
t.Errorf("error while fourth token function invocation: %s", secondErr)
}
if firstToken != secondToken {
t.Errorf(`"some-key" token was not cached`)
}
if thirdToken != fourthToken {
t.Errorf(`"another-key" token was not cached`)
}
if firstToken == thirdToken {
t.Errorf("cached across keys")
}
}
// Tests that EnsureToken correctly invalidates the cache, if the previous
// cached token expires
func Test_CacheMap_EnsureToken_Cache_Invalidation(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(getMapExpiredTokenFunction()),
)
// when
firstToken, firstErr := cache.EnsureToken(context.Background(), "some-key")
secondToken, secondErr := cache.EnsureToken(context.Background(), "some-key")
// then
if firstErr != nil {
t.Errorf("error while first token function invocation: %s", firstErr)
}
if secondErr != nil {
t.Errorf("error while second token function invocation: %s", secondErr)
}
if firstToken == secondToken {
t.Errorf("token was cached, but was not supposed to")
}
}
// Tests that EnsureToken does not cache the token, if the
// token provides not exp claim.
func Test_CacheMap_EnsureToken_NoExp(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(getMapTokenFunctionWithoutExp()),
)
// when
firstToken, firstErr := cache.EnsureToken(context.Background(), "some-key")
secondToken, secondErr := cache.EnsureToken(context.Background(), "some-key")
// then
if firstErr != nil {
t.Errorf("error while first token function invocation: %s", firstErr)
}
if secondErr != nil {
t.Errorf("error while second token function invocation: %s", secondErr)
}
if firstToken == secondToken {
t.Errorf("token was cached, but was not supposed to")
}
}
// Tests that EnsureToken correctly caches the token, and does not
// call the token function multiple times - even if the iat claim is missing.
func Test_CacheMap_EnsureToken_NoIat(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(getMapTokenFunctionWithoutIat()),
)
// when
firstToken, firstErr := cache.EnsureToken(context.Background(), "some-key")
secondToken, secondErr := cache.EnsureToken(context.Background(), "some-key")
// then
if firstErr != nil {
t.Errorf("error while first token function invocation: %s", firstErr)
}
if secondErr != nil {
t.Errorf("error while second token function invocation: %s", secondErr)
}
if firstToken != secondToken {
t.Errorf("token was not cached")
}
}
// Tests that EnsureToken does return the received token, even
// if it can't be parsed for caching usage.
func Test_CacheMap_EnsureToken_BrokenParser(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
counter := 0
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(func(ctx context.Context, key string) (s string, e error) {
counter++
return fmt.Sprintf("not-a-valid-token-%d", counter), nil
}),
)
// when
firstToken, firstErr := cache.EnsureToken(context.Background(), "some-key")
secondToken, secondErr := cache.EnsureToken(context.Background(), "some-key")
// then
if firstErr != nil {
t.Errorf("error while first token function invocation: %s", firstErr)
}
if secondErr != nil {
t.Errorf("error while second token function invocation: %s", secondErr)
}
if firstToken == secondToken {
t.Errorf("token was cached, but was not supposed to")
}
}
// Tests that EnsureToken does return a parsing error, if RejectUnparsable
// is enabled, and the token cannot be parsed (e.g. due to a signing error)
func Test_CacheMap_EnsureToken_BrokenParser_Reject(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
// given
counter := 0
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(func(ctx context.Context, key string) (s string, e error) {
counter++
return fmt.Sprintf("not-a-valid-token-%d", counter), nil
}),
MapRejectUnparsable(true),
)
// when
token, firstErr := cache.EnsureToken(context.Background(), "some-key")
// then
if firstErr == nil {
t.Error("expected error, but got none")
}
if token != "" {
t.Errorf("received token %q, not expected none", token)
}
}
// Tests that EnsureToken correctly verifies JWT signatures,
// if configured.
func Test_MapCache_EnsureToken_Signed_JWT(t *testing.T) {
logger := logrus.New()
logger.Out = io.Discard
ecdsaPrivateKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
t.FailNow()
}
ecdsaPublicKey := ecdsaPrivateKey.Public()
// given
cache := NewCacheMap(
MapLogger(logger),
MapTokenFunction(func(ctx context.Context, key string) (s string, e error) {
signedToken, err := jwt.Sign(jwt.New(), jwa.ES512, ecdsaPrivateKey)
if err != nil {
return "", err
}
return string(signedToken), nil
}),
MapParseOptions(jwt.WithVerify(jwa.ES512, ecdsaPublicKey)),
// Set, so that verification fails if we provide a wrong JWT in the
MapRejectUnparsable(true),
)
// when
token, err := cache.EnsureToken(context.Background(), "some-key")
// then
if err != nil {
t.Errorf("unexpected error: %s", err)
}
if token == "" {
t.Error("expected token, but got none")
}
}