aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/aws/smithy-go/auth/bearer/token_cache_test.go
blob: 3d56f7ee633920f747564b5bdcfc9c1b0a927e9f (plain) (blame)
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package bearer

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
)

var _ TokenProvider = (*TokenCache)(nil)

func TestTokenCache_cache(t *testing.T) {
	expectToken := Token{
		Value: "abc123",
	}

	var retrieveCalled bool
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		if retrieveCalled {
			t.Fatalf("expect wrapped provider to be called once")
		}
		retrieveCalled = true
		return expectToken, nil
	}))

	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}

	for i := 0; i < 100; i++ {
		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Fatalf("expect no error, got %v", err)
		}
		if diff := cmp.Diff(expectToken, token); diff != "" {
			t.Errorf("expect token match\n%s", diff)
		}
	}
}

func TestTokenCache_cacheConcurrent(t *testing.T) {
	expectToken := Token{
		Value: "abc123",
	}

	var retrieveCalled bool
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		if retrieveCalled {
			t.Fatalf("expect wrapped provider to be called once")
		}
		retrieveCalled = true
		return expectToken, nil
	}))

	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}

	for i := 0; i < 100; i++ {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			t.Parallel()

			token, err := provider.RetrieveBearerToken(context.Background())
			if err != nil {
				t.Fatalf("expect no error, got %v", err)
			}
			if diff := cmp.Diff(expectToken, token); diff != "" {
				t.Errorf("expect token match\n%s", diff)
			}
		})
	}
}

func TestTokenCache_expired(t *testing.T) {
	origTimeNow := timeNow
	defer func() { timeNow = origTimeNow }()

	timeNow = func() time.Time { return time.Time{} }

	expectToken := Token{
		Value:     "abc123",
		CanExpire: true,
		Expires:   timeNow().Add(10 * time.Minute),
	}
	refreshedToken := Token{
		Value:     "refreshed-abc123",
		CanExpire: true,
		Expires:   timeNow().Add(30 * time.Minute),
	}

	retrievedCount := new(int32)
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		if atomic.AddInt32(retrievedCount, 1) > 1 {
			return refreshedToken, nil
		}
		return expectToken, nil
	}))

	for i := 0; i < 10; i++ {
		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Fatalf("expect no error, got %v", err)
		}
		if diff := cmp.Diff(expectToken, token); diff != "" {
			t.Errorf("expect token match\n%s", diff)
		}
	}
	if e, a := 1, int(atomic.LoadInt32(retrievedCount)); e != a {
		t.Errorf("expect %v provider calls, got %v", e, a)
	}

	// Offset time for refresh
	timeNow = func() time.Time {
		return (time.Time{}).Add(10 * time.Minute)
	}

	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(refreshedToken, token); diff != "" {
		t.Errorf("expect refreshed token match\n%s", diff)
	}
	if e, a := 2, int(atomic.LoadInt32(retrievedCount)); e != a {
		t.Errorf("expect %v provider calls, got %v", e, a)
	}
}

func TestTokenCache_cancelled(t *testing.T) {
	providerRunning := make(chan struct{})
	providerDone := make(chan struct{})
	var onceClose sync.Once
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		onceClose.Do(func() { close(providerRunning) })

		// Provider running never receives context cancel so that if the first
		// retrieve call is canceled all subsequent retrieve callers won't get
		// canceled as well.
		select {
		case <-providerDone:
			return Token{Value: "abc123"}, nil
		case <-ctx.Done():
			return Token{}, fmt.Errorf("unexpected context canceled, %w", ctx.Err())
		}
	}))

	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	// Retrieve that will have its context canceled, should return error, but
	// underlying provider retrieve will continue to block in the background.
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()

		_, err := provider.RetrieveBearerToken(ctx)
		if err == nil {
			t.Errorf("expect error, got none")

		} else if e, a := "unexpected context canceled", err.Error(); strings.Contains(a, e) {
			t.Errorf("unexpected context canceled received, %v", err)

		} else if e, a := "context canceled", err.Error(); !strings.Contains(a, e) {
			t.Errorf("expect %v error in, %v", e, a)
		}
	}()

	<-providerRunning

	// Retrieve that will be added to existing single flight group, (or create
	// a new group). Returning valid token.
	wg.Add(1)
	go func() {
		defer wg.Done()

		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Errorf("expect no error, got %v", err)
		} else {
			if diff := cmp.Diff(Token{Value: "abc123"}, token); diff != "" {
				t.Errorf("expect token retrieve match\n%s", diff)
			}
		}
	}()
	close(providerDone)

	wg.Wait()
}

