Skip to content

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

Add "requiredSaleorVersion" field to the app manifest (#12164)

Przemysław Łada2b756aabb70e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc382c2255..f104e2aa35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,8 +10,16 @@ All notable, unreleased changes to this project will be documented in this file.
- [Preview] Add `StockBulkUpdate` mutation - #12139 by @SzymJ
- Upgrade GraphiQL to `2.4.0` for playground - #12271 by @zaiste
+- Add new object type `AppManifestRequiredSaleorVersion` - #12164 by @przlada
+ - Add new optional field `Manifest.requiredSaleorVersion`
+ - Add `requiredSaleorVersion` validation to `appInstall` and `appFetchManifest` mutations
+
### Other changes
+### Saleor Apps
+
+- Add `requiredSaleorVersion` field to the App manifest determining the required Saleor version as semver range - #12164 by @przlada
+
# 3.12.0
### Breaking changes
diff --git a/poetry.lock b/poetry.lock
index 83080019fc..48a2918c2d 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -4076,6 +4076,22 @@ botocore = ">=1.12.36,<2.0a.0"
[package.extras]
crt = ["botocore[crt] (>=1.20.29,<2.0a.0)"]
+[[package]]
+name = "semantic-version"
+version = "2.10.0"
+description = "A library implementing the 'SemVer' scheme."
+category = "main"
+optional = false
+python-versions = ">=2.7"
+files = [
+ {file = "semantic_version-2.10.0-py2.py3-none-any.whl", hash = "sha256:de78a3b8e0feda74cabc54aab2da702113e33ac9d9eb9d2389bcf1f58b7d9177"},
+ {file = "semantic_version-2.10.0.tar.gz", hash = "sha256:bdabb6d336998cbb378d4b9db3a4b56a1e3235701dc05ea2690d9a997ed5041c"},
+]
+
+[package.extras]
+dev = ["Django (>=1.11)", "check-manifest", "colorama (<=0.4.1)", "coverage", "flake8", "nose2", "readme-renderer (<25.0)", "tox", "wheel", "zest.releaser[recommended]"]
+doc = ["Sphinx", "sphinx-rtd-theme"]
+
[[package]]
name = "sendgrid"
version = "6.9.7"
@@ -5133,4 +5149,4 @@ test = ["pytest"]
[metadata]
lock-version = "2.0"
python-versions = "~3.9"
-content-hash = "1b6b12647e70ee74abe486e314e08fed4ebb29f524b0e66243886233edf47412"
+content-hash = "09f417fc869046dc213a90538de3afcc0e342fc044231461db2182225f65bee6"
diff --git a/pyproject.toml b/pyproject.toml
index ff2bbf25fe..88dd76cc37 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -73,6 +73,7 @@ documentation = "https://docs.saleor.io/"
uvicorn = {extras = ["standard"], version = "^0.19.0"}
Authlib = "^1.0.0"
pillow-avif-plugin = "^1.3.1"
+ semantic-version = "^2.10.0"
[tool.poetry.dependencies.celery]
version = ">=4.4.5,<6.0.0"
diff --git a/requirements.txt b/requirements.txt
index 841c8edd15..a7f414b300 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -134,6 +134,7 @@ requests==2.28.2 ; python_version >= "3.9" and python_version < "3.10"
rsa==4.9 ; python_version >= "3.9" and python_version < "3.10"
rx==1.6.3 ; python_version >= "3.9" and python_version < "3.10"
s3transfer==0.6.0 ; python_version >= "3.9" and python_version < "3.10"
+semantic-version==2.10.0 ; python_version >= "3.9" and python_version < "3.10"
sendgrid==6.9.7 ; python_version >= "3.9" and python_version < "3.10"
sentry-sdk==1.16.0 ; python_version >= "3.9" and python_version < "3.10"
setuptools==67.5.0 ; python_version >= "3.9" and python_version < "3.10"
diff --git a/requirements_dev.txt b/requirements_dev.txt
index c11f7d87df..002ed59586 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -191,6 +191,7 @@ requests==2.28.2 ; python_version >= "3.9" and python_version < "3.10"
rsa==4.9 ; python_version >= "3.9" and python_version < "3.10"
rx==1.6.3 ; python_version >= "3.9" and python_version < "3.10"
s3transfer==0.6.0 ; python_version >= "3.9" and python_version < "3.10"
+semantic-version==2.10.0 ; python_version >= "3.9" and python_version < "3.10"
sendgrid==6.9.7 ; python_version >= "3.9" and python_version < "3.10"
sentry-sdk==1.16.0 ; python_version >= "3.9" and python_version < "3.10"
setuptools==67.5.0 ; python_version >= "3.9" and python_version < "3.10"
diff --git a/saleor/app/error_codes.py b/saleor/app/error_codes.py
index 76a5fb35fd..7c426708a7 100644
--- a/saleor/app/error_codes.py
+++ b/saleor/app/error_codes.py
@@ -16,3 +16,4 @@ class AppErrorCode(Enum):
UNIQUE = "unique"
OUT_OF_SCOPE_APP = "out_of_scope_app"
OUT_OF_SCOPE_PERMISSION = "out_of_scope_permission"
+ UNSUPPORTED_SALEOR_VERSION = "unsupported_saleor_version"
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 05950e3c4f..2a3520226d 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -55,7 +55,7 @@ def install_app(app_installation: AppInstallation, activate: bool = False):
manifest_data["permissions"] = get_permission_names(assigned_permissions)
- clean_manifest_data(manifest_data)
+ clean_manifest_data(manifest_data, raise_for_saleor_version=True)
app = App.objects.create(
name=app_installation.app_name,
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index 7653ce79ed..1ac8f3f070 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -1,11 +1,13 @@
import logging
from collections import defaultdict
-from typing import Dict, Iterable, List
+from typing import Dict, Iterable, List, Optional
from django.core.exceptions import ValidationError
from django.db.models import Value
from django.db.models.functions import Concat
+from semantic_version import NpmSpec, Version
+from .. import __version__
from ..graphql.core.utils import str_to_enum
from ..graphql.webhook.subscription_query import SubscriptionQuery
from ..permission.enums import (
@@ -95,7 +97,7 @@ def clean_permissions(
return [p for p in saleor_permissions if p.codename in permissions]
-def clean_manifest_data(manifest_data):
+def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
errors: T_ERRORS = defaultdict(list)
validate_required_fields(manifest_data, errors)
@@ -110,6 +112,13 @@ def clean_manifest_data(manifest_data):
)
)
+ try:
+ manifest_data["requiredSaleorVersion"] = clean_required_saleor_version(
+ manifest_data.get("requiredSaleorVersion"), raise_for_saleor_version
+ )
+ except ValidationError as e:
+ errors["requiredSaleorVersion"].append(e)
+
saleor_permissions = get_permissions().annotate(
formated_codename=Concat("content_type__app_label", Value("."), "codename")
)
@@ -291,3 +300,27 @@ def validate_required_fields(manifest_data, errors):
code=AppErrorCode.REQUIRED.value,
)
)
+
+
+def parse_version(version_str: str) -> Version:
+ return Version(version_str)
+
+
+def clean_required_saleor_version(
+ required_version,
+ raise_for_saleor_version: bool,
+ saleor_version=__version__,
+) -> Optional[Dict]:
+ if not required_version:
+ return None
+ try:
+ spec = NpmSpec(required_version)
+ except Exception:
+ msg = "Incorrect value for required Saleor version."
+ raise ValidationError(msg, code=AppErrorCode.INVALID.value)
+ version = parse_version(saleor_version)
+ satisfied = spec.match(version)
+ if raise_for_saleor_version and not satisfied:
+ msg = f"Saleor version {saleor_version} is not supported by the app."
+ raise ValidationError(msg, code=AppErrorCode.UNSUPPORTED_SALEOR_VERSION.value)
+ return {"constraint": required_version, "satisfied": satisfied}
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index f9df651e46..1785ad52e6 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -7,9 +7,11 @@ import requests
from django.core.exceptions import ValidationError
from freezegun import freeze_time
+from ... import __version__
from ...core.utils.json_serializer import CustomJsonEncoder
from ...webhook.event_types import WebhookEventAsyncType
from ...webhook.payloads import generate_meta, generate_requestor
+from ..error_codes import AppErrorCode
from ..installation_utils import (
AppInstallationError,
install_app,
@@ -93,6 +95,43 @@ def test_install_app_created_app_with_audience(
assert app.audience == audience
+def test_install_app_with_required_saleor_version(
+ app_manifest, app_installation, monkeypatch
+):
+ # given
+ app_manifest["requiredSaleorVersion"] = f"^{__version__}"
+ 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.objects.get().id == app.id
+
+
+def test_install_app_when_saleor_version_unsupported(
+ app_manifest, app_installation, monkeypatch
+):
+ # given
+ app_manifest["requiredSaleorVersion"] = "<3.11"
+ 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
+ with pytest.raises(ValidationError) as validation_error:
+ install_app(app_installation, activate=True)
+
+ # then
+ errors = validation_error.value.error_dict["requiredSaleorVersion"]
+ assert len(errors) == 1
+ assert errors[0].code == AppErrorCode.UNSUPPORTED_SALEOR_VERSION.value
+
+
@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/app/tests/test_validators.py b/saleor/app/tests/test_validators.py
index b85614897f..933dc92f6f 100644
--- a/saleor/app/tests/test_validators.py
+++ b/saleor/app/tests/test_validators.py
@@ -1,7 +1,10 @@
import pytest
from django.core.exceptions import ValidationError
+from ... import __version__
from ...app.validators import AppURLValidator
+from ..error_codes import AppErrorCode
+from ..manifest_validations import clean_required_saleor_version, parse_version
def test_validate_url():
@@ -15,3 +18,41 @@ def test_validate_invalid_url():
url = "otherapp:3000"
with pytest.raises(ValidationError):
url_validator(url)
+
+
+def test_parse_version():
+ assert str(parse_version(__version__)) == __version__
+
+
+ "required_version,version,satisfied",
+ [
+ ("*", "3.12.1", True),
+ ("3.8 - 3.9 || ~3.10.2 || 3.11.* || 3.12.x", "3.12.1", True),
+ ("^3.12.0-0 <=3.14", "3.12.0-a", True),
+ ("^3.12", "4.0.0", False),
+ ("^3.12", "3.12.0-a", False),
+ ],
+)
+def test_clean_required_saleor_version(required_version, version, satisfied):
+ cleaned = clean_required_saleor_version(required_version, False, version)
+ assert cleaned == {"constraint": required_version, "satisfied": satisfied}
+
+
+def test_clean_required_saleor_version_optional():
+ assert clean_required_saleor_version(None, False) is None
+
+
+ "required_version", ["3.8-3.9", "^3w.11", {"wrong", "data type"}, 3, 3.12]
+)
+def test_clean_required_saleor_version_with_invalid_range(required_version):
+ with pytest.raises(ValidationError) as error:
+ clean_required_saleor_version(required_version, False, "3.12.1")
+ assert error.value.code == AppErrorCode.INVALID.value
+
+
+def test_clean_required_saleor_version_raise_for_saleor_version():
+ with pytest.raises(ValidationError) as error:
+ clean_required_saleor_version("^3.13", True, "3.12.1")
+ assert error.value.code == AppErrorCode.UNSUPPORTED_SALEOR_VERSION.value
diff --git a/saleor/graphql/app/mutations/app_fetch_manifest.py b/saleor/graphql/app/mutations/app_fetch_manifest.py
index 9a74ce681c..ed986041aa 100644
--- a/saleor/graphql/app/mutations/app_fetch_manifest.py
+++ b/saleor/graphql/app/mutations/app_fetch_manifest.py
@@ -71,6 +71,7 @@ class AppFetchManifest(BaseMutation):
extensions=cleaned_data.get("extensions", []),
webhooks=cleaned_data.get("webhooks", []),
audience=cleaned_data.get("audience"),
+ required_saleor_version=cleaned_data.get("requiredSaleorVersion"),
)
@classmethod
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 c4e569a6a4..2d413aaaa6 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -3,6 +3,7 @@ from unittest.mock import Mock
import pytest
import requests
+from .....app.error_codes import AppErrorCode
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import AppExtensionMountEnum, AppExtensionTargetEnum
@@ -25,6 +26,10 @@ mutation AppFetchManifest($manifest_url: String!){
code
}
audience
+ requiredSaleorVersion{
+ constraint
+ satisfied
+ }
extensions{
label
url
@@ -77,6 +82,7 @@ def test_app_fetch_manifest(staff_api_client, staff_user, permission_manage_apps
"MANAGE_ORDERS",
"MANAGE_USERS",
}
+ assert manifest["requiredSaleorVersion"] is None
@pytest.mark.vcr
@@ -627,3 +633,55 @@ def test_app_fetch_manifest_with_extensions(
assert extension["url"] == "http://127.0.0.1:8080/app"
assert extension["mount"] == AppExtensionMountEnum.PRODUCT_OVERVIEW_CREATE.name
assert extension["target"] == AppExtensionTargetEnum.POPUP.name
+
+
+def test_app_fetch_manifest_with_required_saleor_version(
+ staff_api_client, app_manifest, permission_manage_apps, monkeypatch
+):
+ # given
+ required_saleor_version = "<3.11"
+ app_manifest["requiredSaleorVersion"] = required_saleor_version
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_FETCH_MANIFEST_MUTATION,
+ variables={"manifest_url": "http://localhost:3000/manifest"},
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ manifest = content["data"]["appFetchManifest"]["manifest"]
+ assert len(content["data"]["appFetchManifest"]["errors"]) == 0
+ assert manifest["requiredSaleorVersion"] == {
+ "constraint": required_saleor_version,
+ "satisfied": False,
+ }
+
+
+def test_app_fetch_manifest_with_invalid_required_saleor_version(
+ staff_api_client, app_manifest, permission_manage_apps, monkeypatch
+):
+ # given
+ required_saleor_version = "3.wrong.1"
+ app_manifest["requiredSaleorVersion"] = required_saleor_version
+ mocked_get_response = Mock()
+ mocked_get_response.json.return_value = app_manifest
+ monkeypatch.setattr(requests, "get", Mock(return_value=mocked_get_response))
+
+ # when
+ response = staff_api_client.post_graphql(
+ APP_FETCH_MANIFEST_MUTATION,
+ variables={"manifest_url": "http://localhost:3000/manifest"},
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["appFetchManifest"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "requiredSaleorVersion"
+ assert errors[0]["code"] == AppErrorCode.INVALID.name
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index 233c1e2b42..8e2dba10af 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -16,6 +16,7 @@ from ..core.descriptions import (
ADDED_IN_31,
ADDED_IN_35,
ADDED_IN_38,
+ ADDED_IN_313,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -192,6 +193,23 @@ class AppManifestWebhook(graphene.ObjectType):
return root["targetUrl"]
+class AppManifestRequiredSaleorVersion(graphene.ObjectType):
+ constraint = graphene.String(
+ required=True,
+ description=(
+ "Required Saleor version as semver range." + ADDED_IN_313 + PREVIEW_FEATURE
+ ),
+ )
+ satisfied = graphene.Boolean(
+ required=True,
+ description=(
+ "Informs if the Saleor version matches the required one."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ )
+
+
class Manifest(graphene.ObjectType):
identifier = graphene.String(required=True)
version = graphene.String(required=True)
@@ -224,6 +242,14 @@ class Manifest(graphene.ObjectType):
+ PREVIEW_FEATURE
)
)
+ required_saleor_version = graphene.Field(
+ AppManifestRequiredSaleorVersion,
+ description=(
+ "Determines the app's required Saleor version as semver range."
+ + ADDED_IN_313
+ + PREVIEW_FEATURE
+ ),
+ )
class Meta:
description = "The manifest definition."
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index bd4868f957..154db7311e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -23328,6 +23328,7 @@ enum AppErrorCode {
UNIQUE
OUT_OF_SCOPE_APP
OUT_OF_SCOPE_PERMISSION
+ UNSUPPORTED_SALEOR_VERSION
}
input AppInput {
@@ -23493,6 +23494,15 @@ type Manifest {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
audience: String
+
+ """
+ Determines the app's required Saleor version as semver range.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ requiredSaleorVersion: AppManifestRequiredSaleorVersion
}
type AppManifestExtension {
@@ -23529,6 +23539,26 @@ type AppManifestWebhook {
targetUrl: String!
}
+type AppManifestRequiredSaleorVersion {
+ """
+ Required Saleor version as semver range.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ constraint: String!
+
+ """
+ Informs if the Saleor version matches the required one.
+
+ Added in Saleor 3.13.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ satisfied: Boolean!
+}
+
"""
Activate the app.