Debian Codegraph @

allauth/idp/oidc/internal/oauthlib/request_validator.py

raw
1 from __future__ import annotations
2
3 import uuid
4 from datetime import timedelta
5 from typing import Any
6
7 from django.utils import timezone
8
9 from oauthlib.common import Request
10 from oauthlib.openid import RequestValidator
11
12 from allauth.core import context
13 from allauth.core.internal import httpkit, jwkkit, ratelimit
14 from allauth.core.internal.deferred import jwt
15 from allauth.idp.oidc import app_settings
16 from allauth.idp.oidc.adapter import get_adapter
17 from allauth.idp.oidc.internal.clientkit import (
18 is_origin_allowed,
19 is_redirect_uri_allowed,
20 lookup_client,
21 )
22 from allauth.idp.oidc.internal.oauthlib import authorization_codes
23 from allauth.idp.oidc.internal.oauthlib.utils import (
24 ValidatorContext,
25 get_validator_context,
26 )
27 from allauth.idp.oidc.internal.resources import InvalidTargetError, is_resources_subset
28 from allauth.idp.oidc.internal.tokens import decode_jwt_token, determine_token_type
29 from allauth.idp.oidc.models import Client, Token
30
31
32 class OAuthLibRequestValidator(RequestValidator):
33 def validate_client_id(self, client_id: Any, request: Request) -> bool:
34 if not isinstance(client_id, str):
35 return False
36 client = self._lookup_client(request, client_id)
37 if not client:
38 return False
39 self._use_client(request, client)
40 return True
41
42 def validate_redirect_uri(
43 self, client_id, redirect_uri, request, *args, **kwargs
44 ) -> bool:
45 return is_redirect_uri_allowed(
46 redirect_uri,
47 request.client.get_redirect_uris(),
48 request.client.allow_uri_wildcards,
49 )
50
51 def validate_response_type(
52 self, client_id, response_type, client, request: Request, *args, **kwargs
53 ) -> bool:
54 return response_type in request.client.get_response_types()
55
56 def validate_scopes(
57 self, client_id, scopes, client, request: Request, *args, **kwargs
58 ) -> bool:
59 return set(scopes).issubset(request.client.get_scopes())
60
61 def get_default_scopes(
62 self, client_id, request: Request, *args, **kwargs
63 ) -> list[str]:
64 return request.client.get_default_scopes()
65
66 def save_authorization_code(
67 self, client_id, code, request: Request, *args, **kwargs
68 ) -> None:
69 # WORKAROUND: docstring says:
70 # > To support OIDC, you MUST associate the code with:
71 # > - nonce, if present (``code["nonce"]``)
72 # Yet, nonce is not there, it is in request.nonce.
73 nonce = getattr(request, "nonce", None)
74 if nonce:
75 code = dict(**code, nonce=nonce)
76 # (end WORKAROUND)
77 authorization_codes.create(request.client, code, request)
78
79 def authenticate_client_id(
80 self, client_id, request: Request, *args, **kwargs
81 ) -> bool:
82 """Ensure client_id belong to a non-confidential client."""
83 if (
84 Client.AuthenticationMethod.NONE
85 not in get_validator_context().supported_auth_methods
86 ):
87 return False
88 client = self._lookup_client(request, client_id)
89 if not client or client.type != Client.Type.PUBLIC:
90 return False
91 self._use_client(request, client)
92 return True
93
94 def authenticate_client(self, request: Request, *args, **kwargs) -> bool:
95 ctx = get_validator_context()
96 client_id, client_secret = httpkit.extract_basic_auth(request.headers)
97 if (
98 Client.AuthenticationMethod.CLIENT_SECRET_POST in ctx.supported_auth_methods
99 and not client_id
100 and not client_secret
101 ):
102 client_id = getattr(request, "client_id", None)
103 client_secret = getattr(request, "client_secret", None)
104 if not isinstance(client_id, str):
105 return False
106 if not client_secret and request.grant_type == Client.GrantType.DEVICE_CODE:
107 return self.authenticate_client_id(client_id, request)
108 if not client_secret or not isinstance(client_secret, str):
109 return False
110 client = self._lookup_client(request, client_id)
111 if not client:
112 return False
113 if not client.check_secret(client_secret):
114 return False
115 self._use_client(request, client)
116 return True
117
118 def validate_grant_type(
119 self, client_id, grant_type, client, request: Request, *args, **kwargs
120 ) -> bool:
121 return grant_type in client.get_grant_types()
122
123 def validate_code(
124 self, client_id, code, client, request: Request, *args, **kwargs
125 ) -> bool:
126 return authorization_codes.validate(client_id, code, request)
127
128 def introspect_token(
129 self, token, token_type_hint, request: Request, *args, **kwargs
130 ) -> dict | None:
131 """
132 https://datatracker.ietf.org/doc/html/rfc7662#section-2.1
133 > The protected resource calls the introspection endpoint using an HTTP
134 > POST [RFC7231] request with parameters sent as
135 > "application/x-www-form-urlencoded" data as defined in
136 > [W3C.REC-html5-20141028]. The protected resource sends a parameter
137 > representing the token along with optional parameters representing
138 > additional context that is known by the protected resource to aid the
139 > authorization server in its response.
140
141 > token
142 > REQUIRED. The string value of the token. For access tokens, this
143 > is the "access_token" value returned from the token endpoint
144 > defined in OAuth 2.0 [RFC6749], Section 5.1. For refresh tokens,
145 > this is the "refresh_token" value returned from the token endpoint
146 > as defined in OAuth 2.0 [RFC6749], Section 5.1. Other token types
147 > are outside the scope of this specification.
148
149 > token_type_hint
150 > OPTIONAL. A hint about the type of the token submitted for
151 > introspection. The protected resource MAY pass this parameter to
152 > help the authorization server optimize the token lookup. If the
153 > server is unable to locate the token using the given hint, it MUST
154 > extend its search across all of its supported token types. An
155 > authorization server MAY ignore this parameter, particularly if it
156 > is able to detect the token type automatically. Values for this
157 > field are defined in the "OAuth Token Type Hints" registry defined
158 > in OAuth Token Revocation [RFC7009].
159 """
160 ratelimit.consume(
161 request=context.request,
162 config=app_settings.RATE_LIMITS,
163 action="introspect_client",
164 key=request.client.id,
165 raise_exception=True,
166 )
167 types, fallback_types = determine_token_type(token, token_type_hint)
168 if types is None:
169 return None
170
171 instance = Token.objects.lookup_by_value(types, token)
172 if not instance and fallback_types:
173 instance = Token.objects.lookup_by_value(fallback_types, token)
174 if not instance:
175 return None
176
177 adapter = get_adapter()
178 if instance.user and not instance.user.is_active:
179 return None
180
181 if (
182 not app_settings.INTROSPECTION_CROSS_CLIENT_ALLOWED
183 and instance.client_id != request.client.pk
184 ):
185 return None
186
187 if not adapter.is_introspection_allowed(
188 token=instance,
189 caller_client=request.client,
190 ):
191 """
192 https://datatracker.ietf.org/doc/html/rfc7662#section-2.3
193 > Note that a properly formed and authorized query for an inactive or
194 > otherwise invalid token (or a token the protected resource is not
195 > allowed to know about) is not considered an error response by this
196 > specification. In these cases, the authorization server MUST instead
197 > respond with an introspection response with the "active" field set to
198 > "false" as described in Section 2.2.
199 """
200 return None
201
202 claims = {
203 "iss": adapter.get_issuer(),
204 "iat": int(instance.created_at.timestamp()),
205 "token_type": (
206 "refresh_token"
207 if instance.type == Token.Type.REFRESH_TOKEN
208 else "access_token"
209 ),
210 "scope": " ".join(instance.get_scopes()),
211 }
212 if aud := instance.get_resources():
213 claims["aud"] = aud
214 if instance.expires_at:
215 claims["exp"] = int(instance.expires_at.timestamp())
216 if instance.user and instance.client:
217 claims["sub"] = adapter.get_user_sub(instance.client, instance.user)
218 if instance.client:
219 claims["client_id"] = instance.client.id
220 adapter.populate_introspection_response(response=claims, token=instance)
221 return claims
222
223 def confirm_redirect_uri(
224 self, client_id, code, redirect_uri, client, request: Request, *args, **kwargs
225 ) -> bool:
226 authorization_code = self._lookup_authorization_code(request, client_id, code)
227 if not authorization_code:
228 return False
229 return redirect_uri == authorization_code["redirect_uri"]
230
231 def save_bearer_token(self, token: dict, request: Request, *args, **kwargs) -> None:
232 """
233 https://datatracker.ietf.org/doc/html/rfc6749#section-6
234 > The authorization server MAY issue a new refresh token, in which case
235 > the client MUST discard the old refresh token and replace it with the
236 > new refresh token. The authorization server MAY revoke the old
237 > refresh token after issuing a new refresh token to the client. If a
238 > new refresh token is issued, the refresh token scope MUST be
239 > identical to that of the refresh token included by the client in the
240 > request.
241
242 https://datatracker.ietf.org/doc/html/rfc6749#section-1.5
243 > Refresh tokens are issued to the client by the authorization server and
244 > are used to obtain a new access token when the current access token becomes
245 > invalid or expires, or to obtain additional access tokens with identical or
246 > narrower scope
247 """
248 ctx = get_validator_context()
249 refresh_token = token.get("refresh_token")
250 tokens = []
251 if refresh_token:
252 rt = self._prep_refresh_token(ctx, refresh_token, request)
253 if not rt.pk:
254 tokens.append(rt)
255 if rt.expires_at is not None:
256 # Expose the refresh token lifetime to the client. Not part of
257 # RFC 6749, but ``refresh_expires_in`` is the de-facto convention
258 # (e.g. Keycloak). Omitted when refresh tokens do not expire.
259 token["refresh_expires_in"] = max(
260 0, int((rt.expires_at - timezone.now()).total_seconds())
261 )
262 access_token = self._prep_access_token(ctx, token, request)
263 tokens.append(access_token)
264 for t in tokens:
265 t.set_scopes(request.scopes)
266 if ctx.email:
267 t.set_scope_email(ctx.email)
268 Token.objects.bulk_create(tokens)
269
270 def _prep_access_token(
271 self, ctx: ValidatorContext, token: dict, request: Request
272 ) -> Token:
273 adapter = get_adapter()
274 access_token = Token(
275 client=request.client,
276 user=request.user,
277 type=Token.Type.ACCESS_TOKEN,
278 hash=adapter.hash_token(token["access_token"]),
279 expires_at=timezone.now() + timedelta(seconds=token["expires_in"]),
280 )
281 if resources := ctx.requested_resources:
282 if not is_resources_subset(resources, ctx.granted_resources):
283 raise InvalidTargetError
284 else:
285 resources = ctx.granted_resources
286 if resources:
287 access_token.set_resources(resources)
288 return access_token
289
290 def _prep_refresh_token(
291 self, ctx: ValidatorContext, refresh_token: str, request: Request
292 ) -> Token:
293 adapter = get_adapter()
294 refresh_token_hash = adapter.hash_token(refresh_token)
295 rt: Token | None = ctx.refresh_token
296 if rt:
297 ctx.granted_resources = rt.get_resources()
298 if not ctx.email and "email" in request.scopes:
299 ctx.email = rt.get_scope_email()
300 if (
301 rt
302 and not app_settings.ROTATE_REFRESH_TOKEN
303 and refresh_token_hash == rt.hash
304 ):
305 # We reuse our token.
306 return rt
307
308 resources: list[str] | None
309 if rt:
310 resources = rt.get_resources()
311 # If we have an existing refresh token, drop it, because of:
312 assert (
313 app_settings.ROTATE_REFRESH_TOKEN or refresh_token_hash != rt.hash
314 ) # nosec[assert_used]
315 rt.delete()
316 rt = None
317 else:
318 resources = ctx.granted_resources
319 refresh_expires_in = app_settings.REFRESH_TOKEN_EXPIRES_IN
320 new_rt = Token(
321 client=request.client,
322 user=request.user,
323 type=Token.Type.REFRESH_TOKEN,
324 hash=refresh_token_hash,
325 expires_at=(
326 timezone.now() + timedelta(seconds=refresh_expires_in)
327 if refresh_expires_in
328 else None
329 ),
330 )
331 if resources:
332 new_rt.set_resources(resources)
333 rt = new_rt
334 return rt
335
336 def invalidate_authorization_code(
337 self, client_id, code, request: Request, *args, **kwargs
338 ) -> None:
339 authorization_codes.invalidate(client_id, code)
340
341 def validate_user_match(
342 self, id_token_hint, scopes, claims, request: Request
343 ) -> bool:
344 if not context.request.user:
345 return False
346 sub = None
347 if id_token_hint:
348 payload = decode_jwt_token(
349 id_token_hint,
350 client_id=request.client.id,
351 verify_exp=True,
352 verify_iss=True,
353 )
354 if payload is None:
355 return False
356 sub = payload.get("sub")
357 session_sub = get_adapter().get_user_sub(
358 request.client, context.request.user
359 )
360 if sub != session_sub:
361 return False
362 if claims:
363 sub = claims.get("sub")
364 session_sub = get_adapter().get_user_sub(
365 request.client, context.request.user
366 )
367 if sub != session_sub:
368 return False
369 return True
370
371 def get_authorization_code_scopes(
372 self, client_id, code, redirect_uri, request
373 ) -> list[str]:
374 authorization_code = self._lookup_authorization_code(request, client_id, code)
375 if not authorization_code:
376 return []
377 return authorization_code["scopes"]
378
379 def get_authorization_code_nonce(
380 self, client_id, code, redirect_uri, request
381 ) -> str | None:
382 authorization_code = self._lookup_authorization_code(request, client_id, code)
383 if authorization_code is None:
384 return None
385 return authorization_code["code"].get("nonce")
386
387 def get_code_challenge(self, code, request: Request) -> str | None:
388 ret = None
389 authorization_code = self._lookup_authorization_code(
390 request, request.client_id, code
391 )
392 if authorization_code is None:
393 return None
394 if pkce := authorization_code.get("pkce"):
395 ret = pkce["code_challenge"]
396 return ret
397
398 def get_code_challenge_method(self, code, request: Request) -> str | None:
399 ret = None
400 authorization_code = self._lookup_authorization_code(
401 request, request.client_id, code
402 )
403 if authorization_code is None:
404 return None
405 if pkce := authorization_code.get("pkce"):
406 ret = pkce["code_challenge_method"]
407 return ret
408
409 def is_pkce_required(self, client_id, request: Request) -> bool:
410 client = self._lookup_client(request, client_id)
411 return bool(client and client.type == Client.Type.PUBLIC)
412
413 def finalize_id_token(
414 self, id_token: dict, token: dict, token_handler, request
415 ) -> str:
416 """
417 https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
418 """
419 adapter = get_adapter()
420 id_token["iss"] = adapter.get_issuer()
421 id_token["exp"] = id_token["iat"] + app_settings.ID_TOKEN_EXPIRES_IN
422 id_token["jti"] = uuid.uuid4().hex
423 ctx = get_validator_context()
424 email = ctx.email
425 id_token.update(
426 adapter.get_claims(
427 "id_token", request.user, request.client, request.scopes, email=email
428 )
429 )
430 adapter.populate_id_token(id_token, request.client, request.scopes)
431 jwk_dict, private_key = jwkkit.load_jwk_from_pem(adapter.get_signing_key().pem)
432 return jwt.encode(
433 id_token, private_key, algorithm="RS256", headers={"kid": jwk_dict["kid"]}
434 )
435
436 def validate_bearer_token(self, token, scopes, request: Request) -> bool:
437 if not token:
438 return False
439 if context.request.GET.get("access_token") == token:
440 # Supporting tokens in query params is considered bad practice, yet,
441 # oauthlib supports this. E.g., if access tokens are sent via URI
442 # query parameters, such tokens may leak to log files and the HTTP
443 # 'referer'.
444 return False
445 instance = Token.objects.lookup(Token.Type.ACCESS_TOKEN, token)
446 if not instance:
447 return False
448 if instance.user and not instance.user.is_active:
449 return False
450 granted_scopes = instance.get_scopes()
451 if not set(scopes).issubset(set(granted_scopes)):
452 return False
453 request.user = instance.user
454 if not instance.client:
455 return False
456 ctx = get_validator_context()
457 if (
458 instance.client.type == Client.Type.PUBLIC
459 and Client.AuthenticationMethod.NONE not in ctx.supported_auth_methods
460 ):
461 return False
462 self._use_client(request, instance.client)
463 request.scopes = granted_scopes
464 ctx.access_token = instance
465 request.access_token = token
466 return True
467
468 def revoke_token(self, token, token_type_hint, request, *args, **kwargs) -> None:
469 if token_type_hint == "access_token": # nosec
470 types = [Token.Type.ACCESS_TOKEN]
471 elif token_type_hint == "refresh_token": # nosec
472 types = [Token.Type.REFRESH_TOKEN]
473 else:
474 types = [Token.Type.ACCESS_TOKEN, Token.Type.REFRESH_TOKEN]
475 Token.objects.by_value(token).filter(type__in=types).delete()
476
477 def get_userinfo_claims(self, request: Request) -> dict:
478 access_token = get_validator_context().access_token
479 assert access_token # nosec
480 email = access_token.get_scope_email()
481 return get_adapter().get_claims(
482 "userinfo", request.user, request.client, request.scopes, email=email
483 )
484
485 def get_default_redirect_uri(
486 self, client_id, request: Request, *args, **kwargs
487 ) -> None:
488 # https://openid.net/specs/openid-financial-api-part-1-1_0.html#section-5.2.2
489 # 9. shall require the redirect_uri in the authorization request;
490 # So, don't support a default.
491 return None
492
493 def validate_user(
494 self, username, password, client, request: Request, *args, **kwargs
495 ) -> bool:
496 """
497 Note that this bypasses MFA, which is why the password grant is not
498 recommended and hence disabled. This could work:
499
500 try:
501 user = get_account_adapter().authenticate(
502 context.request, username=username, password=password
503 )
504 except ValidationError:
505 return False
506 else:
507 if not user:
508 return False
509 request.user = user
510 return True
511 """
512 return False
513
514 def validate_refresh_token(
515 self, refresh_token, client, request: Request, *args, **kwargs
516 ) -> bool:
517 token = Token.objects.filter(client=client).lookup(
518 Token.Type.REFRESH_TOKEN, refresh_token
519 )
520 if not token:
521 return False
522 if not token.user or not token.user.is_active:
523 return False
524 request.user = token.user
525 get_validator_context().refresh_token = token
526 return True
527
528 def get_original_scopes(
529 self, refresh_token, request: Request, *args, **kwargs
530 ) -> list[str]:
531 rt = get_validator_context().refresh_token
532 assert rt is not None # nosec
533 return rt.get_scopes()
534
535 def client_authentication_required(self, request: Request, *args, **kwargs) -> bool:
536 """
537 Determine if client authentication is required for current request.
538 """
539 if (
540 Client.AuthenticationMethod.NONE
541 not in get_validator_context().supported_auth_methods
542 ):
543 return True
544 if request.client_id and request.client_secret:
545 return True
546
547 client = self._lookup_client(request, request.client_id)
548 if client and client.type == Client.Type.PUBLIC:
549 return False
550 return super().client_authentication_required(request, *args, **kwargs)
551
552 def _lookup_client(self, request: Request, client_id: str) -> Client | None:
553 """
554 In various places, oauthlib documents:
555
556 Note, while not strictly necessary it can often be very convenient
557 to set request.client to the client object associated with the
558 given client_id.
559
560 It's unclear though that if this is not explicitly stated, and, we still
561 were to set request.client, whether that could have adverse side
562 effects. So, don't assign request.client here.
563 """
564 cache = get_validator_context().clients
565 if client_id in cache:
566 client = cache[client_id]
567 else:
568 client = lookup_client(client_id)
569 cache[client_id] = client
570 return client
571
572 def _use_client(self, request: Request, client: Client) -> None:
573 request.client = client
574 request.client.client_id = client.id
575
576 def _lookup_authorization_code(
577 self, request: Request, client_id: str, code: str
578 ) -> dict | None:
579 cache = get_validator_context().codes
580 key = (client_id, code)
581 if key in cache:
582 authorization_code = cache[key]
583 else:
584 authorization_code = authorization_codes.lookup(client_id, code)
585 cache[key] = authorization_code
586 return authorization_code
587
588 def is_origin_allowed(
589 self, client_id: str, origin: str, request: Request, *args, **kwargs
590 ) -> bool:
591 client = self._lookup_client(request, client_id)
592 return bool(
593 client
594 and is_origin_allowed(
595 origin, client.get_cors_origins(), client.allow_uri_wildcards
596 )
597 )
598
599 def rotate_refresh_token(self, request: Request) -> bool:
600 return app_settings.ROTATE_REFRESH_TOKEN
601
602 def validate_silent_login(self, request: Request) -> bool:
603 if context.request.user.is_authenticated:
604 request.user = context.request.user
605 return True
606 return False
607
608 def validate_silent_authorization(self, request: Request) -> bool:
609 granted_scopes = set()
610 tokens = Token.objects.valid().filter(
611 user=context.request.user,
612 type__in=[Token.Type.REFRESH_TOKEN, Token.Type.ACCESS_TOKEN],
613 )
614 for token in tokens.iterator():
615 granted_scopes.update(token.get_scopes())
616 return set(request.scopes).issubset(granted_scopes)
617
618 def validate_jwt_bearer_token(self, token, scopes, request: Request) -> bool:
619 payload = decode_jwt_token(token, verify_iss=True, verify_exp=True)
620 if not payload:
621 return False
622 token_use = payload.get("token_use")
623 if token_use == "access": # nosec
624 return self._validate_jwt_bearer_access_token(
625 token, scopes, request, payload
626 )
627 return self._validate_jwt_bearer_id_token(token, scopes, request, payload)
628
629 def _validate_jwt_bearer_id_token(self, token, scopes, request, payload) -> bool:
630 if scopes:
631 # We don't have scope for the ID token
632 return False
633 client_id = payload.get("aud")
634 return self.validate_client_id(client_id, request)
635
636 def _validate_jwt_bearer_access_token(
637 self, token, scopes, request, payload
638 ) -> bool:
639 client_id = payload.get("client_id")
640 if not self.validate_client_id(client_id, request):
641 return False
642 return self.validate_bearer_token(token, scopes, request)