"""PKCE is mandatory except for explicitly approved legacy confidential clients.""" from urllib.parse import urlsplit from django.conf import settings def require_pkce(client_id: str) -> bool: if client_id not in settings.OIDC_LEGACY_NO_PKCE_CLIENT_IDS: return True # Import lazily: settings imports this callable before Django populates apps. from oauth2_provider.models import get_application_model application_model = get_application_model() application = ( application_model.objects.filter(client_id=client_id) .only("client_type", "authorization_grant_type", "redirect_uris") .first() ) if application is None: return True redirects = application.redirect_uris.split() return not ( application.client_type == application_model.CLIENT_CONFIDENTIAL and application.authorization_grant_type == application_model.GRANT_AUTHORIZATION_CODE and redirects and all( urlsplit(uri).scheme == "https" and urlsplit(uri).hostname and not urlsplit(uri).username and not urlsplit(uri).fragment and "*" not in uri for uri in redirects ) )