-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy patherror_handler_test.go
More file actions
736 lines (690 loc) · 29.5 KB
/
error_handler_test.go
File metadata and controls
736 lines (690 loc) · 29.5 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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
package jwtmiddleware
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/auth0/go-jwt-middleware/v3/core"
"github.com/auth0/go-jwt-middleware/v3/validator"
)
func TestDefaultErrorHandler(t *testing.T) {
tests := []struct {
name string
err error
wantStatus int
wantError string
wantErrorDescription string
wantErrorCode string
wantWWWAuthenticate string
}{
{
name: "ErrJWTMissing",
err: ErrJWTMissing,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
// Per RFC 6750 Section 3.1, when auth is missing, no error codes should be included
wantErrorDescription: "",
wantWWWAuthenticate: `Bearer realm="api"`,
},
{
name: "ErrJWTInvalid",
err: ErrJWTInvalid,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "JWT is invalid",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="JWT is invalid"`,
},
{
name: "token expired",
err: core.NewValidationError(core.ErrorCodeTokenExpired, "token expired", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token expired",
wantErrorCode: "token_expired",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="The access token expired"`,
},
{
name: "token not yet valid",
err: core.NewValidationError(core.ErrorCodeTokenNotYetValid, "token not yet valid", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token is not yet valid",
wantErrorCode: "token_not_yet_valid",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="The access token is not yet valid"`,
},
{
name: "invalid signature",
err: core.NewValidationError(core.ErrorCodeInvalidSignature, "invalid signature", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token signature is invalid",
wantErrorCode: "invalid_signature",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="The access token signature is invalid"`,
},
{
name: "token malformed",
err: core.NewValidationError(core.ErrorCodeTokenMalformed, "malformed token", nil),
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "The access token is malformed",
wantErrorCode: "token_malformed",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_request", error_description="The access token is malformed"`,
},
{
name: "invalid issuer",
err: core.NewValidationError(core.ErrorCodeInvalidIssuer, "invalid issuer", nil),
wantStatus: http.StatusForbidden,
wantError: "insufficient_scope",
wantErrorDescription: "The access token was issued by an untrusted issuer",
wantErrorCode: "invalid_issuer",
wantWWWAuthenticate: `Bearer realm="api", error="insufficient_scope", error_description="The access token was issued by an untrusted issuer"`,
},
{
name: "invalid audience",
err: core.NewValidationError(core.ErrorCodeInvalidAudience, "invalid audience", nil),
wantStatus: http.StatusForbidden,
wantError: "insufficient_scope",
wantErrorDescription: "The access token audience does not match",
wantErrorCode: "invalid_audience",
wantWWWAuthenticate: `Bearer realm="api", error="insufficient_scope", error_description="The access token audience does not match"`,
},
{
name: "invalid algorithm",
err: core.NewValidationError(core.ErrorCodeInvalidAlgorithm, "invalid algorithm", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token uses an unsupported algorithm",
wantErrorCode: "invalid_algorithm",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="The access token uses an unsupported algorithm"`,
},
{
name: "JWKS fetch failed",
err: core.NewValidationError(core.ErrorCodeJWKSFetchFailed, "jwks fetch failed", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "Unable to verify the access token",
wantErrorCode: "jwks_fetch_failed",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="Unable to verify the access token"`,
},
{
name: "JWKS key not found",
err: core.NewValidationError(core.ErrorCodeJWKSKeyNotFound, "key not found", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "Unable to verify the access token",
wantErrorCode: "jwks_key_not_found",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="Unable to verify the access token"`,
},
{
name: "unknown validation error",
err: core.NewValidationError("unknown_code", "unknown error", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token is invalid",
wantErrorCode: "unknown_code",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_token", error_description="The access token is invalid"`,
},
{
name: "generic error",
err: assert.AnError,
wantStatus: http.StatusInternalServerError,
wantError: "server_error",
wantErrorDescription: "An internal error occurred while processing the request",
wantWWWAuthenticate: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
// Set context for backward compatibility - use DPoPDisabled mode for Bearer-only tests
ctx := r.Context()
ctx = core.SetDPoPMode(ctx, core.DPoPDisabled)
ctx = core.SetAuthScheme(ctx, AuthSchemeBearer)
r = r.WithContext(ctx)
DefaultErrorHandler(w, r, tt.err)
// Check status code
assert.Equal(t, tt.wantStatus, w.Code)
// Check Content-Type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Check WWW-Authenticate header
if tt.wantWWWAuthenticate != "" {
assert.Equal(t, tt.wantWWWAuthenticate, w.Header().Get("WWW-Authenticate"))
} else {
assert.Empty(t, w.Header().Get("WWW-Authenticate"))
}
// Check response body
var resp ErrorResponse
err := json.NewDecoder(w.Body).Decode(&resp)
require.NoError(t, err)
assert.Equal(t, tt.wantError, resp.Error)
assert.Equal(t, tt.wantErrorDescription, resp.ErrorDescription)
if tt.wantErrorCode != "" {
assert.Equal(t, tt.wantErrorCode, resp.ErrorCode)
}
})
}
}
func TestDefaultErrorHandler_DPoPErrors(t *testing.T) {
tests := []struct {
name string
err error
wantStatus int
wantError string
wantErrorDescription string
wantErrorCode string
wantWWWAuthenticate string
}{
{
name: "Missing token - DPoP Required mode only",
err: ErrJWTMissing,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
// Per RFC 6750 Section 3.1, when auth is missing, no error codes should be included
// In DPoP Required mode, only DPoP challenge should be returned
wantErrorDescription: "",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
{
name: "DPoP proof missing",
err: core.NewValidationError(core.ErrorCodeDPoPProofMissing, "DPoP proof is required", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "", // Empty for malformed requests
wantErrorCode: "dpop_proof_missing",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
{
name: "DPoP proof invalid",
err: core.NewValidationError(core.ErrorCodeDPoPProofInvalid, "DPoP proof JWT validation failed", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof JWT validation failed",
wantErrorCode: "dpop_proof_invalid",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof JWT validation failed"`,
},
{
name: "DPoP HTM mismatch",
err: core.NewValidationError(core.ErrorCodeDPoPHTMMismatch, "DPoP proof HTM does not match", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof HTM does not match",
wantErrorCode: "dpop_htm_mismatch",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof HTM does not match"`,
},
{
name: "DPoP HTU mismatch",
err: core.NewValidationError(core.ErrorCodeDPoPHTUMismatch, "DPoP proof HTU does not match", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof HTU does not match",
wantErrorCode: "dpop_htu_mismatch",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof HTU does not match"`,
},
{
name: "DPoP proof expired",
err: core.NewValidationError(core.ErrorCodeDPoPProofExpired, "DPoP proof is too old", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof is too old",
wantErrorCode: "dpop_proof_expired",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof is too old"`,
},
{
name: "DPoP proof too new",
err: core.NewValidationError(core.ErrorCodeDPoPProofTooNew, "DPoP proof iat is in the future", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof iat is in the future",
wantErrorCode: "dpop_proof_too_new",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof iat is in the future"`,
},
{
name: "DPoP ATH mismatch",
err: core.NewValidationError(core.ErrorCodeDPoPATHMismatch, "DPoP proof ath does not match access token hash", core.ErrInvalidDPoPProof),
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof ath does not match access token hash",
wantErrorCode: "dpop_ath_mismatch",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof ath does not match access token hash"`,
},
{
name: "DPoP binding mismatch",
err: core.NewValidationError(core.ErrorCodeDPoPBindingMismatch, "JKT does not match cnf claim", core.ErrDPoPBindingMismatch),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "JKT does not match cnf claim",
wantErrorCode: "dpop_binding_mismatch",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_token", error_description="JKT does not match cnf claim"`,
},
{
name: "Bearer not allowed",
err: core.NewValidationError(core.ErrorCodeBearerNotAllowed, "Bearer tokens are not allowed", core.ErrBearerNotAllowed),
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "Bearer tokens are not allowed (DPoP required)",
wantErrorCode: "bearer_not_allowed",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_request", error_description="Bearer tokens are not allowed (DPoP required)"`,
},
{
name: "DPoP not allowed - bare challenge (RFC 6750 Section 3.1)",
err: core.NewValidationError(core.ErrorCodeDPoPNotAllowed, "", core.ErrDPoPNotAllowed),
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "",
wantErrorCode: "dpop_not_allowed",
wantWWWAuthenticate: `Bearer realm="api"`,
},
{
name: "DPoP not allowed - with message (backward compatibility)",
err: core.NewValidationError(core.ErrorCodeDPoPNotAllowed, "DPoP tokens are not allowed", core.ErrDPoPNotAllowed),
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "DPoP tokens are not allowed",
wantErrorCode: "dpop_not_allowed",
wantWWWAuthenticate: `Bearer realm="api", error="invalid_request", error_description="DPoP tokens are not allowed"`,
},
{
name: "Config invalid",
err: core.NewValidationError(core.ErrorCodeConfigInvalid, "Configuration is invalid", nil),
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token is invalid",
wantErrorCode: "config_invalid",
wantWWWAuthenticate: `DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_token", error_description="The access token is invalid"`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
// Set context for DPoP required mode tests - use DPoPRequired to get DPoP-only challenges
ctx := r.Context()
ctx = core.SetDPoPMode(ctx, core.DPoPRequired)
ctx = core.SetAuthScheme(ctx, AuthSchemeDPoP)
r = r.WithContext(ctx)
DefaultErrorHandler(w, r, tt.err)
// Check status code
assert.Equal(t, tt.wantStatus, w.Code)
// Check Content-Type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Check WWW-Authenticate header
if tt.wantWWWAuthenticate != "" {
assert.Equal(t, tt.wantWWWAuthenticate, w.Header().Get("WWW-Authenticate"))
} else {
assert.Empty(t, w.Header().Get("WWW-Authenticate"))
}
// Check response body
var resp ErrorResponse
err := json.NewDecoder(w.Body).Decode(&resp)
require.NoError(t, err)
assert.Equal(t, tt.wantError, resp.Error)
assert.Equal(t, tt.wantErrorDescription, resp.ErrorDescription)
if tt.wantErrorCode != "" {
assert.Equal(t, tt.wantErrorCode, resp.ErrorCode)
}
})
}
}
func TestDefaultErrorHandler_DPoPAllowed_DualChallenges(t *testing.T) {
// Tests for RFC 9449 Section 6.1: When DPoP is allowed (not required),
// WWW-Authenticate should include BOTH Bearer and DPoP challenges.
tests := []struct {
name string
err error
authScheme AuthScheme
wantStatus int
wantError string
wantErrorDescription string
wantErrorCode string
wantWWWAuthenticateAll []string // All WWW-Authenticate headers (order matters)
wantBearerChallenge bool // Should have Bearer challenge
wantDPoPChallenge bool // Should have DPoP challenge
}{
{
name: "Bearer scheme with DPoP proof - invalid_request",
err: core.NewValidationError(core.ErrorCodeInvalidRequest, "Bearer scheme cannot be used when DPoP proof is present", nil),
authScheme: AuthSchemeBearer,
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "Bearer scheme cannot be used when DPoP proof is present",
wantErrorCode: "invalid_request",
wantWWWAuthenticateAll: []string{
`Bearer realm="api", error="invalid_request", error_description="Bearer scheme cannot be used when DPoP proof is present"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_request", error_description="Bearer scheme cannot be used when DPoP proof is present"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "Missing token - both challenges",
err: ErrJWTMissing,
authScheme: AuthSchemeUnknown,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
// Per RFC 6750 Section 3.1, when auth is missing, no error codes should be included
wantErrorDescription: "",
wantWWWAuthenticateAll: []string{
`Bearer realm="api"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "DPoP proof missing - Bearer + DPoP with error",
err: core.NewValidationError(core.ErrorCodeDPoPProofMissing, "Operation indicated DPoP use but the request has no DPoP HTTP Header", core.ErrInvalidDPoPProof),
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusBadRequest,
wantError: "invalid_request",
wantErrorDescription: "", // Empty per RFC 6750 Section 3.1 - malformed requests omit error_description
wantErrorCode: "dpop_proof_missing",
wantWWWAuthenticateAll: []string{
`Bearer realm="api"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "DPoP proof invalid - Bearer + DPoP with error",
err: core.NewValidationError(core.ErrorCodeDPoPProofInvalid, "Failed to verify DPoP proof", core.ErrInvalidDPoPProof),
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "Failed to verify DPoP proof",
wantErrorCode: "dpop_proof_invalid",
wantWWWAuthenticateAll: []string{
`Bearer realm="api"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="Failed to verify DPoP proof"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "DPoP HTM mismatch - Bearer + DPoP with error",
err: core.NewValidationError(core.ErrorCodeDPoPHTMMismatch, "DPoP proof HTM claim does not match HTTP method", core.ErrInvalidDPoPProof),
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantErrorDescription: "DPoP proof HTM claim does not match HTTP method",
wantErrorCode: "dpop_htm_mismatch",
wantWWWAuthenticateAll: []string{
`Bearer realm="api"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_dpop_proof", error_description="DPoP proof HTM claim does not match HTTP method"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "DPoP binding mismatch - Bearer + DPoP with error",
err: core.NewValidationError(core.ErrorCodeDPoPBindingMismatch, "DPoP proof JKT does not match access token cnf claim", core.ErrDPoPBindingMismatch),
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "DPoP proof JKT does not match access token cnf claim",
wantErrorCode: "dpop_binding_mismatch",
wantWWWAuthenticateAll: []string{
`Bearer realm="api"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_token", error_description="DPoP proof JKT does not match access token cnf claim"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
{
name: "Bearer token with error - Bearer with error + DPoP",
err: core.NewValidationError(core.ErrorCodeInvalidSignature, "signature verification failed", nil),
authScheme: AuthSchemeBearer,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantErrorDescription: "The access token signature is invalid",
wantErrorCode: "invalid_signature",
wantWWWAuthenticateAll: []string{
`Bearer realm="api", error="invalid_token", error_description="The access token signature is invalid"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
wantBearerChallenge: true,
wantDPoPChallenge: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
// Set context for DPoP ALLOWED mode (not required) - this should return BOTH challenges
ctx := r.Context()
ctx = core.SetDPoPMode(ctx, core.DPoPAllowed)
ctx = core.SetAuthScheme(ctx, tt.authScheme)
r = r.WithContext(ctx)
DefaultErrorHandler(w, r, tt.err)
// Check status code
assert.Equal(t, tt.wantStatus, w.Code)
// Check Content-Type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Check WWW-Authenticate headers (multiple headers per RFC 9449 Section 6.1)
authHeaders := w.Header().Values("WWW-Authenticate")
assert.Len(t, authHeaders, len(tt.wantWWWAuthenticateAll), "Should have %d WWW-Authenticate headers", len(tt.wantWWWAuthenticateAll))
// Verify both challenges are present
if tt.wantBearerChallenge {
foundBearer := false
for _, h := range authHeaders {
if len(h) >= 6 && h[:6] == "Bearer" {
foundBearer = true
break
}
}
assert.True(t, foundBearer, "Should have Bearer challenge")
}
if tt.wantDPoPChallenge {
foundDPoP := false
for _, h := range authHeaders {
if len(h) >= 4 && h[:4] == "DPoP" {
foundDPoP = true
break
}
}
assert.True(t, foundDPoP, "Should have DPoP challenge")
}
// Check exact header values (order-dependent)
for i, wantHeader := range tt.wantWWWAuthenticateAll {
if i < len(authHeaders) {
assert.Equal(t, wantHeader, authHeaders[i], "WWW-Authenticate header %d should match", i)
}
}
// Check response body
var resp ErrorResponse
err := json.NewDecoder(w.Body).Decode(&resp)
require.NoError(t, err)
assert.Equal(t, tt.wantError, resp.Error)
assert.Equal(t, tt.wantErrorDescription, resp.ErrorDescription)
if tt.wantErrorCode != "" {
assert.Equal(t, tt.wantErrorCode, resp.ErrorCode)
}
})
}
}
func TestDefaultErrorHandler_EdgeCases(t *testing.T) {
// Test edge cases and defensive branches for complete coverage
tests := []struct {
name string
err error
dpopMode core.DPoPMode
authScheme AuthScheme
wantStatus int
wantError string
wantWWWAuthenticate []string
}{
{
name: "DPoP error when DPoP is disabled (defensive case)",
err: core.NewValidationError(core.ErrorCodeDPoPProofInvalid, "DPoP proof invalid", core.ErrInvalidDPoPProof),
dpopMode: core.DPoPDisabled,
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusBadRequest,
wantError: "invalid_dpop_proof",
wantWWWAuthenticate: []string{
`Bearer realm="api", error="invalid_dpop_proof", error_description="DPoP proof invalid"`,
},
},
{
name: "Invalid token error in DPoP allowed mode",
err: core.NewValidationError(core.ErrorCodeInvalidToken, "Token is invalid", nil),
dpopMode: core.DPoPAllowed,
authScheme: AuthSchemeBearer,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantWWWAuthenticate: []string{
`Bearer realm="api", error="invalid_token", error_description="Token is invalid"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
},
{
name: "Custom claims validation error",
err: core.NewValidationError("custom_error", "Custom validation failed", nil),
dpopMode: core.DPoPAllowed,
authScheme: AuthSchemeUnknown,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantWWWAuthenticate: []string{
`Bearer realm="api", error="invalid_token", error_description="The access token is invalid"`,
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_token", error_description="The access token is invalid"`,
},
},
{
name: "DPoP scheme in allowed mode with token error - tests else branch on line 309",
err: core.NewValidationError(core.ErrorCodeTokenExpired, "Token expired", nil),
dpopMode: core.DPoPAllowed,
authScheme: AuthSchemeDPoP,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantWWWAuthenticate: []string{
`Bearer realm="api"`, // No error in Bearer challenge (line 309 - else branch)
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `", error="invalid_token", error_description="The access token expired"`,
},
},
{
name: "Invalid DPoP mode value (defensive default case)",
err: core.NewValidationError(core.ErrorCodeInvalidSignature, "Invalid signature", nil),
dpopMode: core.DPoPMode(99), // Invalid mode to trigger default case
authScheme: AuthSchemeBearer,
wantStatus: http.StatusUnauthorized,
wantError: "invalid_token",
wantWWWAuthenticate: []string{
`Bearer realm="api", error="invalid_token", error_description="The access token signature is invalid"`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test", nil)
ctx := r.Context()
ctx = core.SetDPoPMode(ctx, tt.dpopMode)
ctx = core.SetAuthScheme(ctx, tt.authScheme)
r = r.WithContext(ctx)
DefaultErrorHandler(w, r, tt.err)
assert.Equal(t, tt.wantStatus, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
authHeaders := w.Header().Values("WWW-Authenticate")
assert.Len(t, authHeaders, len(tt.wantWWWAuthenticate))
for i, wantHeader := range tt.wantWWWAuthenticate {
if i < len(authHeaders) {
assert.Equal(t, wantHeader, authHeaders[i])
}
}
var resp ErrorResponse
err := json.NewDecoder(w.Body).Decode(&resp)
require.NoError(t, err)
assert.Equal(t, tt.wantError, resp.Error)
})
}
}
func TestBuildWWWAuthenticateHeaders_DefaultCases(t *testing.T) {
// Tests defensive default cases in the build*WWWAuthenticateHeaders functions
tests := []struct {
name string
buildFunc string // which function to test
dpopMode core.DPoPMode
wantContains []string
}{
{
name: "buildBareWWWAuthenticateHeaders with invalid mode",
buildFunc: "bare",
dpopMode: core.DPoPMode(99), // Invalid mode
wantContains: []string{
`Bearer realm="api"`, // Default fallback
},
},
{
name: "buildDPoPWWWAuthenticateHeaders with invalid mode",
buildFunc: "dpop",
dpopMode: core.DPoPMode(99), // Invalid mode
wantContains: []string{
`DPoP algs="` + validator.DPoPSupportedAlgorithms + `"`,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var headers []string
switch tt.buildFunc {
case "bare":
headers = buildBareWWWAuthenticateHeaders(tt.dpopMode)
case "dpop":
headers = buildDPoPWWWAuthenticateHeaders("invalid_dpop_proof", "test error", tt.dpopMode)
}
// Check that we got headers and they contain expected strings
assert.NotEmpty(t, headers, "Should have at least one header")
for _, expected := range tt.wantContains {
found := false
for _, header := range headers {
if len(header) >= len(expected) && header[:len(expected)] == expected {
found = true
break
}
}
assert.True(t, found, "Expected to find %q in headers %v", expected, headers)
}
})
}
}
func TestErrorResponse_JSON(t *testing.T) {
tests := []struct {
name string
response ErrorResponse
wantJSON string
}{
{
name: "all fields",
response: ErrorResponse{
Error: "invalid_token",
ErrorDescription: "The token expired",
ErrorCode: "token_expired",
},
wantJSON: `{"error":"invalid_token","error_description":"The token expired","error_code":"token_expired"}`,
},
{
name: "without error code",
response: ErrorResponse{
Error: "invalid_token",
ErrorDescription: "JWT is invalid",
},
wantJSON: `{"error":"invalid_token","error_description":"JWT is invalid"}`,
},
{
name: "without description",
response: ErrorResponse{
Error: "server_error",
},
wantJSON: `{"error":"server_error"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(tt.response)
require.NoError(t, err)
assert.JSONEq(t, tt.wantJSON, string(data))
})
}
}