forked from lukaszraczylo/traefikoidc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_initialization_test.go
More file actions
628 lines (574 loc) · 17.3 KB
/
Copy pathmain_initialization_test.go
File metadata and controls
628 lines (574 loc) · 17.3 KB
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
package traefikoidc
import (
"container/list"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// TestInitializeMetadata tests the initializeMetadata function
func TestInitializeMetadata(t *testing.T) {
tests := []struct {
setupMock func() *httptest.Server
validateFunc func(*testing.T, *TraefikOidc)
name string
providerURL string
wantPanic bool
}{
{
name: "successful metadata initialization",
providerURL: "",
setupMock: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://provider.example.com",
AuthURL: "https://provider.example.com/auth",
TokenURL: "https://provider.example.com/token",
JWKSURL: "https://provider.example.com/jwks",
RevokeURL: "https://provider.example.com/revoke",
EndSessionURL: "https://provider.example.com/logout",
})
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
},
validateFunc: func(t *testing.T, oidc *TraefikOidc) {
if oidc.authURL != "https://provider.example.com/auth" {
t.Errorf("expected authURL to be set, got %s", oidc.authURL)
}
if oidc.tokenURL != "https://provider.example.com/token" {
t.Errorf("expected tokenURL to be set, got %s", oidc.tokenURL)
}
if oidc.jwksURL != "https://provider.example.com/jwks" {
t.Errorf("expected jwksURL to be set, got %s", oidc.jwksURL)
}
if oidc.revocationURL != "https://provider.example.com/revoke" {
t.Errorf("expected revocationURL to be set, got %s", oidc.revocationURL)
}
if oidc.endSessionURL != "https://provider.example.com/logout" {
t.Errorf("expected endSessionURL to be set, got %s", oidc.endSessionURL)
}
},
wantPanic: false,
},
{
name: "metadata endpoint returns 404",
providerURL: "",
setupMock: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not Found"))
}))
},
validateFunc: func(t *testing.T, oidc *TraefikOidc) {
// URLs should remain unchanged when metadata fetch fails
if oidc.authURL != "" {
t.Logf("authURL remained as: %s", oidc.authURL)
}
},
wantPanic: false,
},
{
name: "metadata endpoint returns malformed JSON",
providerURL: "",
setupMock: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"issuer": "test", invalid json`))
}
}))
},
validateFunc: func(t *testing.T, oidc *TraefikOidc) {
// URLs should remain unchanged when JSON parsing fails
if oidc.tokenURL != "" {
t.Logf("tokenURL remained as: %s", oidc.tokenURL)
}
},
wantPanic: false,
},
{
name: "metadata endpoint times out",
providerURL: "",
setupMock: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate timeout by sleeping longer than client timeout
time.Sleep(2 * time.Second)
}))
},
validateFunc: func(t *testing.T, oidc *TraefikOidc) {
// URLs should remain unchanged when request times out
t.Log("Metadata fetch timed out as expected")
},
wantPanic: false,
},
{
name: "partial metadata response",
providerURL: "",
setupMock: func() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
// Only return some fields
json.NewEncoder(w).Encode(map[string]string{
"issuer": "https://partial.example.com",
"authorization_endpoint": "https://partial.example.com/auth",
"token_endpoint": "https://partial.example.com/token",
// Missing jwks_uri, revocation_endpoint, end_session_endpoint
})
}
}))
},
validateFunc: func(t *testing.T, oidc *TraefikOidc) {
if oidc.authURL != "https://partial.example.com/auth" {
t.Errorf("expected authURL to be set, got %s", oidc.authURL)
}
if oidc.tokenURL != "https://partial.example.com/token" {
t.Errorf("expected tokenURL to be set, got %s", oidc.tokenURL)
}
// JWKS URL and others may be empty
if oidc.jwksURL != "" {
t.Logf("jwksURL: %s", oidc.jwksURL)
}
},
wantPanic: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup mock server
server := tt.setupMock()
defer server.Close()
// Create TraefikOidc instance with minimal setup
oidc := &TraefikOidc{
providerURL: server.URL,
httpClient: &http.Client{
Timeout: 1 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
// Handle potential panics
if tt.wantPanic {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic but got none")
}
}()
}
// Initialize metadata
oidc.initializeMetadata(server.URL)
// Validate results
if tt.validateFunc != nil {
tt.validateFunc(t, oidc)
}
})
}
}
// TestInitializeMetadata_Concurrency tests concurrent metadata initialization
func TestInitializeMetadata_Concurrency(t *testing.T) {
requestCount := 0
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requestCount++
mu.Unlock()
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://concurrent.example.com",
AuthURL: "https://concurrent.example.com/auth",
TokenURL: "https://concurrent.example.com/token",
JWKSURL: "https://concurrent.example.com/jwks",
RevokeURL: "https://concurrent.example.com/revoke",
EndSessionURL: "https://concurrent.example.com/logout",
})
}
}))
defer server.Close()
// Create multiple TraefikOidc instances
const numInstances = 5
var wg sync.WaitGroup
wg.Add(numInstances)
for i := 0; i < numInstances; i++ {
go func() {
defer wg.Done()
oidc := &TraefikOidc{
providerURL: server.URL,
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
oidc.initializeMetadata(server.URL)
// Verify initialization
if oidc.tokenURL != "https://concurrent.example.com/token" {
t.Errorf("expected tokenURL to be set")
}
}()
}
wg.Wait()
// Check that multiple requests were made
mu.Lock()
finalCount := requestCount
mu.Unlock()
if finalCount != numInstances {
t.Logf("Made %d requests for %d instances (some may have been cached)", finalCount, numInstances)
}
}
// TestProviderDetection tests provider-specific detection functions
func TestProviderDetection(t *testing.T) {
tests := []struct {
name string
issuerURL string
isGoogle bool
isAzure bool
}{
{
name: "Google provider",
issuerURL: "https://accounts.google.com",
isGoogle: true,
isAzure: false,
},
{
name: "Google provider with different URL",
issuerURL: "https://google.com/oauth",
isGoogle: true,
isAzure: false,
},
{
name: "Azure AD provider",
issuerURL: "https://login.microsoftonline.com/tenant",
isGoogle: false,
isAzure: true,
},
{
name: "Azure AD with sts.windows.net",
issuerURL: "https://sts.windows.net/tenant",
isGoogle: false,
isAzure: true,
},
{
name: "Azure AD with login.windows.net",
issuerURL: "https://login.windows.net/tenant",
isGoogle: false,
isAzure: true,
},
{
name: "Generic provider",
issuerURL: "https://auth.example.com",
isGoogle: false,
isAzure: false,
},
{
name: "Empty issuer URL",
issuerURL: "",
isGoogle: false,
isAzure: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
oidc := &TraefikOidc{
issuerURL: tt.issuerURL,
}
gotGoogle := oidc.isGoogleProvider()
if gotGoogle != tt.isGoogle {
t.Errorf("isGoogleProvider() = %v, want %v", gotGoogle, tt.isGoogle)
}
gotAzure := oidc.isAzureProvider()
if gotAzure != tt.isAzure {
t.Errorf("isAzureProvider() = %v, want %v", gotAzure, tt.isAzure)
}
})
}
}
// TestInitializationWaiting tests waiting for initialization to complete
func TestInitializationWaiting(t *testing.T) {
t.Run("wait for initialization completion", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Delay response to simulate slow initialization
time.Sleep(100 * time.Millisecond)
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://slow.example.com",
AuthURL: "https://slow.example.com/auth",
TokenURL: "https://slow.example.com/token",
JWKSURL: "https://slow.example.com/jwks",
})
}
}))
defer server.Close()
oidc := &TraefikOidc{
providerURL: server.URL,
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
// Start initialization in background
go func() {
oidc.initializeMetadata(server.URL)
// initComplete is closed internally by initializeMetadata
}()
// Wait for initialization
select {
case <-oidc.initComplete:
// Success
if oidc.tokenURL != "https://slow.example.com/token" {
t.Error("expected tokenURL to be set after initialization")
}
case <-time.After(2 * time.Second):
t.Error("initialization did not complete in time")
}
})
t.Run("multiple waiters for initialization", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Delay to ensure multiple waiters
time.Sleep(50 * time.Millisecond)
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://multi.example.com",
AuthURL: "https://multi.example.com/auth",
TokenURL: "https://multi.example.com/token",
JWKSURL: "https://multi.example.com/jwks",
})
}
}))
defer server.Close()
oidc := &TraefikOidc{
providerURL: server.URL,
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
// Start initialization
go func() {
oidc.initializeMetadata(server.URL)
// initComplete is closed internally by initializeMetadata
}()
// Create multiple waiters
const numWaiters = 5
var wg sync.WaitGroup
wg.Add(numWaiters)
for i := 0; i < numWaiters; i++ {
go func(id int) {
defer wg.Done()
select {
case <-oidc.initComplete:
// All waiters should see the same initialized state
if oidc.tokenURL != "https://multi.example.com/token" {
t.Errorf("waiter %d: expected tokenURL to be set", id)
}
case <-time.After(2 * time.Second):
t.Errorf("waiter %d: timeout waiting for initialization", id)
}
}(i)
}
wg.Wait()
})
}
// TestFirstRequestHandling tests the first request initialization behavior
func TestFirstRequestHandling(t *testing.T) {
t.Run("first request triggers initialization", func(t *testing.T) {
initCalled := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
initCalled = true
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://first.example.com",
AuthURL: "https://first.example.com/auth",
TokenURL: "https://first.example.com/token",
JWKSURL: "https://first.example.com/jwks",
})
}
}))
defer server.Close()
oidc := &TraefikOidc{
providerURL: server.URL,
firstRequestReceived: false,
firstRequestMutex: sync.Mutex{},
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
ctx: context.Background(),
cancelFunc: func() {},
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
// Simulate first request processing
oidc.firstRequestMutex.Lock()
if !oidc.firstRequestReceived {
oidc.firstRequestReceived = true
oidc.firstRequestMutex.Unlock()
// This would normally be called asynchronously
go func() {
oidc.initializeMetadata(server.URL)
// initComplete is closed internally by initializeMetadata
}()
} else {
oidc.firstRequestMutex.Unlock()
}
// Wait for initialization
select {
case <-oidc.initComplete:
if !initCalled {
t.Error("expected metadata endpoint to be called")
}
case <-time.After(2 * time.Second):
t.Error("initialization timeout")
}
})
t.Run("concurrent first requests handled correctly", func(t *testing.T) {
metadataCallCount := 0
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/.well-known/openid-configuration") {
mu.Lock()
metadataCallCount++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ProviderMetadata{
Issuer: "https://concurrent.example.com",
AuthURL: "https://concurrent.example.com/auth",
TokenURL: "https://concurrent.example.com/token",
JWKSURL: "https://concurrent.example.com/jwks",
})
}
}))
defer server.Close()
oidc := &TraefikOidc{
providerURL: server.URL,
firstRequestReceived: false,
firstRequestMutex: sync.Mutex{},
httpClient: &http.Client{
Timeout: 5 * time.Second,
},
logger: NewLogger("debug"),
initComplete: make(chan struct{}),
ctx: context.Background(),
cancelFunc: func() {},
metadataCache: &MetadataCache{
cache: &UniversalCache{
items: make(map[string]*CacheItem),
lruList: list.New(),
config: UniversalCacheConfig{
DefaultTTL: 3600 * time.Second,
MaxSize: 100,
},
logger: NewLogger("debug"),
},
logger: NewLogger("debug"),
},
}
// Simulate multiple concurrent "first" requests
const numRequests = 10
var wg sync.WaitGroup
wg.Add(numRequests)
initStarted := 0
var initMu sync.Mutex
for i := 0; i < numRequests; i++ {
go func() {
defer wg.Done()
oidc.firstRequestMutex.Lock()
if !oidc.firstRequestReceived {
oidc.firstRequestReceived = true
oidc.firstRequestMutex.Unlock()
initMu.Lock()
initStarted++
initMu.Unlock()
// Only one should actually start initialization
oidc.initializeMetadata(server.URL)
} else {
oidc.firstRequestMutex.Unlock()
}
}()
}
wg.Wait()
// Verify only one initialization was started
if initStarted != 1 {
t.Errorf("expected exactly 1 initialization, got %d", initStarted)
}
// The metadata endpoint might be called once or not at all depending on timing
mu.Lock()
finalCount := metadataCallCount
mu.Unlock()
if finalCount > 1 {
t.Errorf("metadata endpoint called %d times, expected at most 1", finalCount)
}
})
}