Debian Codegraph @

tests/apps/idp/oidc/test_tokens.py

raw
1 from datetime import timedelta
2 from http import HTTPStatus
3 from unittest.mock import ANY
4
5 from django.urls import reverse
6 from django.utils import timezone
7
8 import pytest
9
10 from allauth.idp.oidc.models import Token
11
12
13 def test_userinfo_bad_token(client, oidc_client, user):
14 # Pass along ID token as hint
15 resp = client.get(reverse("idp:oidc:userinfo"))
16 assert resp.status_code == HTTPStatus.UNAUTHORIZED
17 assert resp.json() == {
18 "error": "invalid_token",
19 "error_description": "The access token provided is expired, revoked, malformed, or invalid for other reasons.",
20 }
21
22
23 def test_revoke_access_token(
24 client, oidc_client, oidc_client_secret, user, access_token_factory
25 ):
26 token, instance = access_token_factory(oidc_client, user)
27 _, instance_to_keep = access_token_factory(oidc_client, user)
28 resp = client.post(
29 reverse("idp:oidc:revoke"),
30 data={
31 "client_id": oidc_client.id,
32 "client_secret": oidc_client_secret,
33 "token": token,
34 },
35 )
36 assert resp.status_code == HTTPStatus.OK
37 assert not Token.objects.filter(pk=instance.pk).exists()
38 assert Token.objects.filter(pk=instance_to_keep.pk).exists()
39
40
41 @pytest.mark.parametrize(
42 "resources",
43 [
44 [],
45 ["https://api.example.com/a"],
46 ["https://api.example.com/a", "https://api.example.com/b"],
47 ],
48 )
49 @pytest.mark.parametrize("rotate_refresh_token", [False, True])
50 @pytest.mark.parametrize("scopes", [("openid",), ("openid", "email")])
51 def test_refresh_token(
52 db,
53 client,
54 oidc_client,
55 oidc_client_secret,
56 user,
57 refresh_token_factory,
58 settings,
59 rotate_refresh_token,
60 scopes,
61 resources,
62 ):
63 settings.IDP_OIDC_ROTATE_REFRESH_TOKEN = rotate_refresh_token
64 rt, rt_instance = refresh_token_factory(
65 user=user, client=oidc_client, scopes=scopes
66 )
67 rt_instance.set_scope_email("[email protected]")
68 rt_instance.save()
69 data = {
70 "refresh_token": rt,
71 "grant_type": "refresh_token",
72 "client_id": oidc_client.id,
73 "client_secret": oidc_client_secret,
74 }
75 if resources:
76 data["resource"] = resources
77 resp = client.post(reverse("idp:oidc:token"), data)
78
79 assert resp.status_code == HTTPStatus.OK
80 data = resp.json()
81 new_rt_instance = Token.objects.lookup(
82 Token.Type.REFRESH_TOKEN, data["refresh_token"]
83 )
84 if rotate_refresh_token:
85 assert data["refresh_token"] != rt
86 assert new_rt_instance.pk != rt_instance.pk
87 else:
88 assert data["refresh_token"] == rt
89 assert Token.objects.filter(type=Token.Type.REFRESH_TOKEN).count() == 1
90 token = Token.objects.lookup(Token.Type.ACCESS_TOKEN, data["access_token"])
91 assert set(token.get_resources()) == set(resources)
92 assert token.get_scope_email() == ("[email protected]" if "email" in scopes else None)
93 return
94 assert data == {
95 "access_token": ANY,
96 "expires_in": 3600,
97 "refresh_token": ANY,
98 "scope": "openid profile",
99 "token_type": "Bearer",
100 }
101
102
103 @pytest.mark.parametrize("rotate_refresh_token", [False, True])
104 @pytest.mark.parametrize("refresh_token_expires_in", [None, 3600])
105 def test_refresh_token_expiry(
106 db,
107 client,
108 oidc_client,
109 oidc_client_secret,
110 user,
111 refresh_token_factory,
112 settings,
113 rotate_refresh_token,
114 refresh_token_expires_in,
115 ):
116 settings.IDP_OIDC_ROTATE_REFRESH_TOKEN = rotate_refresh_token
117 settings.IDP_OIDC_REFRESH_TOKEN_EXPIRES_IN = refresh_token_expires_in
118 rt, rt_instance = refresh_token_factory(user=user, client=oidc_client)
119 if refresh_token_expires_in is None:
120 # Tokens issued while expiry is disabled do not expire.
121 rt_instance.expires_at = None
122 rt_instance.save()
123 resp = client.post(
124 reverse("idp:oidc:token"),
125 {
126 "refresh_token": rt,
127 "grant_type": "refresh_token",
128 "client_id": oidc_client.id,
129 "client_secret": oidc_client_secret,
130 },
131 )
132 assert resp.status_code == HTTPStatus.OK
133 data = resp.json()
134 new_rt = Token.objects.lookup(Token.Type.REFRESH_TOKEN, data["refresh_token"])
135 if rotate_refresh_token:
136 assert new_rt.pk != rt_instance.pk
137 if refresh_token_expires_in:
138 # Rotation mints a fresh token carrying a full expiry window
139 # (sliding window), exposed as ``refresh_expires_in``.
140 expected = timezone.now() + timedelta(seconds=refresh_token_expires_in)
141 assert abs((new_rt.expires_at - expected).total_seconds()) < 30
142 assert abs(data["refresh_expires_in"] - refresh_token_expires_in) < 30
143 else:
144 assert new_rt.expires_at is None
145 assert "refresh_expires_in" not in data
146 else:
147 # The refresh token is reused as is: its expiry is not extended, and
148 # ``refresh_expires_in`` reflects the remaining lifetime (the factory
149 # issues tokens that expire in 60 seconds).
150 assert new_rt.pk == rt_instance.pk
151 assert new_rt.expires_at == rt_instance.expires_at
152 if refresh_token_expires_in:
153 assert 0 < data["refresh_expires_in"] <= 60
154 else:
155 assert "refresh_expires_in" not in data
156
157
158 def test_refresh_token_reuse_keeps_legacy_token_unexpiring(
159 db, client, oidc_client, oidc_client_secret, user, refresh_token_factory, settings
160 ):
161 # Tokens issued before ``REFRESH_TOKEN_EXPIRES_IN`` was enabled are not
162 # retroactively expired when rotation is off: the token is reused as is.
163 settings.IDP_OIDC_ROTATE_REFRESH_TOKEN = False
164 settings.IDP_OIDC_REFRESH_TOKEN_EXPIRES_IN = 3600
165 rt, rt_instance = refresh_token_factory(user=user, client=oidc_client)
166 rt_instance.expires_at = None
167 rt_instance.save()
168 resp = client.post(
169 reverse("idp:oidc:token"),
170 {
171 "refresh_token": rt,
172 "grant_type": "refresh_token",
173 "client_id": oidc_client.id,
174 "client_secret": oidc_client_secret,
175 },
176 )
177 assert resp.status_code == HTTPStatus.OK
178 data = resp.json()
179 assert data["refresh_token"] == rt
180 rt_instance.refresh_from_db()
181 assert rt_instance.expires_at is None
182 assert "refresh_expires_in" not in data
183
184
185 def test_refresh_token_expired(
186 db, client, oidc_client, oidc_client_secret, user, refresh_token_factory
187 ):
188 rt, rt_instance = refresh_token_factory(user=user, client=oidc_client)
189 rt_instance.expires_at = timezone.now() - timedelta(seconds=1)
190 rt_instance.save()
191 resp = client.post(
192 reverse("idp:oidc:token"),
193 {
194 "refresh_token": rt,
195 "grant_type": "refresh_token",
196 "client_id": oidc_client.id,
197 "client_secret": oidc_client_secret,
198 },
199 )
200 assert resp.status_code == HTTPStatus.BAD_REQUEST
201 assert resp.json()["error"] == "invalid_grant"
202
203
204 def test_revoke_refresh_token(
205 db, client, oidc_client, oidc_client_secret, user, refresh_token_factory
206 ):
207 token_value, token_instance = refresh_token_factory(user=user, client=oidc_client)
208 resp = client.post(
209 reverse("idp:oidc:revoke"),
210 {
211 "token": token_value,
212 "client_id": oidc_client.id,
213 "client_secret": oidc_client_secret,
214 },
215 )
216 assert resp.status_code == HTTPStatus.OK
217 assert resp.content == b""
218 assert not Token.objects.filter(pk=token_instance.pk).exists()
219
220
221 def test_revoke_refresh_token_with_wrong_type_hint(
222 db, client, oidc_client, oidc_client_secret, user, refresh_token_factory
223 ):
224 """A wrong token_type_hint does not revoke when no matching token type exists."""
225 token_value, token_instance = refresh_token_factory(user=user, client=oidc_client)
226 resp = client.post(
227 reverse("idp:oidc:revoke"),
228 {
229 "token": token_value,
230 # Wrong hint on purpose: the token is a refresh token.
231 "token_type_hint": "access_token",
232 "client_id": oidc_client.id,
233 "client_secret": oidc_client_secret,
234 },
235 )
236 assert resp.status_code == HTTPStatus.OK
237 assert Token.objects.filter(pk=token_instance.pk).exists()
238
239
240 @pytest.mark.parametrize(
241 "auth_resources,token_resources,success",
242 [
243 ([], ["https://api.example.com/a"], True),
244 (["https://api.example.com"], ["https://api.example.com/a"], True),
245 (["https://api.example.org"], ["https://api.example.com/a"], False),
246 (
247 ["https://api.example.org", "https://api.example.com"],
248 ["https://api.example.com/a"],
249 True,
250 ),
251 (["https://api.example.com/a"], ["https://api.example.com/b"], False),
252 ],
253 )
254 def test_refresh_resource_vs_subresource(
255 db,
256 client,
257 oidc_client,
258 oidc_client_secret,
259 user,
260 refresh_token_factory,
261 settings,
262 auth_resources,
263 token_resources,
264 success,
265 ):
266 scopes = ["openid"]
267 rt, rt_instance = refresh_token_factory(
268 user=user, client=oidc_client, scopes=scopes
269 )
270 rt_instance.set_scope_email("[email protected]")
271 rt_instance.set_resources(auth_resources)
272 rt_instance.save()
273 data = {
274 "refresh_token": rt,
275 "grant_type": "refresh_token",
276 "client_id": oidc_client.id,
277 "client_secret": oidc_client_secret,
278 }
279 if token_resources:
280 data["resource"] = token_resources
281 resp = client.post(reverse("idp:oidc:token"), data)
282
283 if success:
284 assert resp.status_code == HTTPStatus.OK
285 data = resp.json()
286 refresh_token = Token.objects.lookup(
287 Token.Type.REFRESH_TOKEN, data["refresh_token"]
288 )
289 access_token = Token.objects.lookup(
290 Token.Type.ACCESS_TOKEN, data["access_token"]
291 )
292 assert set(refresh_token.get_resources()) == set(auth_resources)
293 assert set(access_token.get_resources()) == set(token_resources)
294 else:
295 assert resp.status_code == HTTPStatus.BAD_REQUEST
296 data = resp.json()
297 assert data == {
298 "error": "invalid_target",
299 "error_description": "The requested resource is invalid, missing, unknown, or malformed.",
300 }