Debian Codegraph @

allauth/socialaccount/internal/jwtkit.py

raw
1 from __future__ import annotations
2
3 import json
4 import time
5
6 from django.core.cache import cache
7
8 from allauth.core.internal.deferred import cryptography, jwt
9 from allauth.socialaccount.adapter import get_adapter
10 from allauth.socialaccount.providers.oauth2.client import OAuth2Error
11
12
13 def lookup_kid_pem_x509_certificate(keys_data, kid):
14 """
15 Looks up the key given keys data of the form:
16
17 {"<kid>": "-----BEGIN CERTIFICATE-----\nCERTIFICATE"}
18 """
19 key = keys_data.get(kid)
20 if key:
21 public_key = cryptography.x509.load_pem_x509_certificate(
22 key.encode("utf8"), cryptography.hazmat.backends.default_backend()
23 ).public_key()
24 return public_key
25
26
27 def lookup_kid_jwk(keys_data, kid):
28 """
29 Looks up the key given keys data of the form:
30
31 {
32 "keys": [
33 {
34 "kty": "RSA",
35 "kid": "W6WcOKB",
36 "use": "sig",
37 "alg": "RS256",
38 "n": "2Zc5d0-zk....",
39 "e": "AQAB"
40 }]
41 }
42 """
43 algorithms = jwt.algorithms.get_default_algorithms()
44 for d in keys_data["keys"]:
45 if d["kid"] == kid:
46 alg = d.get("alg", "RS256")
47 algorithm = algorithms.get(alg)
48 if not algorithm:
49 raise OAuth2Error(f"Unsupported signing algorithm: {d['alg']}")
50 public_key = algorithm.from_jwk(json.dumps(d))
51 return public_key
52
53
54 def fetch_key(credential, keys_url, lookup):
55 header = jwt.get_unverified_header(credential)
56 # {'alg': 'RS256', 'kid': '0ad1fec78504f447bae65bcf5afaedb65eec9e81', 'typ': 'JWT'}
57 kid = header["kid"]
58 alg = header["alg"]
59 with get_adapter().get_requests_session() as sess:
60 response = sess.get(keys_url)
61 response.raise_for_status()
62 keys_data = response.json()
63 key = lookup(keys_data, kid)
64 if not key:
65 raise OAuth2Error(f"Invalid 'kid': '{kid}'")
66 return alg, key
67
68
69 def verify_jti(data: dict) -> None:
70 """
71 Put the JWT token on a blacklist to prevent replay attacks.
72 """
73 iss = data.get("iss")
74 exp = data.get("exp")
75 jti = data.get("jti")
76 if iss is None or exp is None or jti is None:
77 return
78 timeout = exp - time.time()
79 key = f"jwt:iss={iss},jti={jti}"
80 if not cache.add(key=key, value=True, timeout=timeout):
81 raise OAuth2Error("token already used")
82
83
84 def verify_and_decode(
85 *, credential, keys_url, issuer, audience, lookup_kid, verify_signature: bool = True
86 ) -> dict:
87 try:
88 if verify_signature:
89 alg, key = fetch_key(credential, keys_url, lookup_kid)
90 algorithms = [alg]
91 else:
92 key = ""
93 algorithms = None
94 data = jwt.decode(
95 credential,
96 key=key,
97 options={
98 "verify_signature": verify_signature,
99 "verify_iss": True,
100 "verify_aud": True,
101 "verify_exp": True,
102 },
103 issuer=issuer,
104 audience=audience,
105 algorithms=algorithms,
106 )
107 verify_jti(data)
108 return data
109 except jwt.PyJWTError as e:
110 raise OAuth2Error("Invalid id_token") from e