Skip to content

Commit fc5b94e

Browse files
Add cacheing functionality for JWK set (#781)
* Initial implementation of ttl jwk set cache (cherry picked from commit 479a7c1) * Add unit test for jwk set cache * Fix failed unit test * Disable cache signing key by default * Add a negative unit test for get_jwk_set * Add functionality to force refresh the jwk set cache when no matching signing key can be found from the cache * Add unit test for refresh cache * Add unit test to unset cache when the network call throws error * fix naming typo * Update unit test naming * Update comment * Add check for lifespan * Update comments for get_signing_key * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix ci error * Add type declaration to fix CI error * Add more unit tests to improve coverage * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Try to increase test coverage to 100% Co-authored-by: Jerry Wu <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ae3da74 commit fc5b94e

File tree

4 files changed

+263
-33
lines changed

4 files changed

+263
-33
lines changed

jwt/api_jwk.py

+13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import json
4+
import time
45

56
from .algorithms import get_default_algorithms
67
from .exceptions import InvalidKeyError, PyJWKError, PyJWKSetError
@@ -110,3 +111,15 @@ def __getitem__(self, kid):
110111
if key.key_id == kid:
111112
return key
112113
raise KeyError(f"keyset has no key for kid: {kid}")
114+
115+
116+
class PyJWTSetWithTimestamp:
117+
def __init__(self, jwk_set: PyJWKSet):
118+
self.jwk_set = jwk_set
119+
self.timestamp = time.monotonic()
120+
121+
def get_jwk_set(self):
122+
return self.jwk_set
123+
124+
def get_timestamp(self):
125+
return self.timestamp

jwt/jwk_set_cache.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import time
2+
from typing import Optional
3+
4+
from .api_jwk import PyJWKSet, PyJWTSetWithTimestamp
5+
6+
7+
class JWKSetCache:
8+
def __init__(self, lifespan: int):
9+
self.jwk_set_with_timestamp: Optional[PyJWTSetWithTimestamp] = None
10+
self.lifespan = lifespan
11+
12+
def put(self, jwk_set: PyJWKSet):
13+
if jwk_set is not None:
14+
self.jwk_set_with_timestamp = PyJWTSetWithTimestamp(jwk_set)
15+
else:
16+
# clear cache
17+
self.jwk_set_with_timestamp = None
18+
19+
def get(self) -> Optional[PyJWKSet]:
20+
if self.jwk_set_with_timestamp is None or self.is_expired():
21+
return None
22+
23+
return self.jwk_set_with_timestamp.get_jwk_set()
24+
25+
def is_expired(self) -> bool:
26+
27+
return (
28+
self.jwk_set_with_timestamp is not None
29+
and self.lifespan > -1
30+
and time.monotonic()
31+
> self.jwk_set_with_timestamp.get_timestamp() + self.lifespan
32+
)

jwt/jwks_client.py

+65-17
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,68 @@
11
import json
22
import urllib.request
33
from functools import lru_cache
4-
from typing import Any, List
4+
from typing import Any, List, Optional
5+
from urllib.error import URLError
56

67
from .api_jwk import PyJWK, PyJWKSet
78
from .api_jwt import decode_complete as decode_token
89
from .exceptions import PyJWKClientError
10+
from .jwk_set_cache import JWKSetCache
911

1012

1113
class PyJWKClient:
12-
def __init__(self, uri: str, cache_keys: bool = True, max_cached_keys: int = 16):
14+
def __init__(
15+
self,
16+
uri: str,
17+
cache_keys: bool = False,
18+
max_cached_keys: int = 16,
19+
cache_jwk_set: bool = True,
20+
lifespan: int = 300,
21+
):
1322
self.uri = uri
23+
self.jwk_set_cache: Optional[JWKSetCache] = None
24+
25+
if cache_jwk_set:
26+
# Init jwt set cache with default or given lifespan.
27+
# Default lifespan is 300 seconds (5 minutes).
28+
if lifespan <= 0:
29+
raise PyJWKClientError(
30+
f'Lifespan must be greater than 0, the input is "{lifespan}"'
31+
)
32+
self.jwk_set_cache = JWKSetCache(lifespan)
33+
else:
34+
self.jwk_set_cache = None
35+
1436
if cache_keys:
1537
# Cache signing keys
1638
# Ignore mypy (https://github.com/python/mypy/issues/2427)
1739
self.get_signing_key = lru_cache(maxsize=max_cached_keys)(self.get_signing_key) # type: ignore
1840

1941
def fetch_data(self) -> Any:
20-
with urllib.request.urlopen(self.uri) as response:
21-
return json.load(response)
42+
jwk_set: Any = None
43+
try:
44+
with urllib.request.urlopen(self.uri) as response:
45+
jwk_set = json.load(response)
46+
except URLError as e:
47+
raise PyJWKClientError(f'Fail to fetch data from the url, err: "{e}"')
48+
else:
49+
return jwk_set
50+
finally:
51+
if self.jwk_set_cache is not None:
52+
self.jwk_set_cache.put(jwk_set)
53+
54+
def get_jwk_set(self, refresh: bool = False) -> PyJWKSet:
55+
data = None
56+
if self.jwk_set_cache is not None and not refresh:
57+
data = self.jwk_set_cache.get()
58+
59+
if data is None:
60+
data = self.fetch_data()
2261

23-
def get_jwk_set(self) -> PyJWKSet:
24-
data = self.fetch_data()
2562
return PyJWKSet.from_dict(data)
2663

27-
def get_signing_keys(self) -> List[PyJWK]:
28-
jwk_set = self.get_jwk_set()
64+
def get_signing_keys(self, refresh: bool = False) -> List[PyJWK]:
65+
jwk_set = self.get_jwk_set(refresh)
2966
signing_keys = [
3067
jwk_set_key
3168
for jwk_set_key in jwk_set.keys
@@ -39,21 +76,32 @@ def get_signing_keys(self) -> List[PyJWK]:
3976

4077
def get_signing_key(self, kid: str) -> PyJWK:
4178
signing_keys = self.get_signing_keys()
42-
signing_key = None
43-
44-
for key in signing_keys:
45-
if key.key_id == kid:
46-
signing_key = key
47-
break
79+
signing_key = self.match_kid(signing_keys, kid)
4880

4981
if not signing_key:
50-
raise PyJWKClientError(
51-
f'Unable to find a signing key that matches: "{kid}"'
52-
)
82+
# If no matching signing key from the jwk set, refresh the jwk set and try again.
83+
signing_keys = self.get_signing_keys(refresh=True)
84+
signing_key = self.match_kid(signing_keys, kid)
85+
86+
if not signing_key:
87+
raise PyJWKClientError(
88+
f'Unable to find a signing key that matches: "{kid}"'
89+
)
5390

5491
return signing_key
5592

5693
def get_signing_key_from_jwt(self, token: str) -> PyJWK:
5794
unverified = decode_token(token, options={"verify_signature": False})
5895
header = unverified["header"]
5996
return self.get_signing_key(header.get("kid"))
97+
98+
@staticmethod
99+
def match_kid(signing_keys: List[PyJWK], kid: str) -> Optional[PyJWK]:
100+
signing_key = None
101+
102+
for key in signing_keys:
103+
if key.key_id == kid:
104+
signing_key = key
105+
break
106+
107+
return signing_key

0 commit comments

Comments
 (0)