| 1 |
"""Token Verifier module""" |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
from typing import TYPE_CHECKING, Any |
| 5 |
|
| 6 |
from .exceptions import TokenValidationError |
| 7 |
from .rest_async import AsyncRestClient |
| 8 |
from .token_verifier import AsymmetricSignatureVerifier, JwksFetcher, TokenVerifier |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from aiohttp import ClientSession |
| 12 |
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey |
| 13 |
|
| 14 |
|
| 15 |
class AsyncAsymmetricSignatureVerifier(AsymmetricSignatureVerifier): |
| 16 |
"""Async verifier for RSA signatures, which rely on public key certificates. |
| 17 |
|
| 18 |
Args: |
| 19 |
jwks_url (str): The url where the JWK set is located. |
| 20 |
algorithm (str, optional): The expected signing algorithm. Defaults to "RS256". |
| 21 |
""" |
| 22 |
|
| 23 |
def __init__(self, jwks_url: str, algorithm: str = "RS256") -> None: |
| 24 |
super().__init__(jwks_url, algorithm) |
| 25 |
self._fetcher = AsyncJwksFetcher(jwks_url) |
| 26 |
|
| 27 |
def set_session(self, session: ClientSession) -> None: |
| 28 |
"""Set Client Session to improve performance by reusing session. |
| 29 |
|
| 30 |
Args: |
| 31 |
session (aiohttp.ClientSession): The client session which should be closed |
| 32 |
manually or within context manager. |
| 33 |
""" |
| 34 |
self._fetcher.set_session(session) |
| 35 |
|
| 36 |
async def _fetch_key(self, key_id=None): |
| 37 |
"""Request the JWKS. |
| 38 |
|
| 39 |
Args: |
| 40 |
key_id (str): The key's key id.""" |
| 41 |
return await self._fetcher.get_key(key_id) |
| 42 |
|
| 43 |
async def verify_signature(self, token) -> dict[str, Any]: |
| 44 |
"""Verifies the signature of the given JSON web token. |
| 45 |
|
| 46 |
Args: |
| 47 |
token (str): The JWT to get its signature verified. |
| 48 |
|
| 49 |
Raises: |
| 50 |
TokenValidationError: if the token cannot be decoded, the algorithm is invalid |
| 51 |
or the token's signature doesn't match the calculated one. |
| 52 |
""" |
| 53 |
kid = self._get_kid(token) |
| 54 |
secret_or_certificate = await self._fetch_key(key_id=kid) |
| 55 |
|
| 56 |
return self._decode_jwt(token, secret_or_certificate) |
| 57 |
|
| 58 |
|
| 59 |
class AsyncJwksFetcher(JwksFetcher): |
| 60 |
"""Class that async fetches and holds a JSON web key set. |
| 61 |
This class makes use of an in-memory cache. For it to work properly, define this instance once and re-use it. |
| 62 |
|
| 63 |
Args: |
| 64 |
jwks_url (str): The url where the JWK set is located. |
| 65 |
cache_ttl (str, optional): The lifetime of the JWK set cache in seconds. Defaults to 600 seconds. |
| 66 |
""" |
| 67 |
|
| 68 |
def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 69 |
super().__init__(*args, **kwargs) |
| 70 |
self._async_client = AsyncRestClient(None) |
| 71 |
|
| 72 |
def set_session(self, session: ClientSession) -> None: |
| 73 |
"""Set Client Session to improve performance by reusing session. |
| 74 |
|
| 75 |
Args: |
| 76 |
session (aiohttp.ClientSession): The client session which should be closed |
| 77 |
manually or within context manager. |
| 78 |
""" |
| 79 |
self._async_client.set_session(session) |
| 80 |
|
| 81 |
async def _fetch_jwks(self, force: bool = False) -> dict[str, RSAPublicKey]: |
| 82 |
"""Attempts to obtain the JWK set from the cache, as long as it's still valid. |
| 83 |
When not, it will perform a network request to the jwks_url to obtain a fresh result |
| 84 |
and update the cache value with it. |
| 85 |
|
| 86 |
Args: |
| 87 |
force (bool, optional): whether to ignore the cache and force a network request or not. Defaults to False. |
| 88 |
""" |
| 89 |
if force or self._cache_expired(): |
| 90 |
self._cache_value = {} |
| 91 |
try: |
| 92 |
jwks = await self._async_client.get(self._jwks_url) |
| 93 |
self._cache_jwks(jwks) |
| 94 |
except: |
| 95 |
return self._cache_value |
| 96 |
return self._cache_value |
| 97 |
|
| 98 |
self._cache_is_fresh = False |
| 99 |
return self._cache_value |
| 100 |
|
| 101 |
async def get_key(self, key_id: str) -> RSAPublicKey: |
| 102 |
"""Obtains the JWK associated with the given key id. |
| 103 |
|
| 104 |
Args: |
| 105 |
key_id (str): The id of the key to fetch. |
| 106 |
|
| 107 |
Returns: |
| 108 |
the JWK associated with the given key id. |
| 109 |
|
| 110 |
Raises: |
| 111 |
TokenValidationError: when a key with that id cannot be found |
| 112 |
""" |
| 113 |
keys = await self._fetch_jwks() |
| 114 |
|
| 115 |
if keys and key_id in keys: |
| 116 |
return keys[key_id] |
| 117 |
|
| 118 |
if not self._cache_is_fresh: |
| 119 |
keys = await self._fetch_jwks(force=True) |
| 120 |
if keys and key_id in keys: |
| 121 |
return keys[key_id] |
| 122 |
raise TokenValidationError(f'RSA Public Key with ID "{key_id}" was not found.') |
| 123 |
|
| 124 |
|
| 125 |
class AsyncTokenVerifier(TokenVerifier): |
| 126 |
"""Class that verifies ID tokens following the steps defined in the OpenID Connect spec. |
| 127 |
An OpenID Connect ID token is not meant to be consumed until it's verified. |
| 128 |
|
| 129 |
Args: |
| 130 |
signature_verifier (AsyncAsymmetricSignatureVerifier): The instance that knows how to verify the signature. |
| 131 |
issuer (str): The expected issuer claim value. |
| 132 |
audience (str): The expected audience claim value. |
| 133 |
leeway (int, optional): The clock skew to accept when verifying date related claims in seconds. |
| 134 |
Defaults to 60 seconds. |
| 135 |
""" |
| 136 |
|
| 137 |
def __init__( |
| 138 |
self, |
| 139 |
signature_verifier: AsyncAsymmetricSignatureVerifier, |
| 140 |
issuer: str, |
| 141 |
audience: str, |
| 142 |
leeway: int = 0, |
| 143 |
) -> None: |
| 144 |
if not signature_verifier or not isinstance( |
| 145 |
signature_verifier, AsyncAsymmetricSignatureVerifier |
| 146 |
): |
| 147 |
raise TypeError( |
| 148 |
"signature_verifier must be an instance of AsyncAsymmetricSignatureVerifier." |
| 149 |
) |
| 150 |
|
| 151 |
self.iss = issuer |
| 152 |
self.aud = audience |
| 153 |
self.leeway = leeway |
| 154 |
self._sv = signature_verifier |
| 155 |
self._clock = None |
| 156 |
|
| 157 |
def set_session(self, session: ClientSession) -> None: |
| 158 |
"""Set Client Session to improve performance by reusing session. |
| 159 |
|
| 160 |
Args: |
| 161 |
session (aiohttp.ClientSession): The client session which should be closed |
| 162 |
manually or within context manager. |
| 163 |
""" |
| 164 |
self._sv.set_session(session) |
| 165 |
|
| 166 |
async def verify( |
| 167 |
self, |
| 168 |
token: str, |
| 169 |
nonce: str | None = None, |
| 170 |
max_age: int | None = None, |
| 171 |
organization: str | None = None, |
| 172 |
) -> dict[str, Any]: |
| 173 |
"""Attempts to verify the given ID token, following the steps defined in the OpenID Connect spec. |
| 174 |
|
| 175 |
Args: |
| 176 |
token (str): The JWT to verify. |
| 177 |
nonce (str, optional): The nonce value sent during authentication. |
| 178 |
max_age (int, optional): The max_age value sent during authentication. |
| 179 |
organization (str, optional): The expected organization ID (org_id) or organization name (org_name) claim value. This should be specified |
| 180 |
when logging in to an organization. |
| 181 |
|
| 182 |
Returns: |
| 183 |
the decoded payload from the token |
| 184 |
|
| 185 |
Raises: |
| 186 |
TokenValidationError: when the token cannot be decoded, the token signing algorithm is not the expected one, |
| 187 |
the token signature is invalid or the token has a claim missing or with unexpected value. |
| 188 |
""" |
| 189 |
|
| 190 |
|
| 191 |
if not token or not isinstance(token, str): |
| 192 |
raise TokenValidationError("ID token is required but missing.") |
| 193 |
|
| 194 |
|
| 195 |
payload = await self._sv.verify_signature(token) |
| 196 |
|
| 197 |
|
| 198 |
self._verify_payload(payload, nonce, max_age, organization) |
| 199 |
|
| 200 |
return payload |