Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add optional audience field to JWT tokens (#10845)
Maciej Korycinski230490df1022
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38b69f9c37..164e1abd7f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,13 +10,14 @@ All notable, unreleased changes to this project will be documented in this file.- Deprecated `slug` in filter for `menus`. Use `slugs` instead- Add ability to filter payments by list of ids. #10821 by @kadewu- Add ability to filter customers by ids. #10694 by @kadewu+- Add optional field `audience` to mutation `tokenCreate`. If provided, the created tokens will have key `aud` with value: `custom:{audience-input-value}` - #10845 by @korycins- Use `AttributeValue.name` instead of `AttributeValue.slug` to determine uniqueness of a value instance for dropdown and multiselect attributes. - #10881 by @jakubkuc### Other changes- Reference attribute linking to product variants - #10468 by @IKarbowiak- 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 API- Add `taxExemptionManage` mutation - #10344 by @SzymJdiff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 91d829c6a6..7a372846bb 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -67,6 +67,7 @@ def install_app(app_installation: AppInstallation, activate: bool = False):version=manifest_data.get("version"),manifest_url=app_installation.manifest_url,type=AppType.THIRDPARTY,+ audience=manifest_data.get("audience"),)app.permissions.set(app_installation.permissions.all())for extension_data in manifest_data.get("extensions", []):diff --git a/saleor/app/migrations/0017_app_audience.py b/saleor/app/migrations/0017_app_audience.pynew file mode 100644index 0000000000..8a88c198fd--- /dev/null+++ b/saleor/app/migrations/0017_app_audience.py@@ -0,0 +1,18 @@+# Generated by Django 4.0.8 on 2022-10-06 11:29++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("app", "0016_alter_appextension_mount"),+ ]++ operations = [+ migrations.AddField(+ model_name="app",+ name="audience",+ field=models.CharField(blank=True, max_length=256, null=True),+ ),+ ]diff --git a/saleor/app/models.py b/saleor/app/models.pyindex e163961686..0603dd40b9 100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@ -56,7 +56,7 @@ class App(ModelWithMetadata):app_url = models.URLField(blank=True, null=True)manifest_url = models.URLField(blank=True, null=True)version = models.CharField(max_length=60, blank=True, null=True)-+ audience = models.CharField(blank=True, null=True, max_length=256)objects = models.Manager.from_queryset(AppQueryset)()class Meta(ModelWithMetadata.Meta):diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex 725b88655c..901b3f6c80 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -8,6 +8,7 @@ from django.core.exceptions import ValidationErrorfrom freezegun import freeze_timefrom ...core.utils.json_serializer import CustomJsonEncoder+from ...tests.consts import TEST_SERVER_DOMAINfrom ...webhook.event_types import WebhookEventAsyncTypefrom ...webhook.payloads import generate_meta, generate_requestorfrom ..installation_utils import (@@ -61,6 +62,25 @@ def test_install_app_created_app(assert list(app.permissions.all()) == [permission_manage_products]+def test_install_app_created_app_with_audience(+ app_manifest, app_installation, monkeypatch+):+ # given+ audience = f"https://{TEST_SERVER_DOMAIN}.com/app-123"+ app_manifest["audience"] = audience+ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest++ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())++ # when+ app, _ = install_app(app_installation, activate=True)++ # then+ assert app.audience == audience++@freeze_time("2022-05-12 12:00:00")@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")diff --git a/saleor/core/jwt.py b/saleor/core/jwt.pyindex 6eed641e8c..98fbd78190 100644--- a/saleor/core/jwt.py+++ b/saleor/core/jwt.py@@ -73,9 +73,11 @@ def jwt_decode_with_exception_handler(return None-def jwt_decode(token: str, verify_expiration=settings.JWT_EXPIRE) -> Dict[str, Any]:+def jwt_decode(+ token: str, verify_expiration=settings.JWT_EXPIRE, verify_aud: bool = False+) -> Dict[str, Any]:jwt_manager = get_jwt_manager()- return jwt_manager.decode(token, verify_expiration)+ return jwt_manager.decode(token, verify_expiration, verify_aud=verify_aud)def create_token(payload: Dict[str, Any], exp_delta: timedelta) -> str:@@ -157,6 +159,7 @@ def _create_access_token_for_third_party_actions(type: str,object_id: int,object_payload_key: str,+ audience: Optional[str],):app_permission_enums = get_permission_names(permissions)@@ -167,6 +170,8 @@ def _create_access_token_for_third_party_actions(PERMISSIONS_FIELD: list(app_permission_enums & user_permission_enums),USER_PERMISSION_FIELD: list(user_permission_enums),}+ if audience:+ additional_payload["aud"] = audiencepayload = jwt_user_payload(user,@@ -192,11 +197,15 @@ def create_access_token_for_app(app: "App", user: "User"):type="App",object_id=app.id,object_payload_key="app",+ audience=app.audience,)def create_access_token_for_app_extension(- app_extension: "AppExtension", permissions: Iterable["Permission"], user: "User"+ app_extension: "AppExtension",+ permissions: Iterable["Permission"],+ user: "User",+ app: "App",):return _create_access_token_for_third_party_actions(permissions=permissions,@@ -204,4 +213,5 @@ def create_access_token_for_app_extension(type="AppExtension",object_id=app_extension.id,object_payload_key="app_extension",+ audience=app.audience,)diff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.pyindex 8647b8ebe4..c9dbc12269 100644--- a/saleor/core/jwt_manager.py+++ b/saleor/core/jwt_manager.py@@ -37,7 +37,9 @@ class JWTManagerBase:return NotImplemented@classmethod- def decode(cls, token: str, verify_expiration: bool = True) -> dict:+ def decode(+ cls, token: str, verify_expiration: bool = True, verify_aud: bool = False+ ) -> dict:return NotImplemented@classmethod@@ -134,20 +136,22 @@ class JWTManager(JWTManagerBase):)@classmethod- def decode(cls, token, verify_expiration: bool = True):+ def decode(cls, token, verify_expiration: bool = True, verify_aud: bool = False):+ # `verify_aud` set to false as we decode our own tokens+ # we can have `aud` defined for app or custom.headers = jwt.get_unverified_header(token)if headers.get("alg") == "RS256":return jwt.decode(token,cls.get_public_key(), # type: ignorealgorithms=["RS256"],- options={"verify_exp": verify_expiration},+ options={"verify_exp": verify_expiration, "verify_aud": verify_aud},)return jwt.decode(token,settings.SECRET_KEY, # type: ignorealgorithms=["HS256"],- options={"verify_exp": verify_expiration},+ options={"verify_exp": verify_expiration, "verify_aud": verify_aud},)@classmethoddiff --git a/saleor/core/tests/test_jwt.py b/saleor/core/tests/test_jwt.pyindex aa90d849a8..68dea816ba 100644--- a/saleor/core/tests/test_jwt.py+++ b/saleor/core/tests/test_jwt.py@@ -2,6 +2,7 @@ import grapheneimport jwtfrom cryptography.hazmat.primitives import serialization+from ...tests.consts import TEST_SERVER_DOMAINfrom ..jwt import create_access_token_for_app_extension, jwt_decode, jwt_encode@@ -16,7 +17,11 @@ def test_create_access_token_for_app_extension_staff_user_with_more_permissions(staff_user.user_permissions.set([permission_manage_channels, permission_manage_apps, permission_manage_products])+ audience = f"https://{TEST_SERVER_DOMAIN}.com/app-123"app, extensions = app_with_extensions+ app.audience = audience+ app.save()+extension = extensions[0]extension.permissions.set([permission_manage_products])@@ -25,10 +30,11 @@ def test_create_access_token_for_app_extension_staff_user_with_more_permissions(app_extension=extension,permissions=extension.permissions.all(),user=staff_user,+ app=app,)# then- decoded_token = jwt_decode(access_token, verify_expiration=False)+ decoded_token = jwt_decode(access_token, verify_expiration=False, verify_aud=False)assert decoded_token["permissions"] == ["MANAGE_PRODUCTS"]_, decode_extension_id = graphene.Node.from_global_id(decoded_token["app_extension"]@@ -37,6 +43,7 @@ def test_create_access_token_for_app_extension_staff_user_with_more_permissions(["MANAGE_CHANNELS", "MANAGE_APPS", "MANAGE_PRODUCTS"])assert int(decode_extension_id) == extension.id+ assert decoded_token["aud"] == audiencedef test_create_access_token_for_app_extension_with_more_permissions(@@ -48,7 +55,12 @@ def test_create_access_token_for_app_extension_with_more_permissions():# givenstaff_user.user_permissions.set([permission_manage_products])++ audience = f"https://{TEST_SERVER_DOMAIN}.com/app-123"app, extensions = app_with_extensions+ app.audience = audience+ app.save()+extension = extensions[0]extension.permissions.set([permission_manage_channels, permission_manage_apps, permission_manage_products]@@ -59,6 +71,7 @@ def test_create_access_token_for_app_extension_with_more_permissions(app_extension=extension,permissions=extension.permissions.all(),user=staff_user,+ app=app,)# then@@ -69,6 +82,7 @@ def test_create_access_token_for_app_extension_with_more_permissions()assert decoded_token["user_permissions"] == ["MANAGE_PRODUCTS"]assert int(decode_extension_id) == extension.id+ assert decoded_token["aud"] == audiencedef test_jwt_decode_accepts_token_signed_with_hs256(settings):@@ -98,6 +112,29 @@ def test_jwt_decode_accepts_token_signed_with_rs256(settings):assert payload == decoded_token+def test_jwt_decode_accepts_app_token_rs256_with_audience(settings):+ # given+ private_key = serialization.load_pem_private_key(+ settings.RSA_PRIVATE_KEY.encode("utf-8"), password=settings.RSA_PRIVATE_PASSWORD+ )+ payload = {"1": "A", "2": "B", "aud": "tmp"}+ token = jwt.encode(payload, private_key, algorithm="RS256")++ # when & then+ # expected to not raise an exception+ jwt_decode(token)+++def test_jwt_decode_accepts_app_token_hs256_with_audience(settings):+ # given+ payload = {"1": "A", "2": "B", "aud": "tmp"}+ token = jwt.encode(payload, settings.SECRET_KEY, algorithm="HS256")++ # when & then+ # expected to not raise an exception+ jwt_decode(token)++def test_jwt_encode_creates_token_signed_with_rs256(settings):# givenpayload = {"1": "A", "2": "B"}diff --git a/saleor/graphql/account/mutations/authentication.py b/saleor/graphql/account/mutations/authentication.pyindex 83a192c56d..bfdfd2e69b 100644--- a/saleor/graphql/account/mutations/authentication.py+++ b/saleor/graphql/account/mutations/authentication.py@@ -24,6 +24,7 @@ from ....core.jwt import (jwt_decode,)from ....core.permissions import AuthorizationFilters, get_permissions_from_names+from ...core.descriptions import ADDED_IN_38, PREVIEW_FEATUREfrom ...core.fields import JSONStringfrom ...core.mutations import BaseMutationfrom ...core.types import AccountError@@ -81,6 +82,13 @@ class CreateToken(BaseMutation):class Arguments:email = graphene.String(required=True, description="Email of a user.")password = graphene.String(required=True, description="Password of a user.")+ audience = graphene.String(+ required=False,+ description=(+ "The audience that will be included to JWT tokens with "+ "prefix `custom:`." + ADDED_IN_38 + PREVIEW_FEATURE+ ),+ )class Meta:description = "Create JWT token."@@ -139,9 +147,20 @@ class CreateToken(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):user = cls.get_user(info, data)- access_token = create_access_token(user)+ additional_paylod = {}+csrf_token = _get_new_csrf_token()- refresh_token = create_refresh_token(user, {"csrfToken": csrf_token})+ refresh_additional_payload = {+ "csrfToken": csrf_token,+ }+ if audience := data.get("audience"):+ additional_paylod["aud"] = f"custom:{audience}"+ refresh_additional_payload["aud"] = f"custom:{audience}"++ access_token = create_access_token(user, additional_payload=additional_paylod)+ refresh_token = create_refresh_token(+ user, additional_payload=refresh_additional_payload+ )info.context.refresh_token = refresh_tokeninfo.context._cached_user = useruser.last_login = timezone.now()@@ -261,7 +280,10 @@ class RefreshToken(BaseMutation):cls.clean_csrf_token(csrf_token, payload)user = get_user(payload)- token = create_access_token(user)+ additional_payload = {}+ if audience := payload.get("aud"):+ additional_payload["aud"] = audience+ token = create_access_token(user, additional_payload=additional_payload)return cls(errors=[], user=user, token=token)diff --git a/saleor/graphql/account/tests/mutations/test_token_create.py b/saleor/graphql/account/tests/mutations/test_token_create.pyindex fb5f2ff539..d469383d47 100644--- a/saleor/graphql/account/tests/mutations/test_token_create.py+++ b/saleor/graphql/account/tests/mutations/test_token_create.py@@ -14,8 +14,8 @@ from ....tests.utils import get_graphql_contentfrom ...mutations.authentication import _get_new_csrf_tokenMUTATION_CREATE_TOKEN = """- mutation tokenCreate($email: String!, $password: String!){- tokenCreate(email: $email, password: $password) {+ mutation tokenCreate($email: String!, $password: String!, $audience: String){+ tokenCreate(email: $email, password: $password, audience: $audience) {tokenrefreshTokencsrfToken@@ -68,6 +68,45 @@ def test_create_token(api_client, customer_user, settings):assert payload["token"] == customer_user.jwt_token_key+@freeze_time("2020-03-18 12:00:00")+def test_create_token_with_audience(api_client, customer_user, settings):+ audience = "dashboard"+ variables = {+ "email": customer_user.email,+ "password": customer_user._password,+ "audience": audience,+ }+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)+ content = get_graphql_content(response)++ data = content["data"]["tokenCreate"]++ user_email = data["user"]["email"]+ assert customer_user.email == user_email+ assert content["data"]["tokenCreate"]["errors"] == []++ token = data["token"]+ refreshToken = data["refreshToken"]++ payload = jwt_decode(token)+ assert payload["email"] == customer_user.email+ assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()+ expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_ACCESS+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime+ assert payload["type"] == JWT_ACCESS_TYPE+ assert payload["aud"] == f"custom:{audience}"++ payload = jwt_decode(refreshToken)+ assert payload["email"] == customer_user.email+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()+ expected_expiration_datetime = datetime.utcnow() + settings.JWT_TTL_REFRESH+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime+ assert payload["type"] == JWT_REFRESH_TYPE+ assert payload["token"] == customer_user.jwt_token_key+ assert payload["aud"] == f"custom:{audience}"++@freeze_time("2020-03-18 12:00:00")def test_create_token_sets_cookie(api_client, customer_user, settings, monkeypatch):csrf_token = _get_new_csrf_token()diff --git a/saleor/graphql/account/tests/mutations/test_token_refresh.py b/saleor/graphql/account/tests/mutations/test_token_refresh.pyindex 5151e8f05e..f63cc18254 100644--- a/saleor/graphql/account/tests/mutations/test_token_refresh.py+++ b/saleor/graphql/account/tests/mutations/test_token_refresh.py@@ -27,6 +27,37 @@ MUTATION_TOKEN_REFRESH = """"""+@freeze_time("2020-03-18 12:00:00")+def test_refresh_token_with_audience(api_client, customer_user, settings):+ csrf_token = _get_new_csrf_token()+ token_audience = "custom:dashboard"+ refresh_token = create_refresh_token(+ customer_user, {"csrfToken": csrf_token, "aud": token_audience}+ )+ variables = {"token": None, "csrf_token": csrf_token}+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)+ content = get_graphql_content(response)++ data = content["data"]["tokenRefresh"]+ errors = data["errors"]++ assert not errors+ token = data.get("token")+ assert token+ payload = jwt_decode(token)+ assert payload["email"] == customer_user.email+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()+ assert (+ datetime.fromtimestamp(payload["exp"])+ == datetime.utcnow() + settings.JWT_TTL_ACCESS+ )+ assert payload["type"] == JWT_ACCESS_TYPE+ assert payload["token"] == customer_user.jwt_token_key+ assert payload["aud"] == token_audience++@freeze_time("2020-03-18 12:00:00")def test_refresh_token_get_token_from_cookie(api_client, customer_user, settings):csrf_token = _get_new_csrf_token()diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.pyindex 17c91872c2..f67364cab5 100644--- a/saleor/graphql/app/mutations.py+++ b/saleor/graphql/app/mutations.py@@ -479,6 +479,7 @@ class AppFetchManifest(BaseMutation):permissions=cleaned_data.get("permissions"),extensions=cleaned_data.get("extensions", []),webhooks=cleaned_data.get("webhooks", []),+ audience=cleaned_data.get("audience"),)@classmethoddiff --git a/saleor/graphql/app/resolvers.py b/saleor/graphql/app/resolvers.pyindex aa5dddeaee..38e4d410ac 100644--- a/saleor/graphql/app/resolvers.py+++ b/saleor/graphql/app/resolvers.py@@ -29,7 +29,7 @@ def resolve_access_token_for_app(info, root):return create_access_token_for_app(root, user)-def resolve_access_token_for_app_extension(info, root):+def resolve_access_token_for_app_extension(info, root, app):user = info.context.userif not user_is_valid(user):return None@@ -37,7 +37,7 @@ def resolve_access_token_for_app_extension(info, root):user_permissions = user.effective_permissionsif set(extension_permissions).issubset(user_permissions):return create_access_token_for_app_extension(- app_extension=root, permissions=extension_permissions, user=user+ app_extension=root, permissions=extension_permissions, user=user, app=app)return Nonediff --git a/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_app_fetch_manifest_with_audience.yaml b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_app_fetch_manifest_with_audience.yamlnew file mode 100644index 0000000000..5c52209675--- /dev/null+++ b/saleor/graphql/app/tests/mutations/cassettes/test_app_fetch_manifest/test_app_fetch_manifest_with_audience.yaml@@ -0,0 +1,53 @@+interactions:+- request:+ body: null+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate+ Connection:+ - keep-alive+ User-Agent:+ - python-requests/2.23.0+ method: GET+ uri: http://localhost:3000/manifest+ response:+ body:+ string: "{\n \"name\": \"app\", \"audience\": \"http://localhost:8888/app\", \n \"version\": \"1.0.0\",\n \"about\": \"\+ Lorem ipsum\",\n \"dataPrivacy\": \"Lorem ipsum\",\n \"dataPrivacyUrl\"\+ : \"http://localhost:8888/app-data-privacy\",\n \"homepageUrl\": \"http://localhost:8888/homepage\"\+ ,\n \"supportUrl\": \"http://localhost:8888/support\",\n \"configurationUrl\"\+ : \"htpp://localhost:8888/configuration\",\n \"appUrl\": \"http://localhost:8888/app\"\+ ,\n \"tokenTargetUrl\": \"http://localhost:3000/register\",\n \"id\": \"\+ app2\",\n \"permissions\": [\n \"MANAGE_USERS\",\n \"MANAGE_ORDERS\"\+ \n ]\n}"+ headers:+ Access-Control-Allow-Credentials:+ - 'true'+ Cache-Control:+ - no-cache+ Connection:+ - keep-alive+ Content-Length:+ - '497'+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Tue, 26 May 2020 11:13:49 GMT+ ETag:+ - W/"1f1-oiRdlJBgfkdPvTIg7KJUq8+ZGPA"+ Expires:+ - '-1'+ Pragma:+ - no-cache+ Vary:+ - Origin, Accept-Encoding+ X-Content-Type-Options:+ - nosniff+ X-Powered-By:+ - Express+ status:+ code: 200+ message: OK+version: 1diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.pyindex 9bc13653e3..59f23fb9d6 100644--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py@@ -24,6 +24,7 @@ mutation AppFetchManifest($manifest_url: String!){permissions{code}+ audienceextensions{labelurl@@ -78,6 +79,27 @@ def test_app_fetch_manifest(staff_api_client, staff_user, permission_manage_apps}+def test_app_fetch_manifest_with_audience(+ staff_api_client, staff_user, permission_manage_apps+):+ manifest_url = "http://localhost:3000/manifest"+ query = APP_FETCH_MANIFEST_MUTATION+ variables = {+ "manifest_url": manifest_url,+ }+ staff_user.user_permissions.set([permission_manage_apps])+ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ )+ content = get_graphql_content(response)+ errors = content["data"]["appFetchManifest"]["errors"]+ manifest = content["data"]["appFetchManifest"]["manifest"]+ assert not errors+ assert manifest["audience"] == "http://localhost:8888/app"++def test_app_fetch_manifest_missing_permission(staff_api_client, staff_user):manifest_url = "http://localhost:3000/manifest"query = APP_FETCH_MANIFEST_MUTATIONdiff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.pyindex b552841485..b78ff6e75b 100644--- a/saleor/graphql/app/tests/queries/test_app.py+++ b/saleor/graphql/app/tests/queries/test_app.py@@ -4,7 +4,8 @@ from freezegun import freeze_timefrom .....app.models import Appfrom .....app.types import AppType-from .....core.jwt import create_access_token_for_app+from .....core.jwt import create_access_token_for_app, jwt_decode+from .....tests.consts import TEST_SERVER_DOMAINfrom ....tests.utils import assert_no_permission, get_graphql_contentQUERY_APP = """@@ -396,6 +397,36 @@ def test_app_query_for_staff_without_manage_apps(assert app_data["accessToken"] is None+@freeze_time("2012-01-14 11:00:00")+def test_app_query_access_token_with_audience(+ staff_api_client,+ permission_manage_staff,+ external_app,+ webhook,+):+ app = external_app+ app.permissions.add(permission_manage_staff)+ app.audience = f"https://{TEST_SERVER_DOMAIN}.com/app-123"+ app.save()++ webhook = webhook+ webhook.app = app+ webhook.save()++ id = graphene.Node.to_global_id("App", app.id)+ variables = {"id": id}+ response = staff_api_client.post_graphql(+ QUERY_APP_AVAILABLE_FOR_STAFF_WITHOUT_MANAGE_APPS,+ variables,+ )+ content = get_graphql_content(response)++ app_data = content["data"]["app"]++ decoded_token = jwt_decode(app_data["accessToken"])+ assert decoded_token["aud"] == app.audience++def test_app_query_for_normal_user(user_api_client, permission_manage_users, permission_manage_staff, app):diff --git a/saleor/graphql/app/tests/queries/test_app_extension.py b/saleor/graphql/app/tests/queries/test_app_extension.pyindex 14de8a531d..78f7007a19 100644--- a/saleor/graphql/app/tests/queries/test_app_extension.py+++ b/saleor/graphql/app/tests/queries/test_app_extension.py@@ -3,6 +3,7 @@ import graphenefrom .....app.models import AppExtensionfrom .....app.types import AppExtensionMountfrom .....core.jwt import jwt_decode+from .....tests.consts import TEST_SERVER_DOMAINfrom ....tests.utils import assert_no_permission, get_graphql_contentQUERY_APP_EXTENSION = """@@ -177,6 +178,47 @@ def test_app_extension_staff_user_fetching_access_token()+def test_app_extension_access_token_with_audience(+ app,+ staff_api_client,+ permission_manage_orders,+ permission_manage_products,+ permission_manage_apps,+):+ # given+ app.audience = f"https://{TEST_SERVER_DOMAIN}.com/app-123"+ app.save()+ app_extension = AppExtension.objects.create(+ app=app,+ label="Create product with App",+ url="https://www.example.com/app-product",+ mount=AppExtensionMount.PRODUCT_OVERVIEW_MORE_ACTIONS,+ )+ app_extension.permissions.add(permission_manage_products, permission_manage_orders)+ id = graphene.Node.to_global_id("AppExtension", app_extension.id)+ variables = {"id": id}++ # when+ response = staff_api_client.post_graphql(+ QUERY_APP_EXTENSION,+ variables,+ permissions=[+ permission_manage_orders,+ permission_manage_products,+ permission_manage_apps,+ ],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ extension_data = content["data"]["appExtension"]++ assert extension_data["accessToken"]+ decoded_token = jwt_decode(extension_data["accessToken"])+ assert decoded_token["aud"] == app.audience++def test_app_extension_staff_user_partial_permission(app,staff_api_client,diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex edce2a08f5..c96c9fed11 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -16,6 +16,7 @@ from ..core.connection import CountableConnectionfrom ..core.descriptions import (ADDED_IN_31,ADDED_IN_35,+ ADDED_IN_38,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -148,8 +149,11 @@ class AppExtension(AppManifestExtension, ModelObjectType):return format_permissions_for_display(permissions)@staticmethod- def resolve_access_token(root: models.App, info):- return resolve_access_token_for_app_extension(info, root)+ def resolve_access_token(root: models.AppExtension, info):+ def _resolve_access_token(app):+ return resolve_access_token_for_app_extension(info, root, app)++ return AppByIdLoader(info.context).load(root.app_id).then(_resolve_access_token)class AppExtensionCountableConnection(CountableConnection):@@ -212,6 +216,13 @@ class Manifest(graphene.ObjectType):description="List of the app's webhooks." + ADDED_IN_35 + PREVIEW_FEATURE,required=True,)+ audience = graphene.String(+ description=(+ "The audience that will be included in all JWT tokens for the app."+ + ADDED_IN_38+ + PREVIEW_FEATURE+ )+ )class Meta:description = "The manifest definition."diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 1cebc7f2c9..a8989fc2a7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -14029,6 +14029,15 @@ type Mutation {"""Create JWT token."""tokenCreate(+ """+ The audience that will be included to JWT tokens with prefix `custom:`.++ Added in Saleor 3.8.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ audience: String+"""Email of a user."""email: String!@@ -20724,6 +20733,15 @@ type Manifest {Note: this API is currently in Feature Preview and can be subject to changes at later point."""webhooks: [AppManifestWebhook!]!++ """+ The audience that will be included in all JWT tokens for the app.++ Added in Saleor 3.8.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ audience: String}type AppManifestExtension {