func TestTokenCache_cancelledWithTimeout(t *testing.T) {
	providerReady := make(chan struct{})
	var providerReadCloseOnce sync.Once
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		providerReadCloseOnce.Do(func() { close(providerReady) })

		<-ctx.Done()
		return Token{}, fmt.Errorf("token retrieve timeout, %w", ctx.Err())
	}), func(o *TokenCacheOptions) {
		o.RetrieveBearerTokenTimeout = time.Millisecond
	})

	var wg sync.WaitGroup

	// Spin up additional retrieves that will be deduplicated and block on the
	// original retrieve call.
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-providerReady

			_, err := provider.RetrieveBearerToken(context.Background())
			if err == nil {
				t.Errorf("expect error, got none")

			} else if e, a := "token retrieve timeout", err.Error(); !strings.Contains(a, e) {
				t.Errorf("expect %v error in, %v", e, a)
			}
		}()
	}

	_, err := provider.RetrieveBearerToken(context.Background())
	if err == nil {
		t.Errorf("expect error, got none")

	} else if e, a := "token retrieve timeout", err.Error(); !strings.Contains(a, e) {
		t.Errorf("expect %v error in, %v", e, a)
	}

	wg.Wait()
}

func TestTokenCache_asyncRefresh(t *testing.T) {
	origTimeNow := timeNow
	defer func() { timeNow = origTimeNow }()

	timeNow = func() time.Time { return time.Time{} }

	expectToken := Token{
		Value:     "abc123",
		CanExpire: true,
		Expires:   timeNow().Add(10 * time.Minute),
	}
	refreshedToken := Token{
		Value:     "refreshed-abc123",
		CanExpire: true,
		Expires:   timeNow().Add(30 * time.Minute),
	}

	retrievedCount := new(int32)
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		c := atomic.AddInt32(retrievedCount, 1)
		switch {
		case c == 1:
			return expectToken, nil
		case c > 1 && c < 5:
			return Token{}, fmt.Errorf("some error")
		case c == 5:
			return refreshedToken, nil
		default:
			return Token{}, fmt.Errorf("unexpected error")
		}
	}), func(o *TokenCacheOptions) {
		o.RefreshBeforeExpires = 5 * time.Minute
	})

	// 1: Initial retrieve to cache token
	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}

	// 2-5: Offset time for subsequent calls to retrieve to trigger asynchronous
	// refreshes.
	timeNow = func() time.Time {
		return (time.Time{}).Add(6 * time.Minute)
	}

	for i := 0; i < 4; i++ {
		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Fatalf("expect no error, got %v", err)
		}
		if diff := cmp.Diff(expectToken, token); diff != "" {
			t.Errorf("expect token match\n%s", diff)
		}
	}
	// Wait for all async refreshes to complete
	testWaitAsyncRefreshDone(provider)

	if c := int(atomic.LoadInt32(retrievedCount)); c < 2 || c > 5 {
		t.Fatalf("expect async refresh to be called [2,5) times, got, %v", c)
	}

	// Ensure enough retrieves have been done to trigger refresh.
	if c := atomic.LoadInt32(retrievedCount); c != 5 {
		atomic.StoreInt32(retrievedCount, 4)
		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Fatalf("expect no error, got %v", err)
		}
		if diff := cmp.Diff(expectToken, token); diff != "" {
			t.Errorf("expect token match\n%s", diff)
		}
		testWaitAsyncRefreshDone(provider)
	}

	// Last async refresh will succeed and update cached token, expect the next
	// call to get refreshed token.
	token, err = provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(refreshedToken, token); diff != "" {
		t.Errorf("expect refreshed token match\n%s", diff)
	}
}

