Debian Codegraph @

tests/apps/idp/oidc/test_authorization.py

raw
1 from datetime import timedelta
2 from http import HTTPStatus
3 from unittest.mock import ANY
4 from urllib.parse import parse_qs, urlparse
5
6 from django.test import Client
7 from django.urls import reverse
8 from django.utils import timezone
9 from django.utils.http import urlencode
10
11 import jwt
12 import pytest
13 from pytest_django.asserts import assertTemplateUsed
14
15 from allauth.account.models import EmailAddress
16 from allauth.idp.oidc.models import Token
17 from allauth.socialaccount.providers.oauth2.utils import generate_code_challenge
18
19
20 def test_cancel_authorization(auth_client, oidc_client):
21 redirect_uri = oidc_client.get_redirect_uris()[0]
22 resp = auth_client.get(
23 reverse("idp:oidc:authorization")
24 + "?"
25 + urlencode(
26 {
27 "client_id": oidc_client.id,
28 "response_type": "code",
29 "redirect_uri": redirect_uri,
30 }
31 )
32 )
33 assert resp.status_code == HTTPStatus.OK
34 assertTemplateUsed(resp, "idp/oidc/authorization_form.html")
35 resp = auth_client.post(
36 reverse("idp:oidc:authorization"),
37 {
38 "request": resp.context["form"]["request"].value(),
39 },
40 )
41 assert resp.status_code == HTTPStatus.FOUND
42 assert resp["location"] == f"{redirect_uri}?error=access_denied"
43
44
45 @pytest.mark.parametrize(
46 "access_token_format,scopes,has_secondary_email,choose_secondary_email,resources",
47 [
48 ("opaque", ("openid", "profile", "email"), False, False, []),
49 (
50 "opaque",
51 ("openid", "profile", "email"),
52 False,
53 False,
54 ["https://api.example.com/a"],
55 ),
56 (
57 "opaque",
58 ("openid", "profile", "email"),
59 False,
60 False,
61 ["https://api.example.com/a", "https://api.example.com/b"],
62 ),
63 ("opaque", ("openid", "profile", "email"), True, False, []),
64 ("opaque", ("openid", "profile", "email"), True, True, []),
65 ("opaque", ("openid", "profile"), False, False, []),
66 ("opaque", ("openid",), False, False, []),
67 ("jwt", ("openid",), False, False, []),
68 (
69 "jwt",
70 ("openid",),
71 False,
72 False,
73 ["https://api.example.com/a"],
74 ),
75 (
76 "jwt",
77 ("openid",),
78 False,
79 False,
80 ["https://api.example.com/a", "https://api.example.com/b"],
81 ),
82 ],
83 )
84 def test_authorization_code_flow(
85 auth_client,
86 user,
87 oidc_client,
88 oidc_client_secret,
89 enable_cache,
90 scopes,
91 has_secondary_email,
92 choose_secondary_email,
93 email_factory,
94 settings,
95 access_token_format,
96 resources,
97 ):
98 settings.IDP_OIDC_ACCESS_TOKEN_FORMAT = access_token_format
99 secondary_email = email_factory()
100 EmailAddress.objects.create(
101 user=user,
102 email=secondary_email,
103 primary=False,
104 verified=True,
105 )
106 redirect_uri = oidc_client.get_redirect_uris()[0]
107 resp = auth_client.get(
108 reverse("idp:oidc:authorization")
109 + "?"
110 + urlencode(
111 {
112 "client_id": oidc_client.id,
113 "redirect_uri": redirect_uri,
114 "response_type": "code",
115 "scope": " ".join(scopes),
116 "nonce": "some-nonce",
117 "state": "some-state",
118 "resource": resources,
119 },
120 doseq=True,
121 )
122 )
123 assert resp.status_code == HTTPStatus.OK
124 assertTemplateUsed(resp, "idp/oidc/authorization_form.html")
125 post_data = {
126 "scopes": scopes,
127 "action": "grant",
128 "request": resp.context["form"]["request"].value(),
129 }
130 expected_email = secondary_email if choose_secondary_email else user.email
131 if has_secondary_email and "email" in scopes:
132 post_data["email"] = expected_email
133 resp = auth_client.post(
134 reverse("idp:oidc:authorization"),
135 post_data,
136 )
137 assert resp.status_code == HTTPStatus.FOUND
138 redirected_uri = resp["location"]
139 assert redirected_uri.startswith(redirect_uri)
140 parts = urlparse(redirected_uri)
141 params = parse_qs(parts.query)
142 code = params["code"][0]
143 assert params["state"][0] == "some-state"
144 resp = auth_client.post(
145 reverse("idp:oidc:token"),
146 {
147 "code": code,
148 "grant_type": "authorization_code",
149 "client_id": oidc_client.id,
150 "client_secret": oidc_client_secret,
151 "redirect_uri": redirect_uri,
152 },
153 )
154 assert resp.status_code == HTTPStatus.OK
155 data = resp.json()
156 assert set(data.keys()) == {
157 "access_token",
158 "expires_in",
159 "token_type",
160 "scope",
161 "refresh_token",
162 "id_token",
163 }
164
165 access_token = Token.objects.lookup(Token.Type.ACCESS_TOKEN, data["access_token"])
166 assert set(access_token.get_resources()) == set(resources)
167 assert bool(access_token.get_scope_email()) == bool(
168 "email" in scopes and has_secondary_email and choose_secondary_email
169 )
170
171 # Access token
172 if access_token_format == "jwt":
173 decoded = jwt.decode(data["access_token"], options={"verify_signature": False})
174 expected_decoded = {
175 "client_id": oidc_client.id,
176 "exp": ANY,
177 "iat": ANY,
178 "iss": "http://testserver",
179 "jti": ANY,
180 "scope": " ".join(scopes),
181 "sub": str(user.pk),
182 "token_use": "access",
183 }
184 if resources:
185 expected_decoded["aud"] = resources
186 assert decoded == expected_decoded
187
188 # ID token
189 id_token = data["id_token"]
190 decoded = jwt.decode(id_token, options={"verify_signature": False})
191 assert decoded["sub"] == str(user.pk)
192 assert decoded["nonce"] == "some-nonce"
193 if "email" in scopes:
194 assert decoded["email"] == expected_email
195 else:
196 assert "email" not in decoded
197 if "profile" in scopes:
198 assert decoded["preferred_username"] == user.username
199 else:
200 assert "preferred_username" not in decoded
201
202
203 def test_authorization_code_flow_skip_consent(
204 auth_client, user, oidc_client, oidc_client_secret, enable_cache
205 ):
206 oidc_client.skip_consent = True
207 oidc_client.save()
208 redirect_uri = oidc_client.get_redirect_uris()[0]
209 resp = auth_client.get(
210 reverse("idp:oidc:authorization")
211 + "?"
212 + urlencode(
213 {
214 "client_id": oidc_client.id,
215 "response_type": "code",
216 "scope": "openid profile email",
217 "nonce": "some-nonce",
218 "state": "some-state",
219 "redirect_uri": redirect_uri,
220 }
221 )
222 )
223 assert resp.status_code == HTTPStatus.FOUND
224 redirected_uri = resp["location"]
225 assert redirected_uri.startswith(redirect_uri)
226 parts = urlparse(redirected_uri)
227 params = parse_qs(parts.query)
228 code = params["code"][0]
229 resp = auth_client.post(
230 reverse("idp:oidc:token"),
231 {
232 "code": code,
233 "grant_type": "authorization_code",
234 "client_id": oidc_client.id,
235 "client_secret": oidc_client_secret,
236 "redirect_uri": redirect_uri,
237 },
238 )
239 assert resp.status_code == HTTPStatus.OK
240 data = resp.json()
241 assert set(data.keys()) == {
242 "access_token",
243 "expires_in",
244 "token_type",
245 "scope",
246 "refresh_token",
247 "id_token",
248 }
249
250
251 @pytest.mark.parametrize("refresh_token_expires_in", [None, 3600])
252 def test_authorization_code_flow_refresh_token_expiry(
253 auth_client,
254 oidc_client,
255 oidc_client_secret,
256 enable_cache,
257 settings,
258 refresh_token_expires_in,
259 ):
260 # The initially issued refresh token carries the configured expiry, and
261 # the lifetime is exposed in the token response as ``refresh_expires_in``.
262 settings.IDP_OIDC_REFRESH_TOKEN_EXPIRES_IN = refresh_token_expires_in
263 oidc_client.skip_consent = True
264 oidc_client.save()
265 redirect_uri = oidc_client.get_redirect_uris()[0]
266 resp = auth_client.get(
267 reverse("idp:oidc:authorization")
268 + "?"
269 + urlencode(
270 {
271 "client_id": oidc_client.id,
272 "response_type": "code",
273 "scope": "openid",
274 "nonce": "some-nonce",
275 "state": "some-state",
276 "redirect_uri": redirect_uri,
277 }
278 )
279 )
280 assert resp.status_code == HTTPStatus.FOUND
281 code = parse_qs(urlparse(resp["location"]).query)["code"][0]
282 resp = auth_client.post(
283 reverse("idp:oidc:token"),
284 {
285 "code": code,
286 "grant_type": "authorization_code",
287 "client_id": oidc_client.id,
288 "client_secret": oidc_client_secret,
289 "redirect_uri": redirect_uri,
290 },
291 )
292 assert resp.status_code == HTTPStatus.OK
293 data = resp.json()
294 refresh_token = Token.objects.lookup(
295 Token.Type.REFRESH_TOKEN, data["refresh_token"]
296 )
297 if refresh_token_expires_in:
298 assert abs(data["refresh_expires_in"] - refresh_token_expires_in) < 30
299 expected = timezone.now() + timedelta(seconds=refresh_token_expires_in)
300 assert abs((refresh_token.expires_at - expected).total_seconds()) < 30
301 else:
302 assert "refresh_expires_in" not in data
303 assert refresh_token.expires_at is None
304
305
306 def test_authorization_id_token_hint_match(
307 user, id_token_factory, oidc_client, auth_client, user_factory
308 ):
309 redirect_uri = oidc_client.get_redirect_uris()[0]
310 # Pass along ID token as hint
311 resp = auth_client.get(
312 reverse("idp:oidc:authorization")
313 + "?"
314 + urlencode(
315 {
316 "client_id": oidc_client.id,
317 "id_token_hint": id_token_factory(oidc_client, user),
318 "response_type": "code",
319 "scope": "openid",
320 "nonce": "some-nonce",
321 "state": "some-state",
322 "redirect_uri": redirect_uri,
323 }
324 )
325 )
326 assert resp.status_code == HTTPStatus.OK
327
328
329 def test_authorization_id_token_hint_mismatch(
330 user, id_token_factory, oidc_client, auth_client, user_factory
331 ):
332 redirect_uri = oidc_client.get_redirect_uris()[0]
333 # Pass along ID token as hint
334 resp = auth_client.get(
335 reverse("idp:oidc:authorization")
336 + "?"
337 + urlencode(
338 {
339 "client_id": oidc_client.id,
340 "id_token_hint": id_token_factory(oidc_client, user_factory()),
341 "response_type": "code",
342 "redirect_uri": redirect_uri,
343 "scope": "openid",
344 "nonce": "some-nonce",
345 "state": "some-state",
346 }
347 )
348 )
349 assert resp.status_code == HTTPStatus.FOUND
350 parts = urlparse(resp["location"])
351 params = parse_qs(parts.query)
352 assert params["error"] == ["login_required"]
353 assert params["error_description"] == [
354 "Session user does not match client supplied user."
355 ]
356
357
358 def test_authorization_post_redirects_to_get(auth_client):
359 payload = {
360 "client_id": "c123",
361 "response_type": "code",
362 "scope": "openid",
363 "nonce": "some-nonce",
364 "state": "some-state",
365 }
366 resp = auth_client.post(reverse("idp:oidc:authorization"), data=payload)
367 assert resp.status_code == HTTPStatus.FOUND
368 assert resp["location"] == reverse("idp:oidc:authorization") + "?" + urlencode(
369 payload
370 )
371
372
373 def test_authorization_post_redirects_anon_to_get(db, client):
374 payload = {
375 "client_id": "c123",
376 "response_type": "code",
377 "scope": "openid",
378 "nonce": "some-nonce",
379 "state": "some-state",
380 }
381 resp = client.post(reverse("idp:oidc:authorization"), data=payload, follow=True)
382 assert resp.status_code == HTTPStatus.OK
383 url = f"{reverse('idp:oidc:authorization')}?{urlencode(payload)}"
384 assert resp.redirect_chain == [
385 (url, HTTPStatus.FOUND),
386 (
387 reverse("account_login")
388 + "?"
389 + urlencode({"next": url}).replace("%2F", "/"),
390 HTTPStatus.FOUND,
391 ),
392 ]
393
394
395 def test_authorization_post_is_csrf_protected(user):
396 client = Client(enforce_csrf_checks=True)
397 client.force_login(user)
398 payload = {
399 "request": "dummy",
400 "scopes": "openid",
401 }
402 resp = client.post(reverse("idp:oidc:authorization"), data=payload)
403 assert resp.status_code == HTTPStatus.FORBIDDEN
404 assert b"CSRF Failed" in resp.content
405
406
407 @pytest.mark.parametrize("valid_code_verifier", [False, True])
408 def test_authorization_code_flow_with_pkce(
409 auth_client,
410 user,
411 oidc_client,
412 enable_cache,
413 valid_code_verifier,
414 ):
415 oidc_client.type = oidc_client.Type.PUBLIC
416 oidc_client.save()
417 redirect_uri = oidc_client.get_redirect_uris()[0]
418 scopes = ["openid", "profile", "email"]
419 pkce = generate_code_challenge()
420 resp = auth_client.get(
421 reverse("idp:oidc:authorization")
422 + "?"
423 + urlencode(
424 {
425 "client_id": oidc_client.id,
426 "redirect_uri": redirect_uri,
427 "response_type": "code",
428 "scope": " ".join(scopes),
429 "nonce": "some-nonce",
430 "state": "some-state",
431 "code_challenge": pkce["code_challenge"],
432 "code_challenge_method": pkce["code_challenge_method"],
433 }
434 )
435 )
436 assert resp.status_code == HTTPStatus.OK
437 assertTemplateUsed(resp, "idp/oidc/authorization_form.html")
438 resp = auth_client.post(
439 reverse("idp:oidc:authorization"),
440 {
441 "scopes": scopes,
442 "action": "grant",
443 "request": resp.context["form"]["request"].value(),
444 },
445 )
446 assert resp.status_code == HTTPStatus.FOUND
447 redirected_uri = resp["location"]
448 assert redirected_uri.startswith(redirect_uri)
449 parts = urlparse(redirected_uri)
450 params = parse_qs(parts.query)
451 code = params["code"][0]
452 assert params["state"][0] == "some-state"
453 resp = auth_client.post(
454 reverse("idp:oidc:token"),
455 {
456 "grant_type": "authorization_code",
457 "code": code,
458 "client_id": oidc_client.id,
459 "redirect_uri": redirect_uri,
460 "state": "some-state",
461 "code_verifier": pkce["code_verifier"] if valid_code_verifier else "WRONG",
462 },
463 )
464 if not valid_code_verifier:
465 assert resp.status_code == HTTPStatus.BAD_REQUEST
466 return
467
468 assert resp.status_code == HTTPStatus.OK
469 data = resp.json()
470 assert set(data.keys()) == {
471 "access_token",
472 "expires_in",
473 "id_token",
474 "token_type",
475 "scope",
476 "refresh_token",
477 }
478
479
480 @pytest.mark.parametrize("client_fixture", ["auth_client", "client"])
481 @pytest.mark.parametrize(
482 "prompt,next_prompt", [("login", None), ("login consent", "consent")]
483 )
484 def test_redirect_to_login_with_prompt_login(
485 request, client_fixture, oidc_client, prompt, next_prompt
486 ):
487 client = request.getfixturevalue(client_fixture)
488 redirect_uri = oidc_client.get_redirect_uris()[0]
489 resp = client.get(
490 reverse("idp:oidc:authorization")
491 + "?"
492 + urlencode(
493 {
494 "client_id": oidc_client.id,
495 "response_type": "code",
496 "redirect_uri": redirect_uri,
497 "prompt": prompt,
498 }
499 )
500 )
501 assert resp.status_code == HTTPStatus.FOUND
502 parts = urlparse(resp["location"])
503 assert parts.path == reverse(
504 "account_login" if client_fixture == "client" else "account_reauthenticate"
505 )
506 params = parse_qs(parts.query)
507 params = parse_qs(urlparse(params["next"][0]).query)
508 if next_prompt:
509 assert params["prompt"][0] == next_prompt
510 else:
511 assert "prompt" not in params
512
513
514 @pytest.mark.parametrize(
515 "client_fixture,scope,error",
516 [
517 ("auth_client", "openid", None),
518 ("auth_client", "openid profile", "consent_required"),
519 ("client", "openid", "login_required"),
520 ],
521 )
522 def test_prompt_none(
523 request,
524 client_fixture,
525 scope,
526 error,
527 oidc_client,
528 user,
529 access_token_factory,
530 ):
531 access_token_factory(oidc_client, user, scopes=["openid"])
532 client = request.getfixturevalue(client_fixture)
533 redirect_uri = oidc_client.get_redirect_uris()[0]
534 resp = client.get(
535 reverse("idp:oidc:authorization")
536 + "?"
537 + urlencode(
538 {
539 "client_id": oidc_client.id,
540 "response_type": "code",
541 "scope": scope,
542 "redirect_uri": redirect_uri,
543 "prompt": "none",
544 }
545 )
546 )
547 assert resp.status_code == HTTPStatus.FOUND
548 if error:
549 assert resp["location"] == f"https://rp.client/callback?error={error}"
550 else:
551 assert resp["location"].startswith("https://rp.client/callback?code=")
552
553
554 def test_authorization_code_invalid_with_resource(
555 auth_client,
556 user,
557 oidc_client,
558 oidc_client_secret,
559 enable_cache,
560 ):
561 redirect_uri = oidc_client.get_redirect_uris()[0]
562 resp = auth_client.get(
563 reverse("idp:oidc:authorization")
564 + "?"
565 + urlencode(
566 {
567 "client_id": oidc_client.id,
568 "redirect_uri": redirect_uri,
569 "response_type": "code",
570 "scope": " ".join(["openid"]),
571 "nonce": "some-nonce",
572 "state": "some-state",
573 "resource": ["https://api.example.com", "mailto:[email protected]"],
574 },
575 doseq=True,
576 )
577 )
578 assert resp.status_code == HTTPStatus.OK
579 assertTemplateUsed(resp, "idp/oidc/error.html")
580
581
582 @pytest.mark.parametrize(
583 "granted_resources,requested_resources,success",
584 [
585 ([], ["https://api.example.com/a"], True),
586 (["https://api.example.com"], ["https://api.example.com/a"], True),
587 (["https://api.example.org"], ["https://api.example.com/a"], False),
588 (
589 ["https://api.example.org", "https://api.example.com"],
590 ["https://api.example.com/a"],
591 True,
592 ),
593 (["https://api.example.com/a"], ["https://api.example.com/b"], False),
594 ],
595 )
596 def test_authorization_code_requested_granted_resources(
597 auth_client,
598 user,
599 oidc_client,
600 oidc_client_secret,
601 enable_cache,
602 granted_resources,
603 requested_resources,
604 success,
605 ):
606 redirect_uri = oidc_client.get_redirect_uris()[0]
607 data = {
608 "client_id": oidc_client.id,
609 "redirect_uri": redirect_uri,
610 "response_type": "code",
611 "scope": "openid",
612 "nonce": "some-nonce",
613 "state": "some-state",
614 }
615 if granted_resources:
616 data["resource"] = granted_resources
617 resp = auth_client.get(
618 reverse("idp:oidc:authorization") + "?" + urlencode(data, doseq=True)
619 )
620 assert resp.status_code == HTTPStatus.OK
621 assertTemplateUsed(resp, "idp/oidc/authorization_form.html")
622 post_data = {
623 "scopes": "openid",
624 "action": "grant",
625 "request": resp.context["form"]["request"].value(),
626 }
627 resp = auth_client.post(
628 reverse("idp:oidc:authorization"),
629 post_data,
630 )
631 assert resp.status_code == HTTPStatus.FOUND
632 redirected_uri = resp["location"]
633 assert redirected_uri.startswith(redirect_uri)
634 parts = urlparse(redirected_uri)
635 params = parse_qs(parts.query)
636 code = params["code"][0]
637 assert params["state"][0] == "some-state"
638 data = {
639 "code": code,
640 "grant_type": "authorization_code",
641 "client_id": oidc_client.id,
642 "client_secret": oidc_client_secret,
643 "redirect_uri": redirect_uri,
644 }
645 if requested_resources:
646 data["resource"] = requested_resources
647 resp = auth_client.post(reverse("idp:oidc:token"), data)
648 if success:
649 assert resp.status_code == HTTPStatus.OK
650 data = resp.json()
651 assert set(data.keys()) == {
652 "access_token",
653 "expires_in",
654 "token_type",
655 "scope",
656 "refresh_token",
657 "id_token",
658 }
659
660 access_token = Token.objects.lookup(
661 Token.Type.ACCESS_TOKEN, data["access_token"]
662 )
663 assert set(access_token.get_resources()) == set(requested_resources)
664 else:
665 assert resp.status_code == HTTPStatus.BAD_REQUEST
666 data = resp.json()
667 assert data == {
668 "error": "invalid_target",
669 "error_description": "The requested resource is invalid, missing, unknown, or malformed.",
670 }
671
672
673 @pytest.mark.parametrize("skip_consent", [False, True])
674 @pytest.mark.parametrize("action", ["grant", "deny"])
675 def test_authorization_code_app_redirect_uri(
676 auth_client,
677 user,
678 oidc_client,
679 oidc_client_secret,
680 enable_cache,
681 skip_consent,
682 action,
683 ):
684 redirect_uri = "org.allauth.app://callback"
685 oidc_client.set_redirect_uris([redirect_uri])
686 oidc_client.skip_consent = skip_consent
687 oidc_client.save()
688 resp = auth_client.get(
689 reverse("idp:oidc:authorization")
690 + "?"
691 + urlencode(
692 {
693 "client_id": oidc_client.id,
694 "response_type": "code",
695 "scope": "openid profile email",
696 "nonce": "some-nonce",
697 "state": "some-state",
698 "redirect_uri": redirect_uri,
699 }
700 )
701 )
702 if not skip_consent:
703 assert resp.status_code == HTTPStatus.OK
704 post_data = {
705 "scopes": ["openid"],
706 "action": action,
707 "request": resp.context["form"]["request"].value(),
708 }
709 resp = auth_client.post(
710 reverse("idp:oidc:authorization"),
711 post_data,
712 )
713 if action == "deny":
714 assert (
715 resp["location"]
716 == f"{redirect_uri}?error=access_denied&state=some-state"
717 )
718 return
719
720 assert resp.status_code == HTTPStatus.FOUND
721 redirected_uri = resp["location"]
722 assert redirected_uri.startswith(redirect_uri)
723
724
725 @pytest.mark.parametrize(
726 "client_fixture,scope,error",
727 [
728 ("client", "openid", "login_required"),
729 ("auth_client", "openid profile", "consent_required"),
730 ],
731 )
732 def test_prompt_none_app_redirect_uri(
733 request,
734 client_fixture,
735 scope,
736 error,
737 oidc_client,
738 user,
739 access_token_factory,
740 ):
741 """Errors are redirected to app native redirect URIs as well."""
742 redirect_uri = "org.allauth.app://callback"
743 oidc_client.set_redirect_uris([redirect_uri])
744 oidc_client.save()
745 access_token_factory(oidc_client, user, scopes=["openid"])
746 client = request.getfixturevalue(client_fixture)
747 resp = client.get(
748 reverse("idp:oidc:authorization")
749 + "?"
750 + urlencode(
751 {
752 "client_id": oidc_client.id,
753 "response_type": "code",
754 "scope": scope,
755 "redirect_uri": redirect_uri,
756 "state": "some-state",
757 "prompt": "none",
758 }
759 )
760 )
761 assert resp.status_code == HTTPStatus.FOUND
762 assert resp["location"] == f"{redirect_uri}?error={error}&state=some-state"