| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import hashlib |
| 4 |
import uuid |
| 5 |
from collections.abc import Iterable |
| 6 |
from typing import TYPE_CHECKING, Any, Literal |
| 7 |
|
| 8 |
from django.contrib.auth import get_user_model |
| 9 |
from django.contrib.auth.base_user import AbstractBaseUser |
| 10 |
from django.core.exceptions import ImproperlyConfigured |
| 11 |
from django.core.management.utils import get_random_secret_key |
| 12 |
from django.utils import timezone |
| 13 |
from django.utils.module_loading import import_string |
| 14 |
from django.utils.translation import gettext_lazy as _ |
| 15 |
|
| 16 |
from allauth.account.internal.userkit import ( |
| 17 |
str_to_user_id, |
| 18 |
user_id_to_str, |
| 19 |
user_username, |
| 20 |
) |
| 21 |
from allauth.account.models import EmailAddress |
| 22 |
from allauth.core.internal.adapter import BaseAdapter |
| 23 |
from allauth.core.internal.cryptokit import generate_user_code |
| 24 |
from allauth.idp.oidc import app_settings |
| 25 |
from allauth.idp.oidc.internal.private_keys import filter_keys, pick_signing_key |
| 26 |
|
| 27 |
|
| 28 |
if TYPE_CHECKING: |
| 29 |
from allauth.idp.oidc.models import Client, PrivateKey, Token |
| 30 |
|
| 31 |
|
| 32 |
class DefaultOIDCAdapter(BaseAdapter): |
| 33 |
"""The adapter class allows you to override various functionality of the |
| 34 |
``allauth.idp.oidc`` app. To do so, point ``settings.IDP_OIDC_ADAPTER`` to |
| 35 |
your own class that derives from ``DefaultOIDCAdapter`` and override the |
| 36 |
behavior by altering the implementation of the methods according to your own |
| 37 |
needs. |
| 38 |
""" |
| 39 |
|
| 40 |
scope_display = { |
| 41 |
"openid": _("View your user ID"), |
| 42 |
"email": _("View your email address"), |
| 43 |
"profile": _("View your basic profile information"), |
| 44 |
} |
| 45 |
|
| 46 |
def generate_client_id(self) -> str: |
| 47 |
""" |
| 48 |
The client ID to use for newly created clients. |
| 49 |
""" |
| 50 |
return uuid.uuid4().hex |
| 51 |
|
| 52 |
def generate_client_secret(self) -> str: |
| 53 |
""" |
| 54 |
The client secret to use for newly created clients. |
| 55 |
""" |
| 56 |
return get_random_secret_key() |
| 57 |
|
| 58 |
def generate_user_code(self) -> str: |
| 59 |
return generate_user_code(**app_settings.USER_CODE_FORMAT) |
| 60 |
|
| 61 |
def hash_token(self, token: str) -> str: |
| 62 |
""" |
| 63 |
We don't store tokens directly, only the hash of the token. This methods generates |
| 64 |
that hash. |
| 65 |
""" |
| 66 |
return hashlib.sha256(token.encode("utf-8")).hexdigest() |
| 67 |
|
| 68 |
def get_issuer(self) -> str: |
| 69 |
""" |
| 70 |
Returns the URL of the issuer. |
| 71 |
""" |
| 72 |
return self.request.build_absolute_uri("/").rstrip("/") |
| 73 |
|
| 74 |
def populate_id_token( |
| 75 |
self, |
| 76 |
id_token: dict[str, Any], |
| 77 |
client: Client, |
| 78 |
scopes: Iterable[str], |
| 79 |
**kwargs: Any, |
| 80 |
) -> None: |
| 81 |
""" |
| 82 |
This method can be used to alter the ID token payload. It is already populated |
| 83 |
with basic values. Depending on the client and requested scopes, you can |
| 84 |
expose additional information here. |
| 85 |
""" |
| 86 |
pass |
| 87 |
|
| 88 |
def populate_access_token( |
| 89 |
self, |
| 90 |
access_token: dict[str, Any], |
| 91 |
*, |
| 92 |
client: Client, |
| 93 |
scopes: Iterable[str], |
| 94 |
user: AbstractBaseUser, |
| 95 |
**kwargs: Any, |
| 96 |
) -> None: |
| 97 |
""" |
| 98 |
This method can be used to alter the JWT access token payload. It is already |
| 99 |
populated with basic values. |
| 100 |
""" |
| 101 |
pass |
| 102 |
|
| 103 |
def get_claims( |
| 104 |
self, |
| 105 |
purpose: Literal["id_token", "userinfo"], |
| 106 |
user: AbstractBaseUser, |
| 107 |
client: Client, |
| 108 |
scopes: Iterable[str], |
| 109 |
email: str | None = None, |
| 110 |
**kwargs: Any, |
| 111 |
) -> dict[str, Any]: |
| 112 |
""" |
| 113 |
Return the claims to be included in the ID token or userinfo response. |
| 114 |
""" |
| 115 |
claims: dict[str, Any] = {"sub": self.get_user_sub(client, user)} |
| 116 |
if "email" in scopes: |
| 117 |
address: EmailAddress | None = None |
| 118 |
if email: |
| 119 |
try: |
| 120 |
address = EmailAddress.objects.get_for_user(user, email) |
| 121 |
except EmailAddress.DoesNotExist: |
| 122 |
pass |
| 123 |
else: |
| 124 |
address = EmailAddress.objects.get_primary(user) |
| 125 |
if address: |
| 126 |
claims.update( |
| 127 |
{ |
| 128 |
"email": address.email, |
| 129 |
"email_verified": address.verified, |
| 130 |
} |
| 131 |
) |
| 132 |
if "profile" in scopes: |
| 133 |
if hasattr(user, "get_full_name"): |
| 134 |
full_name = user.get_full_name() |
| 135 |
else: |
| 136 |
full_name = "" |
| 137 |
last_name = getattr(user, "last_name", None) |
| 138 |
first_name = getattr(user, "first_name", None) |
| 139 |
username = user_username(user) |
| 140 |
profile_claims = { |
| 141 |
"name": full_name, |
| 142 |
"given_name": first_name, |
| 143 |
"family_name": last_name, |
| 144 |
"preferred_username": username, |
| 145 |
} |
| 146 |
for claim_key, claim_value in profile_claims.items(): |
| 147 |
if claim_value: |
| 148 |
claims[claim_key] = claim_value |
| 149 |
return claims |
| 150 |
|
| 151 |
def get_user_sub(self, client: Client, user: AbstractBaseUser) -> str: |
| 152 |
""" |
| 153 |
Returns the "sub" (subject identifier) for the given user. |
| 154 |
""" |
| 155 |
return user_id_to_str(user) |
| 156 |
|
| 157 |
def get_user_by_sub(self, client: Client, sub: str) -> AbstractBaseUser | None: |
| 158 |
""" |
| 159 |
Looks up a user, given its subject identifier. Returns `None` if no |
| 160 |
such user was found. |
| 161 |
""" |
| 162 |
try: |
| 163 |
pk = str_to_user_id(sub) |
| 164 |
except ValueError: |
| 165 |
return None |
| 166 |
user = get_user_model().objects.filter(pk=pk).first() |
| 167 |
if not user or not user.is_active: |
| 168 |
return None |
| 169 |
return user |
| 170 |
|
| 171 |
def validate_client_registration( |
| 172 |
self, |
| 173 |
*, |
| 174 |
client: Client, |
| 175 |
client_metadata: dict[str, Any], |
| 176 |
token: Token | None, |
| 177 |
bearer_token: str | None, |
| 178 |
**kwargs: Any, |
| 179 |
) -> None: |
| 180 |
""" |
| 181 |
This method is called after all builtin validation was successful, |
| 182 |
and just before the actual client is being created. To intervene, raise |
| 183 |
a ``ValidationError`` or an ``ImmediateHttpResponse``. |
| 184 |
|
| 185 |
``client``: The ``Client`` instance that is about to be saved. |
| 186 |
``client_metadata``: The raw JSON payload from the DCR request. |
| 187 |
``token``: The ``Token`` instance corresponding to the initial access |
| 188 |
token, or ``None`` if no token was provided. |
| 189 |
``bearer_token``: The raw bearer token string from the ``Authorization`` |
| 190 |
header, or ``None`` if no token was provided. |
| 191 |
""" |
| 192 |
pass |
| 193 |
|
| 194 |
def validate_resource_uris(self, *, uris: list[str], **kwargs: Any) -> None: |
| 195 |
""" |
| 196 |
Allows for custom validation of resource URIs (RFC 8707). |
| 197 |
Throw a ``ValidationError`` to reject the resource. |
| 198 |
""" |
| 199 |
pass |
| 200 |
|
| 201 |
def populate_server_metadata(self, data: dict[str, str | list[str]]) -> None: |
| 202 |
""" |
| 203 |
Allows for customizing the ``/.well-known/openid-configuration`` |
| 204 |
payload, as specified in `RFC 8414`_ (OAuth 2.0 Authorization Server |
| 205 |
Metadata). |
| 206 |
|
| 207 |
.. _RFC 8414: https://www.rfc-editor.org/info/rfc8414 |
| 208 |
""" |
| 209 |
pass |
| 210 |
|
| 211 |
def is_cimd_url_allowed(self, url: str) -> bool: |
| 212 |
""" |
| 213 |
Determines whether the given CIMD (Client ID Metadata Document) URL is |
| 214 |
accepted as a ``client_id``. |
| 215 |
|
| 216 |
Override this method to restrict which clients can authenticate via CIMD, |
| 217 |
for example by maintaining a domain allowlist. The default implementation |
| 218 |
accepts all URLs that pass structural validation. |
| 219 |
""" |
| 220 |
return True |
| 221 |
|
| 222 |
def get_jwks_cache_control(self) -> int: |
| 223 |
""" |
| 224 |
Returns the cache control value for the JWKS endpoint. The default |
| 225 |
implementation returns the value of the ``IDP_OIDC_JWKS_CACHE_CONTROL`` |
| 226 |
setting, clamped so that clients refetch before the next key drops out |
| 227 |
of the key set (i.e. before the soonest ``expires_at``). Override this |
| 228 |
method to provide a different cache control value, e.g. in case of a |
| 229 |
secret manager / vault is used. |
| 230 |
""" |
| 231 |
cache_control = app_settings.JWKS_CACHE_CONTROL |
| 232 |
now = timezone.now() |
| 233 |
# Clamp against the same key set that is actually published (so a custom |
| 234 |
# ``list_private_keys()`` override cannot diverge from the cache window). |
| 235 |
for key in self.list_private_keys(is_active=True): |
| 236 |
if key.expires_at is not None: |
| 237 |
cache_control = min( |
| 238 |
cache_control, int((key.expires_at - now).total_seconds()) |
| 239 |
) |
| 240 |
return max(0, cache_control) |
| 241 |
|
| 242 |
def list_private_keys( |
| 243 |
self, |
| 244 |
*, |
| 245 |
did_activate: Literal[True] | None = None, |
| 246 |
is_active: Literal[True] | None = None, |
| 247 |
) -> list[PrivateKey]: |
| 248 |
""" |
| 249 |
Returns the configured private keys, optionally filtered. Pass |
| 250 |
``did_activate=True`` to exclude keys whose ``not_before`` lies in the |
| 251 |
future, and/or ``is_active=True`` to exclude keys past their |
| 252 |
``expires_at``. Used both for token verification and for serving |
| 253 |
``.well-known/jwks.json``. |
| 254 |
""" |
| 255 |
return filter_keys( |
| 256 |
app_settings.PRIVATE_KEYS, did_activate=did_activate, is_active=is_active |
| 257 |
) |
| 258 |
|
| 259 |
def get_signing_key(self) -> PrivateKey: |
| 260 |
""" |
| 261 |
Returns the private key used for signing new tokens: the most recently |
| 262 |
issued key that has activated and not yet expired. Raises |
| 263 |
``ImproperlyConfigured`` if no such key is found. |
| 264 |
""" |
| 265 |
key = pick_signing_key( |
| 266 |
self.list_private_keys(did_activate=True, is_active=True) |
| 267 |
) |
| 268 |
if key is None: |
| 269 |
raise ImproperlyConfigured("No active private key.") |
| 270 |
return key |
| 271 |
|
| 272 |
def populate_introspection_response( |
| 273 |
self, *, response: dict[str, Any], token: Token |
| 274 |
) -> None: |
| 275 |
""" |
| 276 |
This method can be used to add additional information to the introspection |
| 277 |
response for a given token. The default implementation does nothing. |
| 278 |
""" |
| 279 |
return None |
| 280 |
|
| 281 |
def is_introspection_allowed( |
| 282 |
self, |
| 283 |
token: Token, |
| 284 |
*, |
| 285 |
caller_client: Client, |
| 286 |
) -> bool: |
| 287 |
""" |
| 288 |
This method can be used to add additional checks to determine if a token is |
| 289 |
valid in introspection responses and if the caller client is allowed to introspect it. |
| 290 |
The default implementation allows all introspection requests for active tokens, |
| 291 |
regardless of the caller client. |
| 292 |
|
| 293 |
``caller_client``: The authenticated introspection caller client. |
| 294 |
""" |
| 295 |
return True |
| 296 |
|
| 297 |
|
| 298 |
def get_adapter() -> DefaultOIDCAdapter: |
| 299 |
return import_string(app_settings.ADAPTER)() |