Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add iss to JWT tokens (#10842)
Maciej Korycinski2a59d31fc839
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84974c184c..8758981288 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add base shipping price to `Order` - #10771 by @fowczarek- Add new field `audience` to App manifest. If provided, App's JWT access token will have `aud` field. - #10845 by @korycins- GraphQL view no longer generates error logs when the HTTP request doesn't contain a GraphQL query - #10901 by @NyanKiyoshi+- Add `iss` field to JWT tokens - #10842 by @korycins### GraphQL APIdiff --git a/saleor/core/jwt.py b/saleor/core/jwt.pyindex 98fbd78190..347768dcd2 100644--- a/saleor/core/jwt.py+++ b/saleor/core/jwt.py@@ -30,7 +30,12 @@ def jwt_base_payload(exp_delta: Optional[timedelta], token_owner: str) -> Dict[str, Any]:utc_now = datetime.utcnow()- payload = {"iat": utc_now, JWT_OWNER_FIELD: token_owner}++ payload = {+ "iat": utc_now,+ JWT_OWNER_FIELD: token_owner,+ "iss": get_jwt_manager().get_issuer(),+ }if exp_delta:payload["exp"] = utc_now + exp_deltareturn payloaddiff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.pyindex c9dbc12269..916c24af3c 100644--- a/saleor/core/jwt_manager.py+++ b/saleor/core/jwt_manager.py@@ -7,12 +7,16 @@ import jwtfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom django.conf import settings+from django.contrib.sites.models import Sitefrom django.core.exceptions import ImproperlyConfiguredfrom django.core.management.color import color_style+from django.urls import reversefrom django.utils.module_loading import import_stringfrom jwt import api_jwsfrom jwt.algorithms import RSAAlgorithm+from .utils import build_absolute_uri+logger = logging.getLogger(__name__)PUBLIC_KEY: Optional[rsa.RSAPublicKey] = None@@ -20,6 +24,10 @@ KID = "1"class JWTManagerBase:+ @classmethod+ def get_domain(cls) -> str:+ return NotImplemented+@classmethoddef get_private_key(cls) -> rsa.RSAPrivateKey:return NotImplemented@@ -50,10 +58,18 @@ class JWTManagerBase:def get_jwks(cls) -> dict:return NotImplemented+ @classmethod+ def get_issuer(cls) -> str:+ return NotImplemented+class JWTManager(JWTManagerBase):KEY_FILE_FOR_DEBUG = ".jwt_key.pem"+ @classmethod+ def get_domain(cls) -> str:+ return Site.objects.get_current().domain+@classmethoddef get_private_key(cls) -> rsa.RSAPrivateKey:pem = settings.RSA_PRIVATE_KEY@@ -174,6 +190,10 @@ class JWTManager(JWTManagerBase):except Exception as e:raise ImproperlyConfigured(f"Unable to load provided PEM private key. {e}")+ @classmethod+ def get_issuer(cls) -> str:+ return build_absolute_uri(reverse("api"), domain=cls.get_domain())+def get_jwt_manager() -> JWTManagerBase:return import_string(settings.JWT_MANAGER_PATH)diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex e9515fe74a..23d55f9974 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -223,6 +223,18 @@ def test_build_absolute_uri(site_settings, settings):assert logo_url == logo_location+def test_build_absolute_uri_with_host(site_settings, settings):+ # given+ host = "test.com"+ location = "images/close.svg"++ # when+ url = build_absolute_uri(location, host)++ # then+ assert url == f"http://{host}/{location}"++def test_delete_sort_order_with_null_value(menu_item):"""Ensures there is no error when trying to delete a sortable item,which triggers a shifting of the sort orders--which can be null."""diff --git a/saleor/core/tests/test_jwt.py b/saleor/core/tests/test_jwt.pyindex 68dea816ba..bafc1c03d7 100644--- a/saleor/core/tests/test_jwt.py+++ b/saleor/core/tests/test_jwt.py@@ -1,9 +1,11 @@import grapheneimport jwtfrom cryptography.hazmat.primitives import serialization+from django.urls import reversefrom ...tests.consts import TEST_SERVER_DOMAINfrom ..jwt import create_access_token_for_app_extension, jwt_decode, jwt_encode+from ..utils import build_absolute_uridef test_create_access_token_for_app_extension_staff_user_with_more_permissions(@@ -44,6 +46,7 @@ def test_create_access_token_for_app_extension_staff_user_with_more_permissions()assert int(decode_extension_id) == extension.idassert decoded_token["aud"] == audience+ assert decoded_token["iss"] == build_absolute_uri(reverse("api"))def test_create_access_token_for_app_extension_with_more_permissions(diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex e048e16c5b..19fb10d989 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -22,13 +22,13 @@ if TYPE_CHECKING:from django.utils.safestring import SafeText-def build_absolute_uri(location: str) -> Optional[str]:+def build_absolute_uri(location: str, domain: Optional[str] = None) -> str:"""Create absolute uri from location.If provided location is absolute uri by itself, it returns unchanged value,otherwise if provided location is relative, absolute uri is built and returned."""- host = Site.objects.get_current().domain+ host = domain or Site.objects.get_current().domainprotocol = "https" if settings.ENABLE_SSL else "http"current_uri = "%s://%s" % (protocol, host)location = urljoin(current_uri, location)diff --git a/saleor/graphql/account/tests/mutations/test_token_create.py b/saleor/graphql/account/tests/mutations/test_token_create.pyindex d469383d47..784a560aa7 100644--- a/saleor/graphql/account/tests/mutations/test_token_create.py+++ b/saleor/graphql/account/tests/mutations/test_token_create.py@@ -1,6 +1,7 @@from datetime import datetime, timedelta, timezoneimport graphene+from django.urls import reversefrom freezegun import freeze_timefrom .....account.error_codes import AccountErrorCode@@ -10,6 +11,7 @@ from .....core.jwt import (create_refresh_token,jwt_decode,)+from .....core.utils import build_absolute_urifrom ....tests.utils import get_graphql_contentfrom ...mutations.authentication import _get_new_csrf_token@@ -66,6 +68,7 @@ def test_create_token(api_client, customer_user, settings):assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetimeassert payload["type"] == JWT_REFRESH_TYPEassert payload["token"] == customer_user.jwt_token_key+ assert payload["iss"] == build_absolute_uri(reverse("api"))@freeze_time("2020-03-18 12:00:00")@@ -217,3 +220,4 @@ def test_create_token_active_user_logged_before(api_client, customer_user, settiassert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetimeassert payload["type"] == JWT_REFRESH_TYPEassert payload["token"] == customer_user.jwt_token_key+ assert payload["iss"] == build_absolute_uri(reverse("api"))diff --git a/saleor/graphql/account/tests/mutations/test_token_refresh.py b/saleor/graphql/account/tests/mutations/test_token_refresh.pyindex f63cc18254..3e52d6bb9e 100644--- a/saleor/graphql/account/tests/mutations/test_token_refresh.py+++ b/saleor/graphql/account/tests/mutations/test_token_refresh.py@@ -1,5 +1,6 @@from datetime import datetime+from django.urls import reversefrom freezegun import freeze_timefrom .....account.error_codes import AccountErrorCode@@ -11,6 +12,7 @@ from .....core.jwt import (create_refresh_token,jwt_decode,)+from .....core.utils import build_absolute_urifrom ....tests.utils import get_graphql_contentfrom ...mutations.authentication import _get_new_csrf_token@@ -83,6 +85,7 @@ def test_refresh_token_get_token_from_cookie(api_client, customer_user, settings)assert payload["type"] == JWT_ACCESS_TYPEassert payload["token"] == customer_user.jwt_token_key+ assert payload["iss"] == build_absolute_uri(reverse("api"))@freeze_time("2020-03-18 12:00:00")diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 4f0ed1aa3e..a5115c65aa 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -5,6 +5,7 @@ from unittest.mock import ANY, patchimport grapheneimport pytestimport pytz+from django.contrib.sites.models import Sitefrom django.db.models.aggregates import Sumfrom django.utils import timezonefrom prices import Money@@ -769,6 +770,7 @@ def test_checkout_complete_requires_confirmation():site_settings.automatically_confirm_all_new_orders = Falsesite_settings.save()+ Site.objects.clear_cache()payment = payment_dummypayment.checkout = checkout_ready_to_completepayment.save()diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 65d345bca8..5fd83328cd 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -8,6 +8,7 @@ import before_afterimport grapheneimport pytestimport pytz+from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.core.files import Filefrom django.db import transaction@@ -937,6 +938,7 @@ def test_product_query_by_id_weight_returned_in_default_unit(site_settings.default_weight_unit = WeightUnits.LBsite_settings.save(update_fields=["default_weight_unit"])+ Site.objects.clear_cache()variables = {"id": graphene.Node.to_global_id("Product", product.pk),@@ -4531,6 +4533,7 @@ def test_product_type_query_by_id_weight_returned_in_default_unit(site_settings.default_weight_unit = WeightUnits.OZsite_settings.save(update_fields=["default_weight_unit"])+ Site.objects.clear_cache()variables = {"id": graphene.Node.to_global_id("ProductType", product_type.pk)}diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex efd15ff735..afbdf76030 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -6,6 +6,7 @@ from uuid import uuid4import grapheneimport pytestimport pytz+from django.contrib.sites.models import Sitefrom django.utils.text import slugifyfrom freezegun import freeze_timefrom measurement.measures import Weight@@ -98,6 +99,7 @@ def test_fetch_variant(product,permission_manage_products,site_settings,+ settings,channel_USD,):# given@@ -108,6 +110,7 @@ def test_fetch_variant(site_settings.default_weight_unit = WeightUnits.Gsite_settings.save(update_fields=["default_weight_unit"])+ Site.objects.clear_cache()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)variables = {"id": variant_id, "countryCode": "EU", "channel": channel_USD.slug}@@ -154,6 +157,7 @@ def test_fetch_variant_no_stocks(site_settings.default_weight_unit = WeightUnits.Gsite_settings.save(update_fields=["default_weight_unit"])+ Site.objects.clear_cache()warehouse = variant.stocks.first().warehouse# remove the warehouse channelsdiff --git a/saleor/graphql/shipping/tests/test_shipping_zones_query.py b/saleor/graphql/shipping/tests/test_shipping_zones_query.pyindex b09c5ce0ff..ca852fcad0 100644--- a/saleor/graphql/shipping/tests/test_shipping_zones_query.py+++ b/saleor/graphql/shipping/tests/test_shipping_zones_query.py@@ -1,5 +1,6 @@import grapheneimport pytest+from django.contrib.sites.models import Sitefrom measurement.measures import Weightfrom ....core.units import WeightUnits@@ -96,6 +97,7 @@ def test_shipping_zone_query_weights_returned_in_default_unit(site_settings.default_weight_unit = WeightUnits.Gsite_settings.save(update_fields=["default_weight_unit"])+ Site.objects.clear_cache()query = SHIPPING_ZONE_QUERYID = graphene.Node.to_global_id("ShippingZone", shipping.id)diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 7f2cfd2e44..13a88caee0 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -680,6 +680,7 @@ def test_shop_customer_set_password_url_update(content = get_graphql_content(response)data = content["data"]["shopSettingsUpdate"]assert not data["errors"]+ Site.objects.clear_cache()site_settings = Site.objects.get_current().settingsassert site_settings.customer_set_password_url == customer_set_password_url