Debian Codegraph @

src/auth0/authentication/token_verifier.py

raw symbols SCIP
1 """Token Verifier module"""
2 from __future__ import annotations
3
4 import json
5 import time
6 from typing import TYPE_CHECKING, Any, ClassVar
7
8 import jwt
9 import requests
10
11 from .exceptions import TokenValidationError
12
13 if TYPE_CHECKING:
14 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
15
16
17 class SignatureVerifier:
18 """Abstract class that will verify a given JSON web token's signature
19 using the key fetched internally given its key id.
20
21 Args:
22 algorithm (str): The expected signing algorithm (e.g. RS256).
23 """
24
25 DISABLE_JWT_CHECKS: ClassVar[dict[str, bool]] = {
26 "verify_signature": True,
27 "verify_exp": False,
28 "verify_nbf": False,
29 "verify_iat": False,
30 "verify_aud": False,
31 "verify_iss": False,
32 "require_exp": False,
33 "require_iat": False,
34 "require_nbf": False,
35 }
36
37 def __init__(self, algorithm: str) -> None:
38 if not algorithm or type(algorithm) != str:
39 raise ValueError("algorithm must be specified.")
40 self._algorithm = algorithm
41
42 def _fetch_key(self, key_id: str) -> str | RSAPublicKey:
43 """Obtains the key associated to the given key id.
44 Must be implemented by subclasses.
45
46 Args:
47 key_id (str): The id of the key to fetch.
48
49 Returns:
50 the key to use for verifying a cryptographic signature
51 """
52 raise NotImplementedError
53
54 def _get_kid(self, token: str) -> str | None:
55 """Gets the key id from the kid claim of the header of the token
56
57 Args:
58 token (str): The JWT to get the header from.
59
60 Raises:
61 TokenValidationError: if the token cannot be decoded, the algorithm is invalid
62 or the token's signature doesn't match the calculated one.
63
64 Returns:
65 the key id or None
66 """
67 try:
68 header = jwt.get_unverified_header(token)
69 except jwt.exceptions.DecodeError:
70 raise TokenValidationError("token could not be decoded.")
71
72 alg = header.get("alg", None)
73 if alg != self._algorithm:
74 raise TokenValidationError(
75 'Signature algorithm of "{}" is not supported. Expected the token '
76 'to be signed with "{}"'.format(alg, self._algorithm)
77 )
78
79 return header.get("kid", None)
80
81 def _decode_jwt(self, token: str, secret_or_certificate: str) -> dict[str, Any]:
82 """Verifies and decodes the given JSON web token with the given public key or shared secret.
83
84 Args:
85 token (str): The JWT to get its signature verified.
86 secret_or_certificate (str): The public key or shared secret.
87
88 Raises:
89 TokenValidationError: if the token cannot be decoded, the algorithm is invalid
90 or the token's signature doesn't match the calculated one.
91 """
92 try:
93 decoded = jwt.decode(
94 jwt=token,
95 key=secret_or_certificate,
96 algorithms=[self._algorithm],
97 options=self.DISABLE_JWT_CHECKS,
98 )
99 except jwt.exceptions.InvalidSignatureError:
100 raise TokenValidationError("Invalid token signature.")
101 return decoded
102
103 def verify_signature(self, token: str) -> dict[str, Any]:
104 """Verifies the signature of the given JSON web token.
105
106 Args:
107 token (str): The JWT to get its signature verified.
108
109 Raises:
110 TokenValidationError: if the token cannot be decoded, the algorithm is invalid
111 or the token's signature doesn't match the calculated one.
112 """
113 kid = self._get_kid(token)
114 if kid is None:
115 kid = ""
116 secret_or_certificate = self._fetch_key(key_id=kid)
117
118 return self._decode_jwt(token, secret_or_certificate) # type: ignore[arg-type]
119
120
121 class SymmetricSignatureVerifier(SignatureVerifier):
122 """Verifier for HMAC signatures, which rely on shared secrets.
123
124 Args:
125 shared_secret (str): The shared secret used to decode the token.
126 algorithm (str, optional): The expected signing algorithm. Defaults to "HS256".
127 """
128
129 def __init__(self, shared_secret: str, algorithm: str = "HS256") -> None:
130 super().__init__(algorithm)
131 self._shared_secret = shared_secret
132
133 def _fetch_key(self, key_id: str = "") -> str:
134 return self._shared_secret
135
136
137 class JwksFetcher:
138 """Class that fetches and holds a JSON web key set.
139 This class makes use of an in-memory cache. For it to work properly, define this instance once and re-use it.
140
141 Args:
142 jwks_url (str): The url where the JWK set is located.
143 cache_ttl (str, optional): The lifetime of the JWK set cache in seconds. Defaults to 600 seconds.
144 """
145
146 CACHE_TTL: ClassVar[int] = 600 # 10 min cache lifetime
147
148 def __init__(self, jwks_url: str, cache_ttl: int = CACHE_TTL) -> None:
149 self._jwks_url = jwks_url
150 self._init_cache(cache_ttl)
151
152 def _init_cache(self, cache_ttl: int) -> None:
153 self._cache_value: dict[str, RSAPublicKey] = {}
154 self._cache_date = 0.0
155 self._cache_ttl = cache_ttl
156 self._cache_is_fresh = False
157
158 def _cache_expired(self) -> bool:
159 """Checks if the cache is expired
160
161 Returns:
162 True if it should use the cache.
163 """
164 return self._cache_date + self._cache_ttl < time.time()
165
166 def _cache_jwks(self, jwks: dict[str, Any]) -> None:
167 """Cache the response of the JWKS request
168
169 Args:
170 jwks (dict): The JWKS
171 """
172 self._cache_value = self._parse_jwks(jwks)
173 self._cache_is_fresh = True
174 self._cache_date = time.time()
175
176 def _fetch_jwks(self, force: bool = False) -> dict[str, RSAPublicKey]:
177 """Attempts to obtain the JWK set from the cache, as long as it's still valid.
178 When not, it will perform a network request to the jwks_url to obtain a fresh result
179 and update the cache value with it.
180
181 Args:
182 force (bool, optional): whether to ignore the cache and force a network request or not. Defaults to False.
183 """
184 if force or self._cache_expired():
185 self._cache_value = {}
186 response = requests.get(self._jwks_url)
187 if response.ok:
188 jwks: dict[str, Any] = response.json()
189 self._cache_jwks(jwks)
190 return self._cache_value
191
192 self._cache_is_fresh = False
193 return self._cache_value
194
195 @staticmethod
196 def _parse_jwks(jwks: dict[str, Any]) -> dict[str, RSAPublicKey]:
197 """
198 Converts a JWK string representation into a binary certificate in PEM format.
199 """
200 keys: dict[str, RSAPublicKey] = {}
201
202 for key in jwks["keys"]:
203 # noinspection PyUnresolvedReferences
204 # requirement already includes cryptography -> pyjwt[crypto]
205 rsa_key: RSAPublicKey = jwt.algorithms.RSAAlgorithm.from_jwk(
206 json.dumps(key)
207 )
208 keys[key["kid"]] = rsa_key
209 return keys
210
211 def get_key(self, key_id: str) -> RSAPublicKey:
212 """Obtains the JWK associated with the given key id.
213
214 Args:
215 key_id (str): The id of the key to fetch.
216
217 Returns:
218 the JWK associated with the given key id.
219
220 Raises:
221 TokenValidationError: when a key with that id cannot be found
222 """
223 keys = self._fetch_jwks()
224
225 if keys and key_id in keys:
226 return keys[key_id]
227
228 if not self._cache_is_fresh:
229 keys = self._fetch_jwks(force=True)
230 if keys and key_id in keys:
231 return keys[key_id]
232 raise TokenValidationError(f'RSA Public Key with ID "{key_id}" was not found.')
233
234
235 class AsymmetricSignatureVerifier(SignatureVerifier):
236 """Verifier for RSA signatures, which rely on public key certificates.
237
238 Args:
239 jwks_url (str): The url where the JWK set is located.
240 algorithm (str, optional): The expected signing algorithm. Defaults to "RS256".
241 cache_ttl (int, optional): The lifetime of the JWK set cache in seconds. Defaults to 600 seconds.
242 """
243
244 def __init__(
245 self,
246 jwks_url: str,
247 algorithm: str = "RS256",
248 cache_ttl: int = JwksFetcher.CACHE_TTL,
249 ) -> None:
250 super().__init__(algorithm)
251 self._fetcher = JwksFetcher(jwks_url, cache_ttl)
252
253 def _fetch_key(self, key_id: str) -> RSAPublicKey:
254 return self._fetcher.get_key(key_id)
255
256
257 class TokenVerifier:
258 """Class that verifies ID tokens following the steps defined in the OpenID Connect spec.
259 An OpenID Connect ID token is not meant to be consumed until it's verified.
260
261 Args:
262 signature_verifier (SignatureVerifier): The instance that knows how to verify the signature.
263 issuer (str): The expected issuer claim value.
264 audience (str): The expected audience claim value.
265 leeway (int, optional): The clock skew to accept when verifying date related claims in seconds.
266 Defaults to 60 seconds.
267 """
268
269 def __init__(
270 self,
271 signature_verifier: SignatureVerifier,
272 issuer: str,
273 audience: str,
274 leeway: int = 0,
275 ) -> None:
276 if not signature_verifier or not isinstance(
277 signature_verifier, SignatureVerifier
278 ):
279 raise TypeError(
280 "signature_verifier must be an instance of SignatureVerifier."
281 )
282
283 self.iss = issuer
284 self.aud = audience
285 self.leeway = leeway
286 self._sv = signature_verifier
287 self._clock = None # visible for testing
288
289 def verify(
290 self,
291 token: str,
292 nonce: str | None = None,
293 max_age: int | None = None,
294 organization: str | None = None,
295 ) -> dict[str, Any]:
296 """Attempts to verify the given ID token, following the steps defined in the OpenID Connect spec.
297
298 Args:
299 token (str): The JWT to verify.
300 nonce (str, optional): The nonce value sent during authentication.
301 max_age (int, optional): The max_age value sent during authentication.
302 organization (str, optional): The expected organization ID (org_id) or organization name (org_name) claim value. This should be specified
303 when logging in to an organization.
304
305 Returns:
306 the decoded payload from the token
307
308 Raises:
309 TokenValidationError: when the token cannot be decoded, the token signing algorithm is not the expected one,
310 the token signature is invalid or the token has a claim missing or with unexpected value.
311 """
312
313 # Verify token presence
314 if not token or not isinstance(token, str):
315 raise TokenValidationError("ID token is required but missing.")
316
317 # Verify algorithm and signature
318 payload = self._sv.verify_signature(token)
319
320 # Verify claims
321 self._verify_payload(payload, nonce, max_age, organization)
322
323 return payload
324
325 def _verify_payload(
326 self,
327 payload: dict[str, Any],
328 nonce: str | None = None,
329 max_age: int | None = None,
330 organization: str | None = None,
331 ) -> None:
332 # Issuer
333 if "iss" not in payload or not isinstance(payload["iss"], str):
334 raise TokenValidationError(
335 "Issuer (iss) claim must be a string present in the ID token"
336 )
337 if payload["iss"] != self.iss:
338 raise TokenValidationError(
339 'Issuer (iss) claim mismatch in the ID token; expected "{}", '
340 'found "{}"'.format(self.iss, payload["iss"])
341 )
342
343 # Subject
344 if "sub" not in payload or not isinstance(payload["sub"], str):
345 raise TokenValidationError(
346 "Subject (sub) claim must be a string present in the ID token"
347 )
348
349 # Audience
350 if "aud" not in payload or not isinstance(payload["aud"], (str, list)):
351 raise TokenValidationError(
352 "Audience (aud) claim must be a string or array of strings present in"
353 " the ID token"
354 )
355
356 if isinstance(payload["aud"], list) and self.aud not in payload["aud"]:
357 payload_audiences = ", ".join(payload["aud"])
358 raise TokenValidationError(
359 'Audience (aud) claim mismatch in the ID token; expected "{}" but was '
360 'not one of "{}"'.format(self.aud, payload_audiences)
361 )
362 elif isinstance(payload["aud"], str) and payload["aud"] != self.aud:
363 raise TokenValidationError(
364 'Audience (aud) claim mismatch in the ID token; expected "{}" '
365 'but found "{}"'.format(self.aud, payload["aud"])
366 )
367
368 # --Time validation (epoch)--
369 now = self._clock or time.time()
370 leeway = self.leeway
371
372 # Expires at
373 if "exp" not in payload or not isinstance(payload["exp"], int):
374 raise TokenValidationError(
375 "Expiration Time (exp) claim must be a number present in the ID token"
376 )
377
378 exp_time = payload["exp"] + leeway
379 if now > exp_time:
380 raise TokenValidationError(
381 "Expiration Time (exp) claim error in the ID token; current time ({})"
382 " is after expiration time ({})".format(now, exp_time)
383 )
384
385 # Issued at
386 if "iat" not in payload or not isinstance(payload["iat"], int):
387 raise TokenValidationError(
388 "Issued At (iat) claim must be a number present in the ID token"
389 )
390
391 # Nonce
392 if nonce:
393 if "nonce" not in payload or not isinstance(payload["nonce"], str):
394 raise TokenValidationError(
395 "Nonce (nonce) claim must be a string present in the ID token"
396 )
397 if payload["nonce"] != nonce:
398 raise TokenValidationError(
399 'Nonce (nonce) claim mismatch in the ID token; expected "{}", '
400 'found "{}"'.format(nonce, payload["nonce"])
401 )
402
403 # Organization
404 if organization:
405 if organization.startswith("org_"):
406 if "org_id" not in payload or not isinstance(payload["org_id"], str):
407 raise TokenValidationError(
408 "Organization (org_id) claim must be a string present in the ID"
409 " token"
410 )
411 if payload["org_id"] != organization:
412 raise TokenValidationError(
413 "Organization (org_id) claim mismatch in the ID token; expected"
414 ' "{}", found "{}"'.format(organization, payload["org_id"])
415 )
416 else:
417 if "org_name" not in payload or not isinstance(
418 payload["org_name"], str
419 ):
420 raise TokenValidationError(
421 "Organization (org_name) claim must be a string present in the ID"
422 " token"
423 )
424 if payload["org_name"] != organization.lower():
425 raise TokenValidationError(
426 "Organization (org_name) claim mismatch in the ID token; expected"
427 ' "{}", found "{}"'.format(organization, payload["org_name"])
428 )
429
430 # Authorized party
431 if isinstance(payload["aud"], list) and len(payload["aud"]) > 1:
432 if "azp" not in payload or not isinstance(payload["azp"], str):
433 raise TokenValidationError(
434 "Authorized Party (azp) claim must be a string present in the ID"
435 " token when Audience (aud) claim has multiple values"
436 )
437 if payload["azp"] != self.aud:
438 raise TokenValidationError(
439 "Authorized Party (azp) claim mismatch in the ID token; expected"
440 ' "{}", found "{}"'.format(self.aud, payload["azp"])
441 )
442
443 # Authentication time
444 if max_age:
445 if "auth_time" not in payload or not isinstance(payload["auth_time"], int):
446 raise TokenValidationError(
447 "Authentication Time (auth_time) claim must be a number present in"
448 " the ID token when Max Age (max_age) is specified"
449 )
450
451 auth_valid_until = payload["auth_time"] + max_age + leeway
452 if now > auth_valid_until:
453 raise TokenValidationError(
454 "Authentication Time (auth_time) claim in the ID token indicates"
455 " that too much time has passed since the last end-user"
456 " authentication. Current time ({}) is after last auth at ({})".format(
457 now, auth_valid_until
458 )
459 )