func TestTokenCache_asyncRefreshWithMinDelay(t *testing.T) {
	origTimeNow := timeNow
	defer func() { timeNow = origTimeNow }()

	timeNow = func() time.Time { return time.Time{} }

	expectToken := Token{
		Value:     "abc123",
		CanExpire: true,
		Expires:   timeNow().Add(10 * time.Minute),
	}
	refreshedToken := Token{
		Value:     "refreshed-abc123",
		CanExpire: true,
		Expires:   timeNow().Add(30 * time.Minute),
	}

	retrievedCount := new(int32)
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		c := atomic.AddInt32(retrievedCount, 1)
		switch {
		case c == 1:
			return expectToken, nil
		case c > 1 && c < 5:
			return Token{}, fmt.Errorf("some error")
		case c == 5:
			return refreshedToken, nil
		default:
			return Token{}, fmt.Errorf("unexpected error")
		}
	}), func(o *TokenCacheOptions) {
		o.RefreshBeforeExpires = 5 * time.Minute
		o.AsyncRefreshMinimumDelay = 30 * time.Second
	})

	// 1: Initial retrieve to cache token
	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}

	// 2-5: Offset time for subsequent calls to retrieve to trigger asynchronous
	// refreshes.
	timeNow = func() time.Time {
		return (time.Time{}).Add(6 * time.Minute)
	}

	for i := 0; i < 4; i++ {
		token, err := provider.RetrieveBearerToken(context.Background())
		if err != nil {
			t.Fatalf("expect no error, got %v", err)
		}
		if diff := cmp.Diff(expectToken, token); diff != "" {
			t.Errorf("expect token match\n%s", diff)
		}
		// Wait for all async refreshes to complete ensure not deduped
		testWaitAsyncRefreshDone(provider)
	}

	// Only a single refresh attempt is expected.
	if e, a := 2, int(atomic.LoadInt32(retrievedCount)); e != a {
		t.Fatalf("expect %v min async refresh, got %v", e, a)
	}

	// Move time forward to ensure another async refresh is triggered.
	timeNow = func() time.Time { return (time.Time{}).Add(7 * time.Minute) }
	// Make sure the next attempt refreshes the token
	atomic.StoreInt32(retrievedCount, 4)

	// Do async retrieve that will succeed refreshing in background.
	token, err = provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}
	// Wait for all async refreshes to complete ensure not deduped
	testWaitAsyncRefreshDone(provider)

	// Last async refresh will succeed and update cached token, expect the next
	// call to get refreshed token.
	token, err = provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(refreshedToken, token); diff != "" {
		t.Errorf("expect refreshed token match\n%s", diff)
	}
}

func TestTokenCache_disableAsyncRefresh(t *testing.T) {
	origTimeNow := timeNow
	defer func() { timeNow = origTimeNow }()

	timeNow = func() time.Time { return time.Time{} }

	expectToken := Token{
		Value:     "abc123",
		CanExpire: true,
		Expires:   timeNow().Add(10 * time.Minute),
	}
	refreshedToken := Token{
		Value:     "refreshed-abc123",
		CanExpire: true,
		Expires:   timeNow().Add(30 * time.Minute),
	}

	retrievedCount := new(int32)
	provider := NewTokenCache(TokenProviderFunc(func(ctx context.Context) (Token, error) {
		c := atomic.AddInt32(retrievedCount, 1)
		switch {
		case c == 1:
			return expectToken, nil
		case c > 1 && c < 5:
			return Token{}, fmt.Errorf("some error")
		case c == 5:
			return refreshedToken, nil
		default:
			return Token{}, fmt.Errorf("unexpected error")
		}
	}), func(o *TokenCacheOptions) {
		o.RefreshBeforeExpires = 5 * time.Minute
		o.DisableAsyncRefresh = true
	})

	// 1: Initial retrieve to cache token
	token, err := provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(expectToken, token); diff != "" {
		t.Errorf("expect token match\n%s", diff)
	}

	// Update time into refresh window before token expires
	timeNow = func() time.Time {
		return (time.Time{}).Add(6 * time.Minute)
	}

	for i := 0; i < 3; i++ {
		_, err = provider.RetrieveBearerToken(context.Background())
		if err == nil {
			t.Fatalf("expect error, got none")
		}
		if e, a := "some error", err.Error(); !strings.Contains(a, e) {
			t.Fatalf("expect %v error in %v", e, a)
		}
		if e, a := i+2, int(atomic.LoadInt32(retrievedCount)); e != a {
			t.Fatalf("expect %v retrieveCount, got %v", e, a)
		}
	}
	if e, a := 4, int(atomic.LoadInt32(retrievedCount)); e != a {
		t.Fatalf("expect %v retrieveCount, got %v", e, a)
	}

	// Last refresh will succeed and update cached token, expect the next
	// call to get refreshed token.
	token, err = provider.RetrieveBearerToken(context.Background())
	if err != nil {
		t.Fatalf("expect no error, got %v", err)
	}
	if diff := cmp.Diff(refreshedToken, token); diff != "" {
		t.Errorf("expect refreshed token match\n%s", diff)
	}
}

func testWaitAsyncRefreshDone(provider *TokenCache) {
	asyncResCh := provider.sfGroup.DoChan("async-refresh", func() (interface{}, error) {
		return nil, nil
	})
	<-asyncResCh
}