Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Use public key thumbprint as KID in JWKS.json (#13442)
Cezary Miącza24c91626a76
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7aaac4024c..8fb24aa10b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -82,6 +82,7 @@ Shipping methods can be removed by the user after it has been assigned to a chec- Called when metadata is changed for the Shop object via the generic metadata API or the `shopSettingsUpdate` mutation.### Other changes+- Use public key thumbprint as KID in JWKS.json #13442 by @cmiacz- Add POC of Core API tests - #13034 by @fowczarek- Expand metric units to support more types of products. - #13043 by @FremahAdiff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.pyindex 48955dcf25..f616e080b1 100644--- a/saleor/core/jwt_manager.py+++ b/saleor/core/jwt_manager.py@@ -4,6 +4,7 @@ from os.path import exists, joinfrom typing import Optional, Union, castimport jwt+from authlib.jose import JsonWebKeyfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom django.conf import settings@@ -20,7 +21,6 @@ from .utils import build_absolute_urilogger = logging.getLogger(__name__)PUBLIC_KEY: Optional[rsa.RSAPublicKey] = None-KID = "1"class JWTManagerBase:@@ -58,6 +58,10 @@ class JWTManagerBase:def get_jwks(cls) -> dict:return NotImplemented+ @classmethod+ def get_key_id(cls) -> str:+ return NotImplemented+@classmethoddef get_issuer(cls) -> str:return NotImplemented@@ -138,16 +142,30 @@ class JWTManager(JWTManagerBase):@classmethoddef get_jwks(cls) -> dict:jwk_dict = json.loads(RSAAlgorithm.to_jwk(cls.get_public_key()))- jwk_dict.update({"use": "sig", "kid": KID})+ jwk_dict.update({"use": "sig", "kid": cls.get_key_id()})return {"keys": [jwk_dict]}+ @classmethod+ def get_key_id(cls) -> str:+ """Generate JWT key ID for the public key.++ This generates a "thumbprint" as 'kid' field using RFC 7638 implementation+ based on the RSA public key.+ """+ public_key_pem = cls.get_public_key().public_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ jwk = JsonWebKey.import_key(public_key_pem)+ return jwk.thumbprint()+@classmethoddef encode(cls, payload):return jwt.encode(payload,cls.get_private_key(), # type: ignore[arg-type] # key is typed as str for all algos # noqa: E501algorithm="RS256",- headers={"kid": KID},+ headers={"kid": cls.get_key_id()},)@classmethod@@ -156,7 +174,7 @@ class JWTManager(JWTManagerBase):payload,key=cls.get_private_key(), # type: ignore[arg-type] # key is typed as str for all algos # noqa: E501algorithm="RS256",- headers={"kid": KID},+ headers={"kid": cls.get_key_id()},is_payload_detached=is_payload_detached,)