Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add `Saleor-Schema-Version` header to app installation handshake (#13075)

Przemysław Ładabecbbdd78660
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46d2b98168..6a2e96791f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,11 +9,13 @@ All notable, unreleased changes to this project will be documented in this file.
### GraphQL API
### Saleor Apps
+- Introduce `Saleor-Schema-Version` HTTP header in app manifest fetching and app installation handshake requests. - #13075 by @przlada
### Other changes
- Expand metric units to support more types of products. - #13043 by @FremahA
- Fix Error Cannot return null for non-nullable field Webhook.name. - #12989 by @cyborg7898
+
# 3.14.0
### Breaking changes
diff --git a/saleor/__init__.py b/saleor/__init__.py
index 3dd1bcaa63..8c6fcbe53e 100644
--- a/saleor/__init__.py
+++ b/saleor/__init__.py
@@ -18,3 +18,7 @@ class PatchedSubscriberExecutionContext(object):
def __getattr__(self, name):
return getattr(self.exe_context, name)
+
+
+_major, _minor, _ = __version__.split(".", 2)
+schema_version = f"{_major}.{_minor}"
diff --git a/saleor/app/headers.py b/saleor/app/headers.py
index 09c4d9f443..3efb375a59 100644
--- a/saleor/app/headers.py
+++ b/saleor/app/headers.py
@@ -3,6 +3,7 @@ class AppHeaders:
EVENT_TYPE = "Saleor-Event"
SIGNATURE = "Saleor-Signature"
API_URL = "Saleor-Api-Url"
+ SCHEMA_VERSION = "Saleor-Schema-Version"
class DeprecatedAppHeaders:
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index e66360ed0e..ac38f353f0 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -15,6 +15,7 @@ from django.db import DatabaseError
from django.urls import reverse
from requests import HTTPError, Response
+from .. import schema_version
from ..app.headers import AppHeaders, DeprecatedAppHeaders
from ..celeryconf import app
from ..core.utils import build_absolute_uri
@@ -59,6 +60,7 @@ def send_app_token(target_url: str, token: str):
DeprecatedAppHeaders.DOMAIN: domain,
AppHeaders.DOMAIN: domain,
AppHeaders.API_URL: build_absolute_uri(reverse("api"), domain),
+ AppHeaders.SCHEMA_VERSION: schema_version,
}
json_data = {"auth_token": token}
response = requests.post(
@@ -185,13 +187,18 @@ def fetch_brand_data_async(
)
-def install_app(app_installation: AppInstallation, activate: bool = False):
+def fetch_manifest(manifest_url: str, timeout=REQUEST_TIMEOUT):
+ headers = {AppHeaders.SCHEMA_VERSION: schema_version}
response = requests.get(
- app_installation.manifest_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
+ manifest_url, headers=headers, timeout=timeout, allow_redirects=False
)
response.raise_for_status()
+ return response.json()
+
+
+def install_app(app_installation: AppInstallation, activate: bool = False):
+ manifest_data = fetch_manifest(app_installation.manifest_url)
assigned_permissions = app_installation.permissions.all()
- manifest_data = response.json()
manifest_data["permissions"] = get_permission_names(assigned_permissions)
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index 3bfe4eaf4d..ae3f2eee24 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -8,6 +8,7 @@ from django.core.management.base import CommandParser
from django.urls import reverse
from requests.exceptions import RequestException
+from .... import schema_version
from ....app.headers import AppHeaders, DeprecatedAppHeaders
from ....core.utils import build_absolute_uri
from ...models import App
@@ -48,6 +49,7 @@ class Command(BaseCommand):
DeprecatedAppHeaders.DOMAIN: domain,
AppHeaders.DOMAIN: domain,
AppHeaders.API_URL: build_absolute_uri(reverse("api"), domain),
+ AppHeaders.SCHEMA_VERSION: schema_version,
}
try:
response = requests.post(
diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.py
index e32208c08e..0400b5d4cc 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -1,14 +1,13 @@
import json
from typing import Any, Optional
-import requests
from django.core.exceptions import ValidationError
from django.core.management import BaseCommand, CommandError
from django.core.management.base import CommandParser
from ....app.validators import AppURLValidator
from ....core import JobStatus
-from ...installation_utils import install_app
+from ...installation_utils import fetch_manifest, install_app
from ...models import AppInstallation
from .utils import clean_permissions
@@ -32,17 +31,12 @@ class Command(BaseCommand):
except ValidationError:
raise CommandError(f"Incorrect format of manifest-url: {manifest_url}")
- def fetch_manifest_data(self, manifest_url: str) -> dict:
- response = requests.get(manifest_url, timeout=30, allow_redirects=False)
- response.raise_for_status()
- return response.json()
-
def handle(self, *args: Any, **options: Any) -> Optional[str]:
activate = options["activate"]
manifest_url = options["manifest-url"]
self.validate_manifest_url(manifest_url)
- manifest_data = self.fetch_manifest_data(manifest_url)
+ manifest_data = fetch_manifest(manifest_url)
permissions = clean_permissions(manifest_data.get("permissions", []))
diff --git a/saleor/app/tests/cassettes/test_app_commands/test_creates_app_from_manifest_sends_token.yaml b/saleor/app/tests/cassettes/test_app_commands/test_creates_app_from_manifest_sends_token.yaml
deleted file mode 100644
index dbf0c37b19..0000000000
--- a/saleor/app/tests/cassettes/test_app_commands/test_creates_app_from_manifest_sends_token.yaml
+++ /dev/null
@@ -1,104 +0,0 @@
-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\",\n \"version\": \"1.0.0\",\n \"aboutApp\"\
- : \"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\"\
- : \"http://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:
- - '500'
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Wed, 20 May 2020 07:56:35 GMT
- ETag:
- - W/"1f4-qx17e+bDbZJtTZiNJJshOoM1U6s"
- Expires:
- - '-1'
- Pragma:
- - no-cache
- Vary:
- - Origin, Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- X-Powered-By:
- - Express
- status:
- code: 200
- message: OK
-- 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\",\n \"version\": \"1.0.0\",\n \"aboutApp\"\
- : \"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\"\
- : \"http://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:
- - '500'
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Wed, 20 May 2020 07:56:35 GMT
- ETag:
- - W/"1f4-qx17e+bDbZJtTZiNJJshOoM1U6s"
- Expires:
- - '-1'
- Pragma:
- - no-cache
- Vary:
- - Origin, Accept-Encoding
- X-Content-Type-Options:
- - nosniff
- X-Powered-By:
- - Express
- status:
- code: 200
- message: OK
-version: 1
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 306d4c5d20..6f46211d8c 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -1,9 +1,10 @@
-from unittest.mock import ANY, Mock
+from unittest.mock import ANY, Mock, call
import pytest
import requests
from django.core.management import call_command
+from ... import schema_version
from ...core import JobStatus
from ...permission.enums import get_permissions
from ..models import App, AppInstallation
@@ -45,25 +46,35 @@ def test_creates_app_from_manifest_app_has_all_required_permissions():
assert set(app.permissions.all()) == set(expected_permission)
-def test_creates_app_from_manifest_sends_token(monkeypatch):
- mocked_response = Mock()
- mocked_response.status_code = 200
- mocked_post = Mock(return_value=mocked_response)
+def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
+ mocked_get = Mock(return_value=Mock())
+ mocked_get.return_value.json = Mock(return_value=app_manifest)
+ mocked_post = Mock(return_value=Mock())
+ mocked_post.return_value.status_code = 200
+
+ monkeypatch.setattr(requests, "get", mocked_get)
monkeypatch.setattr(requests, "post", mocked_post)
manifest_url = "http://localhost:3000/manifest"
call_command("install_app", manifest_url)
+ get_call = call(
+ manifest_url,
+ headers={"Saleor-Schema-Version": schema_version},
+ timeout=ANY,
+ allow_redirects=False,
+ )
+ mocked_get.assert_has_calls([get_call, get_call])
mocked_post.assert_called_once_with(
- "http://localhost:3000/register",
+ app_manifest["tokenTargetUrl"],
headers={
"Content-Type": "application/json",
# X- headers will be deprecated in Saleor 4.0, proper headers are without X-
"X-Saleor-Domain": "mirumee.com",
"Saleor-Domain": "mirumee.com",
"Saleor-Api-Url": "http://mirumee.com/graphql/",
+ "Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
timeout=ANY,
@@ -130,6 +141,7 @@ def test_sends_data_to_target_url(monkeypatch):
"X-Saleor-Domain": "mirumee.com",
"Saleor-Domain": "mirumee.com",
"Saleor-Api-Url": "http://mirumee.com/graphql/",
+ "Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
timeout=ANY,
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 1e6af911b5..f5c10dc8ce 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -11,7 +11,7 @@ from django.core.files.base import ContentFile
from django.db import DatabaseError
from freezegun import freeze_time
-from ... import __version__
+from ... import __version__, schema_version
from ...core.utils.json_serializer import CustomJsonEncoder
from ...webhook.event_types import WebhookEventAsyncType
from ...webhook.payloads import generate_meta, generate_requestor
@@ -54,10 +54,10 @@ def test_install_app_created_app(
):
# given
app_manifest["permissions"] = ["MANAGE_PRODUCTS"]
- mocked_get_response = Mock()
- mocked_get_response.json.return_value = app_manifest
+ mocked_get = Mock(return_value=Mock())
+ mocked_get.return_value.json = Mock(return_value=app_manifest)
- monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+ monkeypatch.setattr(requests, "get", mocked_get)
mocked_post = Mock()
monkeypatch.setattr(requests, "post", mocked_post)
@@ -67,6 +67,12 @@ def test_install_app_created_app(
app, _ = install_app(app_installation, activate=True)
# then
+ mocked_get.assert_called_once_with(
+ app_installation.manifest_url,
+ headers={"Saleor-Schema-Version": schema_version},
+ timeout=ANY,
+ allow_redirects=False,
+ )
mocked_post.assert_called_once_with(
app_manifest["tokenTargetUrl"],
headers={
@@ -75,6 +81,7 @@ def test_install_app_created_app(
"X-Saleor-Domain": "mirumee.com",
"Saleor-Domain": "mirumee.com",
"Saleor-Api-Url": "http://mirumee.com/graphql/",
+ "Saleor-Schema-Version": schema_version,
},
json={"auth_token": ANY},
timeout=ANY,
diff --git a/saleor/graphql/app/mutations/app_fetch_manifest.py b/saleor/graphql/app/mutations/app_fetch_manifest.py
index 51f883b385..617c72e74f 100644
--- a/saleor/graphql/app/mutations/app_fetch_manifest.py
+++ b/saleor/graphql/app/mutations/app_fetch_manifest.py
@@ -3,7 +3,7 @@ import requests
from django.core.exceptions import ValidationError
from ....app.error_codes import AppErrorCode
-from ....app.installation_utils import REQUEST_TIMEOUT, fetch_brand_data
+from ....app.installation_utils import fetch_brand_data, fetch_manifest
from ....app.manifest_validations import clean_manifest_data, clean_manifest_url
from ....permission.enums import AppPermission
from ...core import types as grapqhl_types
@@ -37,11 +37,7 @@ class AppFetchManifest(BaseMutation):
@classmethod
def fetch_manifest(cls, manifest_url):
try:
- response = requests.get(
- manifest_url, timeout=REQUEST_TIMEOUT, allow_redirects=False
- )
- response.raise_for_status()
- return response.json()
+ return fetch_manifest(manifest_url)
except requests.Timeout:
msg = "The request to fetch manifest data timed out."
code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
diff --git a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
index 248bd347af..b7931f8e06 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -1,11 +1,12 @@
import base64
from io import BytesIO
-from unittest.mock import Mock
+from unittest.mock import ANY, Mock
import pytest
import requests
from PIL import Image
+from ..... import schema_version
from .....app.error_codes import AppErrorCode
from .....thumbnail import IconThumbnailFormat
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -101,6 +102,32 @@ def test_app_fetch_manifest(staff_api_client, staff_user, permission_manage_apps
assert manifest["brand"] is None
+def test_app_fetch_manifest_custom_saleor_headers(
+ app_manifest, monkeypatch, staff_api_client, permission_manage_apps
+):
+ # given
+ mocked_get = Mock(return_value=Mock())
+ mocked_get.return_value.json = Mock(return_value=app_manifest)
+
+ monkeypatch.setattr(requests, "get", mocked_get)
+ query = APP_FETCH_MANIFEST_MUTATION
+ manifest_url = "http://localhost:3000/configuration/manifest"
+ variables = {"manifest_url": manifest_url}
+
+ # when
+ staff_api_client.post_graphql(
+ query, variables=variables, permissions=[permission_manage_apps]
+ )
+
+ # then
+ mocked_get.assert_called_once_with(
+ manifest_url,
+ headers={"Saleor-Schema-Version": schema_version},
+ timeout=ANY,
+ allow_redirects=False,
+ )
+
+
@pytest.mark.vcr
def test_app_fetch_manifest_with_audience(
staff_api_client, staff_user, permission_manage_apps
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index ff4e718a32..81771c7db2 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -6,7 +6,7 @@ from django_countries import countries
from django_prices_vatlayer.models import VAT
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE
-from ... import __version__
+from ... import __version__, schema_version
from ...account import models as account_models
from ...channel import models as channel_models
from ...core.utils import build_absolute_uri
@@ -537,8 +537,7 @@ class Shop(graphene.ObjectType):
@staticmethod
def resolve_schema_version(_, _info):
- major, minor, _ = __version__.split(".", 2)
- return f"{major}.{minor}"
+ return schema_version
# deprecated