Debian Codegraph @

tests/apps/idp/oidc/test_introspection.py

raw
1 import base64
2 import uuid
3 from datetime import timedelta
4 from http import HTTPStatus
5
6 from django.urls import reverse
7 from django.utils import timezone
8
9 import pytest
10 from oauthlib.common import Request
11
12 from allauth.core.context import request_context
13 from allauth.idp.oidc.adapter import get_adapter
14 from allauth.idp.oidc.internal.oauthlib.server import generate_jwt_access_token
15 from allauth.idp.oidc.models import Token
16
17
18 def _basic_auth(client_id: str, secret: str) -> str:
19 raw = f"{client_id}:{secret}".encode("utf-8")
20 return "Basic " + base64.b64encode(raw).decode("ascii")
21
22
23 @pytest.fixture(autouse=True)
24 def introspection_enabled(settings_impacting_urls):
25 with settings_impacting_urls(IDP_OIDC_INTROSPECTION_ENABLED=True):
26 yield
27
28
29 @pytest.fixture
30 def jwt_access_token_factory(settings, rf):
31 """Mint a *JWT*-formatted access token regardless of the parametrized format."""
32
33 def f(client, user, scopes=["openid"]):
34 settings.IDP_OIDC_ACCESS_TOKEN_FORMAT = "jwt"
35 o_request = Request("/")
36 o_request.user = user
37 o_request.client = client
38 o_request.scopes = scopes
39 with request_context(rf.get("/")):
40 token = generate_jwt_access_token(o_request)
41 instance = Token(
42 type=Token.Type.ACCESS_TOKEN,
43 user=user,
44 client=client,
45 hash=get_adapter().hash_token(token),
46 )
47 instance.set_scopes(scopes)
48 instance.save()
49 return token, instance
50
51 return f
52
53
54 @pytest.fixture
55 def opaque_access_token_factory():
56 """Mint an *opaque* access token regardless of the parametrized format."""
57
58 def f(client, user, scopes=["openid"], resources=None, expires_at=None):
59 value = uuid.uuid4().hex
60 instance = Token(
61 type=Token.Type.ACCESS_TOKEN,
62 user=user,
63 client=client,
64 hash=get_adapter().hash_token(value),
65 )
66 instance.set_scopes(scopes)
67 if resources:
68 instance.set_resources(resources)
69 if expires_at:
70 instance.expires_at = expires_at
71 instance.save()
72 return value, instance
73
74 return f
75
76
77 # ---------------------------------------------------------------------------
78 # Caller authentication -- client credentials (client_secret_basic) mode
79 # ---------------------------------------------------------------------------
80
81
82 def test_introspect_client_credentials_basic(
83 client, oidc_client, oidc_client_secret, user, access_token_factory
84 ):
85 """A confidential caller authenticating via Basic auth gets an active result."""
86 token, _ = access_token_factory(oidc_client, user, scopes=["openid"])
87 resp = client.post(
88 reverse("idp:oidc:introspect"),
89 data={"token": token},
90 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
91 )
92 assert resp.status_code == HTTPStatus.OK
93 data = resp.json()
94 assert data["active"] is True
95 assert data["client_id"] == oidc_client.id
96 assert data["iss"] == "http://testserver"
97
98
99 def test_introspect_wrong_client_secret_is_unauthorized(
100 client, oidc_client, oidc_client_secret, user, access_token_factory
101 ):
102 token, _ = access_token_factory(oidc_client, user, scopes=["openid"])
103 resp = client.post(
104 reverse("idp:oidc:introspect"),
105 data={"token": token},
106 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, "wrong-secret"),
107 )
108 assert resp.status_code == HTTPStatus.UNAUTHORIZED
109 assert resp.json()["error"] == "invalid_client"
110
111
112 def test_introspect_client_credentials_post_body(
113 client, oidc_client, oidc_client_secret, user, access_token_factory
114 ):
115 """client_secret_post (credentials in the body) authenticates the caller too.
116
117 Note: ``client_secret_post`` is reachable even though it is not in the
118 view's ``supported_methods`` list -- only the bearer/basic/none paths are
119 gated by that list.
120 """
121 token, _ = access_token_factory(oidc_client, user, scopes=["openid"])
122 resp = client.post(
123 reverse("idp:oidc:introspect"),
124 data={
125 "token": token,
126 "client_id": oidc_client.id,
127 "client_secret": oidc_client_secret,
128 },
129 )
130 assert resp.status_code == HTTPStatus.OK
131 assert resp.json()["active"] is True
132
133
134 # ---------------------------------------------------------------------------
135 # Target token results
136 # ---------------------------------------------------------------------------
137
138
139 def test_introspect_opaque_access_token_claims(
140 client, oidc_client, oidc_client_secret, user, opaque_access_token_factory
141 ):
142 """An *opaque* access token gets a server-constructed RFC 7662 claim set."""
143 expires_at = timezone.now() + timedelta(seconds=300)
144 token, instance = opaque_access_token_factory(
145 oidc_client,
146 user,
147 scopes=["openid", "profile"],
148 resources=["https://api.example.com/a"],
149 expires_at=expires_at,
150 )
151 resp = client.post(
152 reverse("idp:oidc:introspect"),
153 data={"token": token},
154 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
155 )
156 assert resp.status_code == HTTPStatus.OK
157 data = resp.json()
158 assert data["active"] is True
159 assert data["token_type"] == "access_token"
160 assert data["scope"] == "openid profile"
161 assert data["iss"] == "http://testserver"
162 assert data["client_id"] == oidc_client.id
163 assert data["sub"] == get_adapter().get_user_sub(oidc_client, user)
164 assert data["aud"] == ["https://api.example.com/a"]
165 assert data["exp"] == int(instance.expires_at.timestamp())
166 assert data["iat"] == int(instance.created_at.timestamp())
167
168
169 def test_introspect_jwt_access_token_claims(
170 client, oidc_client, oidc_client_secret, user, jwt_access_token_factory
171 ):
172 """
173 An *JWT* access token gets a server-constructed RFC 7662 claim set, matching the *opaque* case.
174 Note: This is different from the token's own JWT claims -- see RFC 7662 section 4, which allows
175 for a different response shape for JWT tokens, but the spec is permissive and allows for
176 the same claim set as opaque tokens too.
177 """
178 token, instance = jwt_access_token_factory(
179 oidc_client, user, scopes=["openid", "profile"]
180 )
181 instance.expires_at = timezone.now() + timedelta(seconds=300)
182 instance.save()
183 resp = client.post(
184 reverse("idp:oidc:introspect"),
185 data={"token": token},
186 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
187 )
188 assert resp.status_code == HTTPStatus.OK
189 data = resp.json()
190 assert data["active"] is True
191 assert data["token_type"] == "access_token"
192 assert data["scope"] == "openid profile"
193 assert data["iss"] == "http://testserver"
194 assert data["client_id"] == oidc_client.id
195 assert data["sub"] == get_adapter().get_user_sub(oidc_client, user)
196 assert data["exp"] == int(instance.expires_at.timestamp())
197
198
199 def test_introspect_active_refresh_token(
200 client, oidc_client, oidc_client_secret, user, refresh_token_factory
201 ):
202 refresh_value, _ = refresh_token_factory(user=user, client=oidc_client)
203 resp = client.post(
204 reverse("idp:oidc:introspect"),
205 data={"token": refresh_value, "token_type_hint": "refresh_token"},
206 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
207 )
208 assert resp.status_code == HTTPStatus.OK
209 data = resp.json()
210 assert data["active"] is True
211 assert data["token_type"] == "refresh_token"
212
213
214 def test_introspect_expired_token_is_inactive(
215 client, oidc_client, oidc_client_secret, user, access_token_factory
216 ):
217 token, instance = access_token_factory(oidc_client, user, scopes=["openid"])
218 instance.expires_at = timezone.now() - timedelta(seconds=60)
219 instance.save()
220 resp = client.post(
221 reverse("idp:oidc:introspect"),
222 data={"token": token},
223 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
224 )
225 assert resp.status_code == HTTPStatus.OK
226 assert resp.json() == {"active": False}
227
228
229 def test_introspect_unknown_token_is_inactive(client, oidc_client, oidc_client_secret):
230 resp = client.post(
231 reverse("idp:oidc:introspect"),
232 data={"token": "does-not-exist"},
233 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
234 )
235 assert resp.status_code == HTTPStatus.OK
236 assert resp.json() == {"active": False}
237
238
239 def test_introspect_token_type_hint_mismatch_falls_back(
240 client, oidc_client, oidc_client_secret, user, refresh_token_factory
241 ):
242 """A wrong token_type_hint still resolves the token via the fallback type."""
243 refresh_value, _ = refresh_token_factory(user=user, client=oidc_client)
244 resp = client.post(
245 reverse("idp:oidc:introspect"),
246 # Wrong hint on purpose: the token is a refresh token.
247 data={"token": refresh_value, "token_type_hint": "access_token"},
248 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
249 )
250 assert resp.status_code == HTTPStatus.OK
251 data = resp.json()
252 assert data["active"] is True
253 assert data["token_type"] == "refresh_token"
254
255
256 # ---------------------------------------------------------------------------
257 # Target token results -- JWT detection branch
258 # ---------------------------------------------------------------------------
259
260
261 def test_introspect_valid_jwt_token(
262 client, oidc_client, oidc_client_secret, user, jwt_access_token_factory
263 ):
264 """A genuine JWT access token is detected and introspected as active."""
265 token, _ = jwt_access_token_factory(oidc_client, user, scopes=["openid"])
266 resp = client.post(
267 reverse("idp:oidc:introspect"),
268 data={"token": token},
269 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
270 )
271 assert resp.status_code == HTTPStatus.OK
272 data = resp.json()
273 assert data["active"] is True
274 assert data["token_type"] == "access_token"
275
276
277 def test_introspect_invalid_jwt_token_is_inactive(
278 client, oidc_client, oidc_client_secret
279 ):
280 """A JWT-shaped but undecodable token resolves to active: false."""
281 # Starts with "ey" and has two dots, so it is treated as a JWT, but the
282 # signature is bogus, so decoding fails -> token-not-active.
283 bogus_jwt = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4In0.not-a-real-signature"
284 resp = client.post(
285 reverse("idp:oidc:introspect"),
286 data={"token": bogus_jwt},
287 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
288 )
289 assert resp.status_code == HTTPStatus.OK
290 assert resp.json() == {"active": False}
291
292
293 # ---------------------------------------------------------------------------
294 # Request validation
295 # ---------------------------------------------------------------------------
296
297
298 def test_introspect_missing_token_is_invalid_request(
299 client, oidc_client, oidc_client_secret
300 ):
301 resp = client.post(
302 reverse("idp:oidc:introspect"),
303 data={},
304 HTTP_AUTHORIZATION=_basic_auth(oidc_client.id, oidc_client_secret),
305 )
306 assert resp.status_code == HTTPStatus.BAD_REQUEST
307 assert resp.json()["error"] == "invalid_request"
308
309
310 @pytest.mark.parametrize("cross_client_allowed", [False, True])
311 def test_introspect_other_client(
312 client,
313 oidc_client,
314 oidc_client_secret,
315 oidc_client_factory,
316 user,
317 opaque_access_token_factory,
318 cross_client_allowed,
319 settings,
320 ):
321 """An *opaque* access token gets a server-constructed RFC 7662 claim set."""
322 settings.IDP_OIDC_INTROSPECTION_CROSS_CLIENT_ALLOWED = cross_client_allowed
323 token, instance = opaque_access_token_factory(
324 oidc_client,
325 user,
326 scopes=["openid", "profile"],
327 resources=["https://api.example.com/a"],
328 )
329 other_oidc_client = oidc_client_factory(secret=oidc_client_secret)
330 resp = client.post(
331 reverse("idp:oidc:introspect"),
332 data={"token": token},
333 HTTP_AUTHORIZATION=_basic_auth(other_oidc_client.id, oidc_client_secret),
334 )
335 assert resp.status_code == HTTPStatus.OK
336 assert resp.json()["active"] == cross_client_allowed