Debian Codegraph @

pkg/op/auth_request_test.go

raw
1 package op_test
2
3 import (
4 "context"
5 "errors"
6 "io"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "reflect"
11 "testing"
12
13 "github.com/golang/mock/gomock"
14 "github.com/stretchr/testify/assert"
15 "github.com/stretchr/testify/require"
16 "github.com/zitadel/oidc/v3/example/server/storage"
17 tu "github.com/zitadel/oidc/v3/internal/testutil"
18 httphelper "github.com/zitadel/oidc/v3/pkg/http"
19 "github.com/zitadel/oidc/v3/pkg/oidc"
20 "github.com/zitadel/oidc/v3/pkg/op"
21 "github.com/zitadel/oidc/v3/pkg/op/mock"
22 "github.com/zitadel/schema"
23 )
24
25 func TestAuthorize(t *testing.T) {
26 tests := []struct {
27 name string
28 req *http.Request
29 expect func(a *mock.MockAuthorizerMockRecorder)
30 }{
31 {
32 name: "parse error", // used to panic, see issue #315
33 req: httptest.NewRequest(http.MethodPost, "/?;", nil),
34 },
35 }
36 for _, tt := range tests {
37 t.Run(tt.name, func(t *testing.T) {
38 w := httptest.NewRecorder()
39 authorizer := mock.NewMockAuthorizer(gomock.NewController(t))
40
41 expect := authorizer.EXPECT()
42 expect.Decoder().Return(schema.NewDecoder())
43
44 if tt.expect != nil {
45 tt.expect(expect)
46 }
47
48 op.Authorize(w, tt.req, authorizer)
49 })
50 }
51 }
52
53 // customAuthorizeValidator is an Authorizer that also implements
54 // AuthorizeValidator, replacing the default validation closure in Authorize.
55 type customAuthorizeValidator struct {
56 *mock.MockAuthorizer
57 validate func(context.Context, *oidc.AuthRequest, op.Storage, *op.IDTokenHintVerifier) (string, error)
58 }
59
60 func (c *customAuthorizeValidator) ValidateAuthRequest(ctx context.Context, authReq *oidc.AuthRequest, storage op.Storage, verifier *op.IDTokenHintVerifier) (string, error) {
61 return c.validate(ctx, authReq, storage, verifier)
62 }
63
64 type stubAuthRequest struct {
65 op.AuthRequest
66 id string
67 }
68
69 func (s *stubAuthRequest) GetID() string { return s.id }
70
71 // TestAuthorizeCustomValidator authorizes with an Authorizer that implements
72 // AuthorizeValidator. The custom validator replaces the default validation
73 // closure, which is what assigns Authorize's local client, so Authorize must
74 // resolve the client itself before RedirectToLogin dereferences it.
75 // Used to panic with a nil-pointer dereference, see issue #909.
76 func TestAuthorizeCustomValidator(t *testing.T) {
77 ctrl := gomock.NewController(t)
78 storage := mock.NewMockStorage(ctrl)
79 client := mock.NewMockClient(ctrl)
80
81 authorizer := &customAuthorizeValidator{
82 MockAuthorizer: mock.NewMockAuthorizer(ctrl),
83 validate: func(context.Context, *oidc.AuthRequest, op.Storage, *op.IDTokenHintVerifier) (string, error) {
84 // succeeds without assigning Authorize's local client variable
85 return "userID", nil
86 },
87 }
88 expect := authorizer.MockAuthorizer.EXPECT()
89 expect.Decoder().Return(schema.NewDecoder())
90 expect.Storage().Return(storage).AnyTimes()
91 expect.IDTokenHintVerifier(gomock.Any()).Return(nil)
92
93 storage.EXPECT().GetClientByClientID(gomock.Any(), "native").Return(client, nil)
94 storage.EXPECT().CreateAuthRequest(gomock.Any(), gomock.Any(), "userID").Return(&stubAuthRequest{id: "authReqID"}, nil)
95 client.EXPECT().LoginURL("authReqID").Return("/login?authRequestID=authReqID")
96
97 req := httptest.NewRequest(http.MethodGet,
98 "/authorize?client_id=native&redirect_uri=http%3A%2F%2Flocalhost%3A9999%2Fcallback&scope=openid&response_type=code",
99 nil)
100 w := httptest.NewRecorder()
101 op.Authorize(w, req, authorizer)
102
103 resp := w.Result()
104 require.Equal(t, http.StatusFound, resp.StatusCode)
105 assert.Equal(t, "/login?authRequestID=authReqID", resp.Header.Get("Location"))
106 }
107
108 // TestAuthorizeCustomValidatorClientLookupError covers the fallback client
109 // lookup failing after a custom AuthorizeValidator succeeded. Because the
110 // library cannot assume the custom validator verified the redirect_uri, the
111 // error must be rendered directly instead of redirecting to the (potentially
112 // unvalidated) redirect_uri, which would be an open redirect.
113 func TestAuthorizeCustomValidatorClientLookupError(t *testing.T) {
114 ctrl := gomock.NewController(t)
115 storage := mock.NewMockStorage(ctrl)
116
117 authorizer := &customAuthorizeValidator{
118 MockAuthorizer: mock.NewMockAuthorizer(ctrl),
119 validate: func(context.Context, *oidc.AuthRequest, op.Storage, *op.IDTokenHintVerifier) (string, error) {
120 // succeeds without assigning Authorize's local client variable
121 return "userID", nil
122 },
123 }
124 expect := authorizer.MockAuthorizer.EXPECT()
125 expect.Decoder().Return(schema.NewDecoder())
126 expect.Storage().Return(storage).AnyTimes()
127 expect.IDTokenHintVerifier(gomock.Any()).Return(nil)
128
129 storage.EXPECT().GetClientByClientID(gomock.Any(), "native").Return(nil, errors.New("client not found"))
130
131 req := httptest.NewRequest(http.MethodGet,
132 "/authorize?client_id=native&redirect_uri=http%3A%2F%2Flocalhost%3A9999%2Fcallback&scope=openid&response_type=code",
133 nil)
134 w := httptest.NewRecorder()
135 op.Authorize(w, req, authorizer)
136
137 resp := w.Result()
138 require.Equal(t, http.StatusBadRequest, resp.StatusCode)
139 assert.Empty(t, resp.Header.Get("Location"))
140 body, err := io.ReadAll(resp.Body)
141 require.NoError(t, err)
142 assert.Contains(t, string(body), "unable to retrieve client by id")
143 }
144
145 func TestParseAuthorizeRequest(t *testing.T) {
146 type args struct {
147 r *http.Request
148 decoder httphelper.Decoder
149 }
150 type res struct {
151 want *oidc.AuthRequest
152 err bool
153 }
154 tests := []struct {
155 name string
156 args args
157 res res
158 }{
159 {
160 "parsing form error",
161 args{
162 &http.Request{URL: &url.URL{RawQuery: "invalid=%%param"}},
163 schema.NewDecoder(),
164 },
165 res{
166 nil,
167 true,
168 },
169 },
170 {
171 "decoding error",
172 args{
173 &http.Request{URL: &url.URL{RawQuery: "unknown=value"}},
174 func() httphelper.Decoder {
175 decoder := schema.NewDecoder()
176 decoder.IgnoreUnknownKeys(false)
177 return decoder
178 }(),
179 },
180 res{
181 nil,
182 true,
183 },
184 },
185 {
186 "parsing ok",
187 args{
188 &http.Request{URL: &url.URL{RawQuery: "scope=openid"}},
189 func() httphelper.Decoder {
190 decoder := schema.NewDecoder()
191 decoder.IgnoreUnknownKeys(false)
192 return decoder
193 }(),
194 },
195 res{
196 &oidc.AuthRequest{Scopes: oidc.SpaceDelimitedArray{"openid"}},
197 false,
198 },
199 },
200 }
201 for _, tt := range tests {
202 t.Run(tt.name, func(t *testing.T) {
203 got, err := op.ParseAuthorizeRequest(tt.args.r, tt.args.decoder)
204 if (err != nil) != tt.res.err {
205 t.Errorf("ParseAuthorizeRequest() error = %v, wantErr %v", err, tt.res.err)
206 }
207 if !reflect.DeepEqual(got, tt.res.want) {
208 t.Errorf("ParseAuthorizeRequest() got = %v, want %v", got, tt.res.want)
209 }
210 })
211 }
212 }
213
214 func TestValidateAuthRequest(t *testing.T) {
215 type args struct {
216 authRequest *oidc.AuthRequest
217 storage op.Storage
218 verifier *op.IDTokenHintVerifier
219 }
220 tests := []struct {
221 name string
222 args args
223 wantErr error
224 }{
225 {
226 "scope missing fails",
227 args{&oidc.AuthRequest{}, mock.NewMockStorageExpectValidClientID(t), nil},
228 oidc.ErrInvalidRequest(),
229 },
230 {
231 "response_type missing fails",
232 args{&oidc.AuthRequest{Scopes: []string{"openid"}}, mock.NewMockStorageExpectValidClientID(t), nil},
233 oidc.ErrInvalidRequest(),
234 },
235 {
236 "client_id missing fails",
237 args{&oidc.AuthRequest{Scopes: []string{"openid"}, ResponseType: oidc.ResponseTypeCode}, mock.NewMockStorageExpectValidClientID(t), nil},
238 oidc.ErrInvalidRequest(),
239 },
240 {
241 "redirect_uri missing fails",
242 args{&oidc.AuthRequest{Scopes: []string{"openid"}, ResponseType: oidc.ResponseTypeCode, ClientID: "client_id"}, mock.NewMockStorageExpectValidClientID(t), nil},
243 oidc.ErrInvalidRequest(),
244 },
245 }
246 for _, tt := range tests {
247 t.Run(tt.name, func(t *testing.T) {
248 _, err := op.ValidateAuthRequest(context.TODO(), tt.args.authRequest, tt.args.storage, tt.args.verifier)
249 if tt.wantErr == nil && err != nil {
250 t.Errorf("ValidateAuthRequest() unexpected error = %v", err)
251 }
252 if tt.wantErr != nil && !errors.Is(err, tt.wantErr) {
253 t.Errorf("ValidateAuthRequest() unexpected error = %v, want = %v", err, tt.wantErr)
254 }
255 })
256 }
257 }
258
259 func TestValidateAuthReqPrompt(t *testing.T) {
260 type args struct {
261 prompts []string
262 maxAge *uint
263 }
264 type res struct {
265 maxAge *uint
266 err error
267 }
268 tests := []struct {
269 name string
270 args args
271 res res
272 }{
273 {
274 "no prompts and maxAge, ok",
275 args{
276 nil,
277 nil,
278 },
279 res{
280 nil,
281 nil,
282 },
283 },
284 {
285 "no prompts but maxAge, ok",
286 args{
287 nil,
288 oidc.NewMaxAge(10),
289 },
290 res{
291 oidc.NewMaxAge(10),
292 nil,
293 },
294 },
295 {
296 "prompt none, ok",
297 args{
298 []string{"none"},
299 oidc.NewMaxAge(10),
300 },
301 res{
302 oidc.NewMaxAge(10),
303 nil,
304 },
305 },
306 {
307 "prompt none with others, err",
308 args{
309 []string{"none", "login"},
310 oidc.NewMaxAge(10),
311 },
312 res{
313 nil,
314 oidc.ErrInvalidRequest(),
315 },
316 },
317 {
318 "prompt login, ok",
319 args{
320 []string{"login"},
321 nil,
322 },
323 res{
324 oidc.NewMaxAge(0),
325 nil,
326 },
327 },
328 {
329 "prompt login with maxAge, ok",
330 args{
331 []string{"login"},
332 oidc.NewMaxAge(10),
333 },
334 res{
335 oidc.NewMaxAge(0),
336 nil,
337 },
338 },
339 }
340 for _, tt := range tests {
341 t.Run(tt.name, func(t *testing.T) {
342 maxAge, err := op.ValidateAuthReqPrompt(tt.args.prompts, tt.args.maxAge)
343 if tt.res.err == nil && err != nil {
344 t.Errorf("ValidateAuthRequest() unexpected error = %v", err)
345 }
346 if tt.res.err != nil && !errors.Is(err, tt.res.err) {
347 t.Errorf("ValidateAuthRequest() unexpected error = %v, want = %v", err, tt.res.err)
348 }
349 assert.Equal(t, tt.res.maxAge, maxAge)
350 })
351 }
352 }
353
354 func TestValidateAuthReqScopes(t *testing.T) {
355 type args struct {
356 client op.Client
357 scopes []string
358 }
359 type res struct {
360 err bool
361 scopes []string
362 }
363 tests := []struct {
364 name string
365 args args
366 res res
367 }{
368 {
369 "scopes missing fails",
370 args{},
371 res{
372 err: true,
373 },
374 },
375 {
376 "scope ok",
377 args{
378 mock.NewClientExpectAny(t, op.ApplicationTypeWeb),
379 []string{"openid"},
380 },
381 res{
382 scopes: []string{"openid"},
383 },
384 },
385 {
386 "scope with drop ok",
387 args{
388 mock.NewClientExpectAny(t, op.ApplicationTypeWeb),
389 []string{"openid", "email", "unknown"},
390 },
391 res{
392 scopes: []string{"openid", "email"},
393 },
394 },
395 }
396 for _, tt := range tests {
397 t.Run(tt.name, func(t *testing.T) {
398 scopes, err := op.ValidateAuthReqScopes(tt.args.client, tt.args.scopes)
399 if (err != nil) != tt.res.err {
400 t.Errorf("ValidateAuthReqScopes() error = %v, wantErr %v", err, tt.res.err)
401 }
402 assert.ElementsMatch(t, scopes, tt.res.scopes)
403 })
404 }
405 }
406
407 func TestValidateAuthReqRedirectURI(t *testing.T) {
408 type args struct {
409 uri string
410 client op.Client
411 responseType oidc.ResponseType
412 }
413 tests := []struct {
414 name string
415 args args
416 wantErr bool
417 }{
418 {
419 "empty fails",
420 args{
421 "",
422 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
423 oidc.ResponseTypeCode,
424 },
425 true,
426 },
427 {
428 "unregistered https fails",
429 args{
430 "https://unregistered.com/callback",
431 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
432 oidc.ResponseTypeCode,
433 },
434 true,
435 },
436 {
437 "unregistered http fails",
438 args{
439 "http://unregistered.com/callback",
440 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
441 oidc.ResponseTypeCode,
442 },
443 true,
444 },
445 {
446 "code flow registered https web ok",
447 args{
448 "https://registered.com/callback",
449 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
450 oidc.ResponseTypeCode,
451 },
452 false,
453 },
454 {
455 "code flow registered https native ok",
456 args{
457 "https://registered.com/callback",
458 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeNative, nil, false),
459 oidc.ResponseTypeCode,
460 },
461 false,
462 },
463 {
464 "code flow registered https user agent ok",
465 args{
466 "https://registered.com/callback",
467 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, false),
468 oidc.ResponseTypeCode,
469 },
470 false,
471 },
472 {
473 "code flow registered http confidential (web) ok",
474 args{
475 "http://registered.com/callback",
476 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
477 oidc.ResponseTypeCode,
478 },
479 false,
480 },
481 {
482 "code flow registered http not confidential (native) fails",
483 args{
484 "http://registered.com/callback",
485 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeNative, nil, false),
486 oidc.ResponseTypeCode,
487 },
488 true,
489 },
490 {
491 "code flow registered http not confidential (user agent) fails",
492 args{
493 "http://registered.com/callback",
494 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, false),
495 oidc.ResponseTypeCode,
496 },
497 true,
498 },
499 {
500 "code flow registered http localhost native ok",
501 args{
502 "http://localhost:4200/callback",
503 mock.NewClientWithConfig(t, []string{"http://localhost/callback"}, op.ApplicationTypeNative, nil, false),
504 oidc.ResponseTypeCode,
505 },
506 false,
507 },
508 {
509 "code flow registered http loopback v4 native ok",
510 args{
511 "http://127.0.0.1:4200/callback",
512 mock.NewClientWithConfig(t, []string{"http://127.0.0.1/callback"}, op.ApplicationTypeNative, nil, false),
513 oidc.ResponseTypeCode,
514 },
515 false,
516 },
517 {
518 "code flow registered http loopback v6 native ok",
519 args{
520 "http://[::1]:4200/callback",
521 mock.NewClientWithConfig(t, []string{"http://[::1]/callback"}, op.ApplicationTypeNative, nil, false),
522 oidc.ResponseTypeCode,
523 },
524 false,
525 },
526 {
527 "code flow registered https loopback v4 native ok",
528 args{
529 "https://127.0.0.1:4200/callback",
530 mock.NewClientWithConfig(t, []string{"https://127.0.0.1/callback"}, op.ApplicationTypeNative, nil, false),
531 oidc.ResponseTypeCode,
532 },
533 false,
534 },
535 {
536 "code flow registered https loopback v6 native ok",
537 args{
538 "https://[::1]:4200/callback",
539 mock.NewClientWithConfig(t, []string{"https://[::1]/callback"}, op.ApplicationTypeNative, nil, false),
540 oidc.ResponseTypeCode,
541 },
542 false,
543 },
544 {
545 "code flow unregistered http native fails",
546 args{
547 "http://unregistered.com/callback",
548 mock.NewClientWithConfig(t, []string{"http://locahost/callback"}, op.ApplicationTypeNative, nil, false),
549 oidc.ResponseTypeCode,
550 },
551 true,
552 },
553 {
554 "code flow unregistered custom native fails",
555 args{
556 "unregistered://callback",
557 mock.NewClientWithConfig(t, []string{"registered://callback"}, op.ApplicationTypeNative, nil, false),
558 oidc.ResponseTypeCode,
559 },
560 true,
561 },
562 {
563 "code flow unregistered loopback native fails",
564 args{
565 "http://[::1]:4200/unregistered",
566 mock.NewClientWithConfig(t, []string{"http://[::1]:4200/callback"}, op.ApplicationTypeNative, nil, false),
567 oidc.ResponseTypeCode,
568 },
569 true,
570 },
571 {
572 "code flow registered custom not native (web) fails",
573 args{
574 "custom://callback",
575 mock.NewClientWithConfig(t, []string{"custom://callback"}, op.ApplicationTypeWeb, nil, false),
576 oidc.ResponseTypeCode,
577 },
578 true,
579 },
580 {
581 "code flow registered custom not native (user agent) fails",
582 args{
583 "custom://callback",
584 mock.NewClientWithConfig(t, []string{"custom://callback"}, op.ApplicationTypeUserAgent, nil, false),
585 oidc.ResponseTypeCode,
586 },
587 true,
588 },
589 {
590 "code flow registered custom native ok",
591 args{
592 "custom://callback",
593 mock.NewClientWithConfig(t, []string{"custom://callback"}, op.ApplicationTypeNative, nil, false),
594 oidc.ResponseTypeCode,
595 },
596 false,
597 },
598 {
599 "code flow dev mode http ok",
600 args{
601 "http://registered.com/callback",
602 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, true),
603 oidc.ResponseTypeCode,
604 },
605 false,
606 },
607 {
608 "implicit flow registered ok",
609 args{
610 "https://registered.com/callback",
611 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, false),
612 oidc.ResponseTypeIDToken,
613 },
614 false,
615 },
616 {
617 "implicit flow unregistered fails",
618 args{
619 "https://unregistered.com/callback",
620 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, false),
621 oidc.ResponseTypeIDToken,
622 },
623 true,
624 },
625 {
626 "implicit flow registered http localhost native ok",
627 args{
628 "http://localhost:9999/callback",
629 mock.NewClientWithConfig(t, []string{"http://localhost:9999/callback"}, op.ApplicationTypeNative, nil, false),
630 oidc.ResponseTypeIDToken,
631 },
632 false,
633 },
634 {
635 "implicit flow registered http localhost web fails",
636 args{
637 "http://localhost:9999/callback",
638 mock.NewClientWithConfig(t, []string{"http://localhost:9999/callback"}, op.ApplicationTypeWeb, nil, false),
639 oidc.ResponseTypeIDToken,
640 },
641 true,
642 },
643 {
644 "implicit flow registered http localhost user agent fails",
645 args{
646 "http://localhost:9999/callback",
647 mock.NewClientWithConfig(t, []string{"http://localhost:9999/callback"}, op.ApplicationTypeUserAgent, nil, false),
648 oidc.ResponseTypeIDToken,
649 },
650 true,
651 },
652 {
653 "implicit flow http non localhost fails",
654 args{
655 "http://registered.com/callback",
656 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeNative, nil, false),
657 oidc.ResponseTypeIDToken,
658 },
659 true,
660 },
661 {
662 "implicit flow custom fails",
663 args{
664 "custom://callback",
665 mock.NewClientWithConfig(t, []string{"custom://callback"}, op.ApplicationTypeNative, nil, false),
666 oidc.ResponseTypeIDToken,
667 },
668 false,
669 },
670 {
671 "implicit flow dev mode http ok",
672 args{
673 "http://registered.com/callback",
674 mock.NewClientWithConfig(t, []string{"http://registered.com/callback"}, op.ApplicationTypeUserAgent, nil, true),
675 oidc.ResponseTypeIDToken,
676 },
677 false,
678 },
679 {
680 "code flow dev mode has redirect globs regular ok",
681 args{
682 "http://registered.com/callback",
683 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://registered.com/*"}, op.ApplicationTypeUserAgent, nil, true),
684 oidc.ResponseTypeCode,
685 },
686 false,
687 },
688 {
689 "code flow dev mode has redirect globs wildcard ok",
690 args{
691 "http://registered.com/callback",
692 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://registered.com/*"}, op.ApplicationTypeUserAgent, nil, true),
693 oidc.ResponseTypeCode,
694 },
695 false,
696 },
697 {
698 "code flow dev mode has redirect globs double star ok",
699 args{
700 "http://registered.com/callback",
701 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://**/*"}, op.ApplicationTypeUserAgent, nil, true),
702 oidc.ResponseTypeCode,
703 },
704 false,
705 },
706 {
707 "code flow dev mode has redirect globs double star ok",
708 args{
709 "http://registered.com/callback",
710 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://**/*"}, op.ApplicationTypeUserAgent, nil, true),
711 oidc.ResponseTypeCode,
712 },
713 false,
714 },
715 {
716 "code flow dev mode has redirect globs IPv6 ok",
717 args{
718 "http://[::1]:80/callback",
719 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://\\[::1\\]:80/*"}, op.ApplicationTypeUserAgent, nil, true),
720 oidc.ResponseTypeCode,
721 },
722 false,
723 },
724 {
725 "code flow dev mode has redirect globs bad pattern",
726 args{
727 "http://registered.com/callback",
728 mock.NewHasRedirectGlobsWithConfig(t, []string{"http://**/\\"}, op.ApplicationTypeUserAgent, nil, true),
729 oidc.ResponseTypeCode,
730 },
731 true,
732 },
733 {
734 // A redirect_uri reaches this validator already decoded by
735 // r.ParseForm, so a percent-encoded literal denotes a
736 // different URI than the one registered and must not match.
737 // Guards against re-introducing a second decode here; see #968.
738 "code flow percent-encoded redirect_uri does not match",
739 args{
740 "https%3A%2F%2Fregistered.com%2Fcallback",
741 mock.NewClientWithConfig(t, []string{"https://registered.com/callback"}, op.ApplicationTypeWeb, nil, false),
742 oidc.ResponseTypeCode,
743 },
744 true,
745 },
746 }
747 for _, tt := range tests {
748 t.Run(tt.name, func(t *testing.T) {
749 if err := op.ValidateAuthReqRedirectURI(tt.args.client, tt.args.uri, tt.args.responseType); (err != nil) != tt.wantErr {
750 t.Errorf("ValidateRedirectURI() error = %v, wantErr %v", err, tt.wantErr)
751 }
752 })
753 }
754 }
755
756 func TestLoopbackOrLocalhost(t *testing.T) {
757 type args struct {
758 url string
759 }
760 tests := []struct {
761 name string
762 args args
763 want bool
764 }{
765 {
766 "not parsable, false",
767 args{url: string('\n')},
768 false,
769 },
770 {
771 "not http, false",
772 args{url: "localhost/test"},
773 false,
774 },
775 {
776 "not http, false",
777 args{url: "http://localhost.com/test"},
778 false,
779 },
780 {
781 "v4 no port ok",
782 args{url: "http://127.0.0.1/test"},
783 true,
784 },
785 {
786 "v6 short no port ok",
787 args{url: "http://[::1]/test"},
788 true,
789 },
790 {
791 "v6 long no port ok",
792 args{url: "http://[0:0:0:0:0:0:0:1]/test"},
793 true,
794 },
795 {
796 "localhost no port ok",
797 args{url: "http://localhost/test"},
798 true,
799 },
800 {
801 "v4 with port ok",
802 args{url: "http://127.0.0.1:4200/test"},
803 true,
804 },
805 {
806 "v6 short with port ok",
807 args{url: "http://[::1]:4200/test"},
808 true,
809 },
810 {
811 "v6 long with port ok",
812 args{url: "http://[0:0:0:0:0:0:0:1]:4200/test"},
813 true,
814 },
815 {
816 "localhost with port ok",
817 args{url: "http://localhost:4200/test"},
818 true,
819 },
820 }
821 for _, tt := range tests {
822 t.Run(tt.name, func(t *testing.T) {
823 if _, got := op.HTTPLoopbackOrLocalhost(tt.args.url); got != tt.want {
824 t.Errorf("loopbackOrLocalhost() = %v, want %v", got, tt.want)
825 }
826 })
827 }
828 }
829
830 func TestValidateAuthReqResponseType(t *testing.T) {
831 type args struct {
832 responseType oidc.ResponseType
833 client op.Client
834 }
835 tests := []struct {
836 name string
837 args args
838 wantErr bool
839 }{
840 {
841 "empty response type",
842 args{
843 "",
844 mock.NewClientWithConfig(t, nil, op.ApplicationTypeNative, []oidc.ResponseType{oidc.ResponseTypeCode}, true),
845 },
846 true,
847 },
848 {
849 "response type missing in client config",
850 args{
851 oidc.ResponseTypeIDToken,
852 mock.NewClientWithConfig(t, nil, op.ApplicationTypeNative, []oidc.ResponseType{oidc.ResponseTypeCode}, true),
853 },
854 true,
855 },
856 {
857 "valid response type",
858 args{
859 oidc.ResponseTypeCode,
860 mock.NewClientWithConfig(t, nil, op.ApplicationTypeNative, []oidc.ResponseType{oidc.ResponseTypeCode}, true),
861 },
862 false,
863 },
864 }
865 for _, tt := range tests {
866 t.Run(tt.name, func(t *testing.T) {
867 if err := op.ValidateAuthReqResponseType(tt.args.client, tt.args.responseType); (err != nil) != tt.wantErr {
868 t.Errorf("ValidateAuthReqScopes() error = %v, wantErr %v", err, tt.wantErr)
869 }
870 })
871 }
872 }
873
874 func TestRedirectToLogin(t *testing.T) {
875 type args struct {
876 authReqID string
877 client op.Client
878 w http.ResponseWriter
879 r *http.Request
880 }
881 tests := []struct {
882 name string
883 args args
884 }{
885 {
886 "redirect ok",
887 args{
888 "id",
889 mock.NewClientExpectAny(t, op.ApplicationTypeNative),
890 httptest.NewRecorder(),
891 httptest.NewRequest("GET", "/authorize", nil),
892 },
893 },
894 }
895 for _, tt := range tests {
896 t.Run(tt.name, func(t *testing.T) {
897 op.RedirectToLogin(tt.args.authReqID, tt.args.client, tt.args.w, tt.args.r)
898 rec := tt.args.w.(*httptest.ResponseRecorder)
899 require.Equal(t, http.StatusFound, rec.Code)
900 require.Equal(t, "/login?id=id", rec.Header().Get("location"))
901 })
902 }
903 }
904
905 func TestAuthResponseURL(t *testing.T) {
906 type args struct {
907 redirectURI string
908 responseType oidc.ResponseType
909 responseMode oidc.ResponseMode
910 response any
911 encoder httphelper.Encoder
912 }
913 type res struct {
914 url string
915 err error
916 }
917 tests := []struct {
918 name string
919 args args
920 res res
921 }{
922 {
923 "encoding error",
924 args{
925 "uri",
926 oidc.ResponseTypeCode,
927 "",
928 map[string]any{"test": "test"},
929 &mockEncoder{
930 errors.New("error encoding"),
931 },
932 },
933 res{
934 "",
935 oidc.ErrServerError(),
936 },
937 },
938 {
939 "response mode query",
940 args{
941 "uri",
942 oidc.ResponseTypeIDToken,
943 oidc.ResponseModeQuery,
944 map[string][]string{"test": {"test"}},
945 &mockEncoder{},
946 },
947 res{
948 "uri?test=test",
949 nil,
950 },
951 },
952 {
953 "response mode fragment",
954 args{
955 "uri",
956 oidc.ResponseTypeCode,
957 oidc.ResponseModeFragment,
958 map[string][]string{"test": {"test"}},
959 &mockEncoder{},
960 },
961 res{
962 "uri#test=test",
963 nil,
964 },
965 },
966 {
967 "response mode fragment with values that need escaping",
968 args{
969 "uri",
970 oidc.ResponseTypeCode,
971 oidc.ResponseModeFragment,
972 map[string][]string{"state": {"PADTEST=="}, "test": {"a b/c&d"}},
973 &mockEncoder{},
974 },
975 res{
976 "uri#state=PADTEST%3D%3D&test=a+b%2Fc%26d",
977 nil,
978 },
979 },
980 {
981 "response type id token with values that need escaping",
982 args{
983 "uri?param=value",
984 oidc.ResponseTypeIDToken,
985 "",
986 map[string][]string{"state": {"eyJ0IjoxfQ=="}},
987 &mockEncoder{},
988 },
989 res{
990 "uri?param=value#state=eyJ0IjoxfQ%3D%3D",
991 nil,
992 },
993 },
994 {
995 "response type code",
996 args{
997 "uri",
998 oidc.ResponseTypeCode,
999 "",
1000 map[string][]string{"test": {"test"}},
1001 &mockEncoder{},
1002 },
1003 res{
1004 "uri?test=test",
1005 nil,
1006 },
1007 },
1008 {
1009 "response type id token",
1010 args{
1011 "uri",
1012 oidc.ResponseTypeIDToken,
1013 "",
1014 map[string][]string{"test": {"test"}},
1015 &mockEncoder{},
1016 },
1017 res{
1018 "uri#test=test",
1019 nil,
1020 },
1021 },
1022 {
1023 "with query",
1024 args{
1025 "uri?param=value",
1026 oidc.ResponseTypeCode,
1027 "",
1028 map[string][]string{"test": {"test"}},
1029 &mockEncoder{},
1030 },
1031 res{
1032 "uri?param=value&test=test",
1033 nil,
1034 },
1035 },
1036 {
1037 "with query response type id token",
1038 args{
1039 "uri?param=value",
1040 oidc.ResponseTypeIDToken,
1041 "",
1042 map[string][]string{"test": {"test"}},
1043 &mockEncoder{},
1044 },
1045 res{
1046 "uri?param=value#test=test",
1047 nil,
1048 },
1049 },
1050 {
1051 "with existing query",
1052 args{
1053 "uri?test=value",
1054 oidc.ResponseTypeCode,
1055 "",
1056 map[string][]string{"test": {"test"}},
1057 &mockEncoder{},
1058 },
1059 res{
1060 "uri?test=value&test=test",
1061 nil,
1062 },
1063 },
1064 {
1065 "with existing query response type id token",
1066 args{
1067 "uri?test=value",
1068 oidc.ResponseTypeIDToken,
1069 "",
1070 map[string][]string{"test": {"test"}},
1071 &mockEncoder{},
1072 },
1073 res{
1074 "uri?test=value#test=test",
1075 nil,
1076 },
1077 },
1078 {
1079 "with existing query and multiple values",
1080 args{
1081 "uri?test=value",
1082 oidc.ResponseTypeCode,
1083 "",
1084 map[string][]string{"test": {"test", "test2"}},
1085 &mockEncoder{},
1086 },
1087 res{
1088 "uri?test=value&test=test&test=test2",
1089 nil,
1090 },
1091 },
1092 {
1093 "with existing query and multiple values response type id token",
1094 args{
1095 "uri?test=value",
1096 oidc.ResponseTypeIDToken,
1097 "",
1098 map[string][]string{"test": {"test", "test2"}},
1099 &mockEncoder{},
1100 },
1101 res{
1102 "uri?test=value#test=test&test=test2",
1103 nil,
1104 },
1105 },
1106 }
1107 for _, tt := range tests {
1108 t.Run(tt.name, func(t *testing.T) {
1109 got, err := op.AuthResponseURL(tt.args.redirectURI, tt.args.responseType, tt.args.responseMode, tt.args.response, tt.args.encoder)
1110 if tt.res.err == nil && err != nil {
1111 t.Errorf("ValidateAuthRequest() unexpected error = %v", err)
1112 }
1113 if tt.res.err != nil && !errors.Is(err, tt.res.err) {
1114 t.Errorf("ValidateAuthRequest() unexpected error = %v, want = %v", err, tt.res.err)
1115 }
1116 if got != tt.res.url {
1117 t.Errorf("AuthResponseURL() got = %v, want %v", got, tt.res.url)
1118 }
1119 })
1120 }
1121 }
1122
1123 type mockEncoder struct {
1124 err error
1125 }
1126
1127 func (m *mockEncoder) Encode(src any, dst map[string][]string) error {
1128 if m.err != nil {
1129 return m.err
1130 }
1131 for s, strings := range src.(map[string][]string) {
1132 dst[s] = strings
1133 }
1134 return nil
1135 }
1136
1137 // mockCrypto implements the op.Crypto interface
1138 // and in always equals out. (It doesn't crypt anything).
1139 // When returnErr != nil, that error is always returned instead.
1140 type mockCrypto struct {
1141 returnErr error
1142 }
1143
1144 func (c *mockCrypto) Encrypt(s string) (string, error) {
1145 if c.returnErr != nil {
1146 return "", c.returnErr
1147 }
1148 return s, nil
1149 }
1150
1151 func (c *mockCrypto) Decrypt(s string) (string, error) {
1152 if c.returnErr != nil {
1153 return "", c.returnErr
1154 }
1155 return s, nil
1156 }
1157
1158 func TestAuthResponseCode(t *testing.T) {
1159 type args struct {
1160 authReq op.AuthRequest
1161 authorizer func(*testing.T) op.Authorizer
1162 }
1163 type res struct {
1164 wantCode int
1165 wantLocationHeader string
1166 wantCacheControlHeader string
1167 wantBody string
1168 }
1169 tests := []struct {
1170 name string
1171 args args
1172 res res
1173 }{
1174 {
1175 name: "create code error",
1176 args: args{
1177 authReq: &storage.AuthRequest{
1178 ID: "id1",
1179 TransferState: "state1",
1180 },
1181 authorizer: func(t *testing.T) op.Authorizer {
1182 ctrl := gomock.NewController(t)
1183 storage := mock.NewMockStorage(ctrl)
1184
1185 authorizer := mock.NewMockAuthorizer(ctrl)
1186 authorizer.EXPECT().Storage().Return(storage)
1187 authorizer.EXPECT().Crypto().Return(&mockCrypto{
1188 returnErr: io.ErrClosedPipe,
1189 })
1190 return authorizer
1191 },
1192 },
1193 res: res{
1194 wantCode: http.StatusBadRequest,
1195 wantBody: "io: read/write on closed pipe\n",
1196 },
1197 },
1198 {
1199 name: "success with state",
1200 args: args{
1201 authReq: &storage.AuthRequest{
1202 ID: "id1",
1203 TransferState: "state1",
1204 },
1205 authorizer: func(t *testing.T) op.Authorizer {
1206 ctrl := gomock.NewController(t)
1207 storage := mock.NewMockStorage(ctrl)
1208 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1209
1210 authorizer := mock.NewMockAuthorizer(ctrl)
1211 authorizer.EXPECT().Storage().Return(storage)
1212 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1213 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1214 return authorizer
1215 },
1216 },
1217 res: res{
1218 wantCode: http.StatusFound,
1219 wantLocationHeader: "/auth/callback/?code=id1&state=state1",
1220 wantBody: "",
1221 },
1222 },
1223 {
1224 name: "success with state and session_state",
1225 args: args{
1226 authReq: &storage.AuthRequestWithSessionState{
1227 AuthRequest: &storage.AuthRequest{
1228 ID: "id1",
1229 TransferState: "state1",
1230 },
1231 SessionState: "session_state1",
1232 },
1233 authorizer: func(t *testing.T) op.Authorizer {
1234 ctrl := gomock.NewController(t)
1235 storage := mock.NewMockStorage(ctrl)
1236 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1237
1238 authorizer := mock.NewMockAuthorizer(ctrl)
1239 authorizer.EXPECT().Storage().Return(storage)
1240 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1241 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1242 return authorizer
1243 },
1244 },
1245 res: res{
1246 wantCode: http.StatusFound,
1247 wantLocationHeader: "/auth/callback/?code=id1&session_state=session_state1&state=state1",
1248 wantBody: "",
1249 },
1250 },
1251 {
1252 name: "success without state", // reproduce issue #415
1253 args: args{
1254 authReq: &storage.AuthRequest{
1255 ID: "id1",
1256 TransferState: "",
1257 },
1258 authorizer: func(t *testing.T) op.Authorizer {
1259 ctrl := gomock.NewController(t)
1260 storage := mock.NewMockStorage(ctrl)
1261 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1262
1263 authorizer := mock.NewMockAuthorizer(ctrl)
1264 authorizer.EXPECT().Storage().Return(storage)
1265 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1266 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1267 return authorizer
1268 },
1269 },
1270 res: res{
1271 wantCode: http.StatusFound,
1272 wantLocationHeader: "/auth/callback/?code=id1",
1273 wantBody: "",
1274 },
1275 },
1276 {
1277 name: "success form_post",
1278 args: args{
1279 authReq: &storage.AuthRequest{
1280 ID: "id1",
1281 CallbackURI: "https://example.com/callback",
1282 TransferState: "state1",
1283 ResponseMode: "form_post",
1284 },
1285 authorizer: func(t *testing.T) op.Authorizer {
1286 ctrl := gomock.NewController(t)
1287 storage := mock.NewMockStorage(ctrl)
1288 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1289
1290 authorizer := mock.NewMockAuthorizer(ctrl)
1291 authorizer.EXPECT().Storage().Return(storage)
1292 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1293 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1294 return authorizer
1295 },
1296 },
1297 res: res{
1298 wantCode: http.StatusOK,
1299 wantCacheControlHeader: "no-store",
1300 wantBody: "<!doctype html>\n<html>\n<head><meta charset=\"UTF-8\" /></head>\n<body onload=\"javascript:document.forms[0].submit()\">\n<form method=\"post\" action=\"https://example.com/callback\">\n<input type=\"hidden\" name=\"state\" value=\"state1\"/>\n<input type=\"hidden\" name=\"code\" value=\"id1\" />\n\n\n\n\n</form>\n</body>\n</html>",
1301 },
1302 },
1303 }
1304 for _, tt := range tests {
1305 t.Run(tt.name, func(t *testing.T) {
1306 r := httptest.NewRequest(http.MethodPost, "/auth/callback/", nil)
1307 w := httptest.NewRecorder()
1308 op.AuthResponseCode(w, r, tt.args.authReq, tt.args.authorizer(t))
1309 resp := w.Result()
1310 defer resp.Body.Close()
1311 assert.Equal(t, tt.res.wantCode, resp.StatusCode)
1312 assert.Equal(t, tt.res.wantLocationHeader, resp.Header.Get("Location"))
1313 assert.Equal(t, tt.res.wantCacheControlHeader, resp.Header.Get("Cache-Control"))
1314 body, err := io.ReadAll(resp.Body)
1315 require.NoError(t, err)
1316 assert.Equal(t, tt.res.wantBody, string(body))
1317 })
1318 }
1319 }
1320
1321 func Test_parseAuthorizeCallbackRequest(t *testing.T) {
1322 tests := []struct {
1323 name string
1324 url string
1325 wantId string
1326 wantErr bool
1327 }{
1328 {
1329 name: "parse error",
1330 url: "/?id;=99",
1331 wantErr: true,
1332 },
1333 {
1334 name: "missing id",
1335 url: "/",
1336 wantErr: true,
1337 },
1338 {
1339 name: "ok",
1340 url: "/?id=99",
1341 wantId: "99",
1342 },
1343 }
1344 for _, tt := range tests {
1345 t.Run(tt.name, func(t *testing.T) {
1346 r := httptest.NewRequest(http.MethodGet, tt.url, nil)
1347 gotId, err := op.ParseAuthorizeCallbackRequest(r)
1348 if tt.wantErr {
1349 assert.Error(t, err)
1350 } else {
1351 require.NoError(t, err)
1352 }
1353 assert.Equal(t, tt.wantId, gotId)
1354 })
1355 }
1356 }
1357
1358 func TestBuildAuthResponseCodeResponsePayload(t *testing.T) {
1359 type args struct {
1360 authReq op.AuthRequest
1361 authorizer func(*testing.T) op.Authorizer
1362 }
1363 type res struct {
1364 wantCode string
1365 wantState string
1366 wantSessionState string
1367 wantErr bool
1368 }
1369 tests := []struct {
1370 name string
1371 args args
1372 res res
1373 }{
1374 {
1375 name: "create code error",
1376 args: args{
1377 authReq: &storage.AuthRequest{
1378 ID: "id1",
1379 },
1380 authorizer: func(t *testing.T) op.Authorizer {
1381 ctrl := gomock.NewController(t)
1382 storage := mock.NewMockStorage(ctrl)
1383
1384 authorizer := mock.NewMockAuthorizer(ctrl)
1385 authorizer.EXPECT().Storage().Return(storage)
1386 authorizer.EXPECT().Crypto().Return(&mockCrypto{
1387 returnErr: io.ErrClosedPipe,
1388 })
1389 return authorizer
1390 },
1391 },
1392 res: res{
1393 wantErr: true,
1394 },
1395 },
1396 {
1397 name: "success with state",
1398 args: args{
1399 authReq: &storage.AuthRequest{
1400 ID: "id1",
1401 TransferState: "state1",
1402 },
1403 authorizer: func(t *testing.T) op.Authorizer {
1404 ctrl := gomock.NewController(t)
1405 storage := mock.NewMockStorage(ctrl)
1406 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1407
1408 authorizer := mock.NewMockAuthorizer(ctrl)
1409 authorizer.EXPECT().Storage().Return(storage)
1410 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1411 return authorizer
1412 },
1413 },
1414 res: res{
1415 wantCode: "id1",
1416 wantState: "state1",
1417 },
1418 },
1419 {
1420 name: "success without state",
1421 args: args{
1422 authReq: &storage.AuthRequest{
1423 ID: "id1",
1424 TransferState: "",
1425 },
1426 authorizer: func(t *testing.T) op.Authorizer {
1427 ctrl := gomock.NewController(t)
1428 storage := mock.NewMockStorage(ctrl)
1429 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1430
1431 authorizer := mock.NewMockAuthorizer(ctrl)
1432 authorizer.EXPECT().Storage().Return(storage)
1433 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1434 return authorizer
1435 },
1436 },
1437 res: res{
1438 wantCode: "id1",
1439 wantState: "",
1440 },
1441 },
1442 {
1443 name: "success with session_state",
1444 args: args{
1445 authReq: &storage.AuthRequestWithSessionState{
1446 AuthRequest: &storage.AuthRequest{
1447 ID: "id1",
1448 TransferState: "state1",
1449 },
1450 SessionState: "session_state1",
1451 },
1452 authorizer: func(t *testing.T) op.Authorizer {
1453 ctrl := gomock.NewController(t)
1454 storage := mock.NewMockStorage(ctrl)
1455 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1456
1457 authorizer := mock.NewMockAuthorizer(ctrl)
1458 authorizer.EXPECT().Storage().Return(storage)
1459 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1460 return authorizer
1461 },
1462 },
1463 res: res{
1464 wantCode: "id1",
1465 wantState: "state1",
1466 wantSessionState: "session_state1",
1467 },
1468 },
1469 }
1470 for _, tt := range tests {
1471 t.Run(tt.name, func(t *testing.T) {
1472 got, err := op.BuildAuthResponseCodeResponsePayload(context.Background(), tt.args.authReq, tt.args.authorizer(t))
1473 if tt.res.wantErr {
1474 assert.Error(t, err)
1475 return
1476 }
1477 require.NoError(t, err)
1478 assert.Equal(t, tt.res.wantCode, got.Code)
1479 assert.Equal(t, tt.res.wantState, got.State)
1480 assert.Equal(t, tt.res.wantSessionState, got.SessionState)
1481 })
1482 }
1483 }
1484
1485 func TestValidateAuthReqIDTokenHint(t *testing.T) {
1486 token, _ := tu.ValidIDToken()
1487 tests := []struct {
1488 name string
1489 idTokenHint string
1490 want string
1491 wantErr error
1492 }{
1493 {
1494 name: "empty",
1495 },
1496 {
1497 name: "verify err",
1498 idTokenHint: "foo",
1499 wantErr: oidc.ErrLoginRequired(),
1500 },
1501 {
1502 name: "ok",
1503 idTokenHint: token,
1504 want: tu.ValidSubject,
1505 },
1506 }
1507 for _, tt := range tests {
1508 t.Run(tt.name, func(t *testing.T) {
1509 got, err := op.ValidateAuthReqIDTokenHint(context.Background(), tt.idTokenHint, op.NewIDTokenHintVerifier(tu.ValidIssuer, tu.KeySet{}))
1510 require.ErrorIs(t, err, tt.wantErr)
1511 assert.Equal(t, tt.want, got)
1512 })
1513 }
1514 }
1515
1516 func TestBuildAuthResponseCallbackURL(t *testing.T) {
1517 type args struct {
1518 authReq op.AuthRequest
1519 authorizer func(*testing.T) op.Authorizer
1520 }
1521 type res struct {
1522 wantURL string
1523 wantErr bool
1524 }
1525 tests := []struct {
1526 name string
1527 args args
1528 res res
1529 }{
1530 {
1531 name: "error when generating code response",
1532 args: args{
1533 authReq: &storage.AuthRequest{
1534 ID: "id1",
1535 },
1536 authorizer: func(t *testing.T) op.Authorizer {
1537 ctrl := gomock.NewController(t)
1538 storage := mock.NewMockStorage(ctrl)
1539
1540 authorizer := mock.NewMockAuthorizer(ctrl)
1541 authorizer.EXPECT().Storage().Return(storage)
1542 authorizer.EXPECT().Crypto().Return(&mockCrypto{
1543 returnErr: io.ErrClosedPipe,
1544 })
1545 return authorizer
1546 },
1547 },
1548 res: res{
1549 wantErr: true,
1550 },
1551 },
1552 {
1553 name: "error when generating callback URL",
1554 args: args{
1555 authReq: &storage.AuthRequest{
1556 ID: "id1",
1557 CallbackURI: "://invalid-url",
1558 },
1559 authorizer: func(t *testing.T) op.Authorizer {
1560 ctrl := gomock.NewController(t)
1561 storage := mock.NewMockStorage(ctrl)
1562 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1563
1564 authorizer := mock.NewMockAuthorizer(ctrl)
1565 authorizer.EXPECT().Storage().Return(storage)
1566 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1567 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1568 return authorizer
1569 },
1570 },
1571 res: res{
1572 wantErr: true,
1573 },
1574 },
1575 {
1576 name: "success with state",
1577 args: args{
1578 authReq: &storage.AuthRequest{
1579 ID: "id1",
1580 CallbackURI: "https://example.com/callback",
1581 TransferState: "state1",
1582 },
1583 authorizer: func(t *testing.T) op.Authorizer {
1584 ctrl := gomock.NewController(t)
1585 storage := mock.NewMockStorage(ctrl)
1586 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1587
1588 authorizer := mock.NewMockAuthorizer(ctrl)
1589 authorizer.EXPECT().Storage().Return(storage)
1590 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1591 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1592 return authorizer
1593 },
1594 },
1595 res: res{
1596 wantURL: "https://example.com/callback?code=id1&state=state1",
1597 wantErr: false,
1598 },
1599 },
1600 {
1601 name: "success without state",
1602 args: args{
1603 authReq: &storage.AuthRequest{
1604 ID: "id1",
1605 CallbackURI: "https://example.com/callback",
1606 },
1607 authorizer: func(t *testing.T) op.Authorizer {
1608 ctrl := gomock.NewController(t)
1609 storage := mock.NewMockStorage(ctrl)
1610 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1611
1612 authorizer := mock.NewMockAuthorizer(ctrl)
1613 authorizer.EXPECT().Storage().Return(storage)
1614 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1615 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1616 return authorizer
1617 },
1618 },
1619 res: res{
1620 wantURL: "https://example.com/callback?code=id1",
1621 wantErr: false,
1622 },
1623 },
1624 {
1625 name: "success with session_state",
1626 args: args{
1627 authReq: &storage.AuthRequestWithSessionState{
1628 AuthRequest: &storage.AuthRequest{
1629 ID: "id1",
1630 CallbackURI: "https://example.com/callback",
1631 TransferState: "state1",
1632 },
1633 SessionState: "session_state1",
1634 },
1635 authorizer: func(t *testing.T) op.Authorizer {
1636 ctrl := gomock.NewController(t)
1637 storage := mock.NewMockStorage(ctrl)
1638 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1639
1640 authorizer := mock.NewMockAuthorizer(ctrl)
1641 authorizer.EXPECT().Storage().Return(storage)
1642 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1643 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1644 return authorizer
1645 },
1646 },
1647 res: res{
1648 wantURL: "https://example.com/callback?code=id1&session_state=session_state1&state=state1",
1649 wantErr: false,
1650 },
1651 },
1652 {
1653 name: "success with existing query parameters",
1654 args: args{
1655 authReq: &storage.AuthRequest{
1656 ID: "id1",
1657 CallbackURI: "https://example.com/callback?param=value",
1658 TransferState: "state1",
1659 },
1660 authorizer: func(t *testing.T) op.Authorizer {
1661 ctrl := gomock.NewController(t)
1662 storage := mock.NewMockStorage(ctrl)
1663 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1664
1665 authorizer := mock.NewMockAuthorizer(ctrl)
1666 authorizer.EXPECT().Storage().Return(storage)
1667 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1668 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1669 return authorizer
1670 },
1671 },
1672 res: res{
1673 wantURL: "https://example.com/callback?param=value&code=id1&state=state1",
1674 wantErr: false,
1675 },
1676 },
1677 {
1678 name: "success with fragment response mode",
1679 args: args{
1680 authReq: &storage.AuthRequest{
1681 ID: "id1",
1682 CallbackURI: "https://example.com/callback",
1683 TransferState: "state1",
1684 ResponseMode: "fragment",
1685 },
1686 authorizer: func(t *testing.T) op.Authorizer {
1687 ctrl := gomock.NewController(t)
1688 storage := mock.NewMockStorage(ctrl)
1689 storage.EXPECT().SaveAuthCode(gomock.Any(), "id1", "id1")
1690
1691 authorizer := mock.NewMockAuthorizer(ctrl)
1692 authorizer.EXPECT().Storage().Return(storage)
1693 authorizer.EXPECT().Crypto().Return(&mockCrypto{})
1694 authorizer.EXPECT().Encoder().Return(schema.NewEncoder())
1695 return authorizer
1696 },
1697 },
1698 res: res{
1699 wantURL: "https://example.com/callback#code=id1&state=state1",
1700 wantErr: false,
1701 },
1702 },
1703 }
1704 for _, tt := range tests {
1705 t.Run(tt.name, func(t *testing.T) {
1706 got, err := op.BuildAuthResponseCallbackURL(context.Background(), tt.args.authReq, tt.args.authorizer(t))
1707 if tt.res.wantErr {
1708 assert.Error(t, err)
1709 return
1710 }
1711 require.NoError(t, err)
1712
1713 if tt.res.wantURL != "" {
1714 // Parse the URLs to compare components instead of direct string comparison
1715 expectedURL, err := url.Parse(tt.res.wantURL)
1716 require.NoError(t, err)
1717 actualURL, err := url.Parse(got)
1718 require.NoError(t, err)
1719
1720 // Compare the base parts (scheme, host, path)
1721 assert.Equal(t, expectedURL.Scheme, actualURL.Scheme)
1722 assert.Equal(t, expectedURL.Host, actualURL.Host)
1723 assert.Equal(t, expectedURL.Path, actualURL.Path)
1724
1725 // Compare the fragment if any
1726 assert.Equal(t, expectedURL.Fragment, actualURL.Fragment)
1727
1728 // For query parameters, compare them independently of order
1729 expectedQuery := expectedURL.Query()
1730 actualQuery := actualURL.Query()
1731
1732 assert.Equal(t, len(expectedQuery), len(actualQuery), "Query parameter count does not match")
1733
1734 for key, expectedValues := range expectedQuery {
1735 actualValues, exists := actualQuery[key]
1736 assert.True(t, exists, "Expected query parameter %s not found", key)
1737 assert.ElementsMatch(t, expectedValues, actualValues, "Values for parameter %s don't match", key)
1738 }
1739 }
1740 })
1741 }
1742 }