| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import logging |
| 5 |
import typing as t |
| 6 |
|
| 7 |
import jwt |
| 8 |
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey |
| 9 |
|
| 10 |
from globus_sdk._missing import MISSING, MissingType |
| 11 |
from globus_sdk.response import GlobusHTTPResponse |
| 12 |
|
| 13 |
log = logging.getLogger(__name__) |
| 14 |
|
| 15 |
|
| 16 |
class _JWKGetCallbackProto(t.Protocol): |
| 17 |
def __call__( |
| 18 |
self, |
| 19 |
path: str, |
| 20 |
*, |
| 21 |
query_params: dict[str, t.Any] | None = None, |
| 22 |
headers: dict[str, str] | None = None, |
| 23 |
) -> GlobusHTTPResponse: ... |
| 24 |
|
| 25 |
|
| 26 |
def get_jwk_data( |
| 27 |
*, |
| 28 |
fget: _JWKGetCallbackProto, |
| 29 |
openid_configuration: GlobusHTTPResponse | dict[str, t.Any], |
| 30 |
) -> dict[str, t.Any]: |
| 31 |
jwks_uri = openid_configuration["jwks_uri"] |
| 32 |
log.debug("fetching from jwks_uri=%s", jwks_uri) |
| 33 |
data = fget(jwks_uri).data |
| 34 |
if not isinstance(data, dict): |
| 35 |
# how could this happen? |
| 36 |
# some guesses: |
| 37 |
# - interfering proxy or cache |
| 38 |
# - user passed explicit (incorrect) OIDC config |
| 39 |
raise ValueError( |
| 40 |
"JWK data was not a dict. This should be an unreachable condition." |
| 41 |
) |
| 42 |
return data |
| 43 |
|
| 44 |
|
| 45 |
def pem_decode_jwk_data( |
| 46 |
*, |
| 47 |
jwk_data: dict[str, t.Any], |
| 48 |
) -> RSAPublicKey: |
| 49 |
log.debug("JWK PEM decode requested, decoding...") |
| 50 |
# decode from JWK to an RSA PEM key for JWT decoding |
| 51 |
# cast here because this should never be private key |
| 52 |
jwk_as_pem: RSAPublicKey = t.cast( |
| 53 |
RSAPublicKey, |
| 54 |
jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk_data["keys"][0])), |
| 55 |
) |
| 56 |
log.debug("JWK PEM decoding finished successfully") |
| 57 |
return jwk_as_pem |
| 58 |
|
| 59 |
|
| 60 |
@t.runtime_checkable |
| 61 |
class SupportsJWKMethods(t.Protocol): |
| 62 |
client_id: str | None |
| 63 |
|
| 64 |
def get_openid_configuration(self) -> GlobusHTTPResponse: ... |
| 65 |
|
| 66 |
@t.overload |
| 67 |
def get_jwk( |
| 68 |
self, |
| 69 |
openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType, |
| 70 |
*, |
| 71 |
as_pem: t.Literal[True], |
| 72 |
) -> RSAPublicKey: ... |
| 73 |
|
| 74 |
@t.overload |
| 75 |
def get_jwk( |
| 76 |
self, |
| 77 |
openid_configuration: GlobusHTTPResponse | dict[str, t.Any] | MissingType, |
| 78 |
*, |
| 79 |
as_pem: t.Literal[False], |
| 80 |
) -> dict[str, t.Any]: ... |
| 81 |
|
| 82 |
def get_jwk( |
| 83 |
self, |
| 84 |
openid_configuration: ( |
| 85 |
GlobusHTTPResponse | dict[str, t.Any] | MissingType |
| 86 |
) = MISSING, |
| 87 |
*, |
| 88 |
as_pem: bool = False, |
| 89 |
) -> RSAPublicKey | dict[str, t.Any]: ... |