Skip to content

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

Add static typing for app install (#18881)

Iga Karbowiak3cd1430f3164
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b99d46e28b..8ae82bef06 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.
Make sure to adapt your GraphQL queries if you use the `_entities` query.
- Mutations `channelCreate` and `channelUpdate` now raise GraphQL errors instead `INVALID` when negative `MINUTE`/`HOUR`/`DAY` values are passed.
+- `AppInstallInput` for `appInstall` mutation now requires `appName` and `manifestUrl` fields in the schema, matching the validation that was always enforced by the mutation logic.
### GraphQL API
diff --git a/saleor/app/manifest_schema.py b/saleor/app/manifest_schema.py
new file mode 100644
index 0000000000..b132c95cf2
--- /dev/null
+++ b/saleor/app/manifest_schema.py
@@ -0,0 +1,137 @@
+import mimetypes
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from pydantic import BaseModel, ConfigDict, field_validator
+from pydantic.alias_generators import to_camel
+from pydantic_core import PydanticCustomError
+
+from ..thumbnail import ICON_MIME_TYPES
+from ..webhook.response_schemas.utils.annotations import DefaultIfNone
+from .error_codes import AppErrorCode
+from .types import DEFAULT_APP_TARGET
+from .validators import AppURLValidator, image_url_validator
+
+_CAMEL_CONFIG = ConfigDict(
+ extra="ignore",
+ populate_by_name=True,
+ alias_generator=to_camel,
+)
+
+
+class ManifestBrandLogoSchema(BaseModel):
+ model_config = _CAMEL_CONFIG
+
+ default: str
+
+ @field_validator("default")
+ @classmethod
+ def validate_logo_url(cls, v: str) -> str:
+ try:
+ image_url_validator(v)
+ except DjangoValidationError as e:
+ raise PydanticCustomError(
+ AppErrorCode.INVALID_URL_FORMAT.value,
+ "Incorrect value for field: logo.default.",
+ {"error_code": AppErrorCode.INVALID_URL_FORMAT.value},
+ ) from e
+ filetype = mimetypes.guess_type(v)[0]
+ if filetype not in ICON_MIME_TYPES:
+ raise PydanticCustomError(
+ AppErrorCode.INVALID_URL_FORMAT.value,
+ "Invalid file type for field: logo.default.",
+ {"error_code": AppErrorCode.INVALID_URL_FORMAT.value},
+ )
+ return v
+
+
+class ManifestBrandSchema(BaseModel):
+ model_config = _CAMEL_CONFIG
+
+ logo: ManifestBrandLogoSchema
+
+
+class ManifestExtensionSchema(BaseModel):
+ model_config = _CAMEL_CONFIG
+
+ label: str
+ url: str
+ mount: str
+ target: str = DEFAULT_APP_TARGET
+ permissions: list[str] = []
+ options: dict = {}
+
+
+class ManifestWebhookSchema(BaseModel):
+ model_config = _CAMEL_CONFIG
+
+ name: str
+ target_url: str
+ query: str
+ is_active: bool = True
+ async_events: list[str] = []
+ sync_events: list[str] = []
+ custom_headers: dict | None = None
+
+ @field_validator("target_url")
+ @classmethod
+ def validate_target_url(cls, v: str) -> str:
+ url_validator = AppURLValidator(schemes=["http", "https", "awssqs", "gcpubsub"])
+ try:
+ url_validator(v)
+ except (DjangoValidationError, AttributeError) as e:
+ raise PydanticCustomError(
+ AppErrorCode.INVALID_URL_FORMAT.value,
+ "Invalid target url.",
+ {"error_code": AppErrorCode.INVALID_URL_FORMAT.value},
+ ) from e
+ return v
+
+
+class ManifestSchema(BaseModel):
+ model_config = _CAMEL_CONFIG
+
+ id: str
+ name: str
+ version: str
+ about: str | None = None
+ permissions: list[str] = []
+ app_url: str | None = None
+ token_target_url: str | None = None
+ data_privacy_url: str | None = None
+ homepage_url: str | None = None
+ support_url: str | None = None
+ audience: str | None = None
+ required_saleor_version: str | None = None
+ author: str | None = None
+ brand: ManifestBrandSchema | None = None
+ extensions: DefaultIfNone[list[ManifestExtensionSchema]] = []
+ webhooks: DefaultIfNone[list[ManifestWebhookSchema]] = []
+
+ @field_validator("token_target_url")
+ @classmethod
+ def validate_token_target_url(cls, v: str | None) -> str | None:
+ if v is None:
+ return None
+ url_validator = AppURLValidator()
+ try:
+ url_validator(v)
+ except (DjangoValidationError, AttributeError) as e:
+ raise PydanticCustomError(
+ AppErrorCode.INVALID_URL_FORMAT.value,
+ "Invalid target url.",
+ {"error_code": AppErrorCode.INVALID_URL_FORMAT.value},
+ ) from e
+ return v
+
+ @field_validator("author")
+ @classmethod
+ def validate_author(cls, v: str | None) -> str | None:
+ if v is None:
+ return None
+ if clean := v.strip():
+ return clean
+ raise PydanticCustomError(
+ AppErrorCode.INVALID.value,
+ "Incorrect value for field: author",
+ {"error_code": AppErrorCode.INVALID.value},
+ )
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index 8deab11861..77d3a8636c 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -5,12 +5,14 @@ from collections.abc import Iterable
from django.core.exceptions import ValidationError
from django.db.models import Value
from django.db.models.functions import Concat
+from pydantic import ValidationError as PydanticValidationError
from semantic_version import NpmSpec, Version
from semantic_version.base import Range
from .. import __version__
from ..giftcard.const import GIFT_CARD_PAYMENT_GATEWAY_ID
from ..graphql.core.utils import str_to_enum
+from ..graphql.error import pydantic_to_validation_error
from ..graphql.webhook.subscription_query import SubscriptionQuery
from ..permission.enums import (
get_permissions,
@@ -21,9 +23,10 @@ from ..permission.models import Permission
from ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ..webhook.validators import custom_headers_validator
from .error_codes import AppErrorCode
+from .manifest_schema import ManifestSchema
from .models import App
from .types import DEFAULT_APP_TARGET
-from .validators import AppURLValidator, brand_validator
+from .validators import AppURLValidator
logger = logging.getLogger(__name__)
@@ -97,20 +100,15 @@ def _clean_permissions(
def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
- errors: T_ERRORS = defaultdict(list)
-
- _validate_required_fields(manifest_data, errors)
-
+ # Structural validation: required fields, field types, URL formats, brand logo.
try:
- if token_target_url := manifest_data.get("tokenTargetUrl"):
- _clean_app_url(token_target_url)
- except (ValidationError, AttributeError):
- errors["tokenTargetUrl"].append(
- ValidationError(
- "Incorrect format.",
- code=AppErrorCode.INVALID_URL_FORMAT.value,
- )
- )
+ ManifestSchema.model_validate(manifest_data)
+ except PydanticValidationError as exc:
+ raise pydantic_to_validation_error(
+ exc, default_error_code=AppErrorCode.INVALID.value
+ ) from exc
+
+ errors: T_ERRORS = defaultdict(list)
try:
manifest_data["requiredSaleorVersion"] = _clean_required_saleor_version(
@@ -119,16 +117,6 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
except ValidationError as e:
errors["requiredSaleorVersion"].append(e)
- try:
- manifest_data["author"] = _clean_author(manifest_data.get("author"))
- except ValidationError as e:
- errors["author"].append(e)
-
- try:
- brand_validator(manifest_data.get("brand"))
- except ValidationError as e:
- errors["brand"].append(e)
-
saleor_permissions = get_permissions().annotate(
formatted_codename=Concat("content_type__app_label", Value("."), "codename")
)
@@ -225,19 +213,8 @@ def _clean_webhooks(manifest_data, errors):
str_to_enum(e_type[0]): e_type[0] for e_type in WebhookEventSyncType.CHOICES
}
- target_url_validator = AppURLValidator(
- schemes=["http", "https", "awssqs", "gcpubsub"]
- )
-
for webhook in webhooks:
webhook["isActive"] = webhook.get("isActive", True)
- if not isinstance(webhook["isActive"], bool):
- errors["webhooks"].append(
- ValidationError(
- "Incorrect value for field: isActive.",
- code=AppErrorCode.INVALID.value,
- )
- )
webhook["events"] = []
for e_type in webhook.get("asyncEvents", []):
@@ -273,16 +250,6 @@ def _clean_webhooks(manifest_data, errors):
if not webhook["events"]:
webhook["events"] = subscription_query.events
- try:
- target_url_validator(webhook["targetUrl"])
- except ValidationError:
- errors["webhooks"].append(
- ValidationError(
- "Invalid target url.",
- code=AppErrorCode.INVALID_URL_FORMAT.value,
- )
- )
-
if custom_headers := webhook.get("customHeaders"):
try:
webhook["customHeaders"] = custom_headers_validator(custom_headers)
@@ -295,42 +262,6 @@ def _clean_webhooks(manifest_data, errors):
)
-def _validate_required_fields(manifest_data, errors):
- manifest_required_fields = {"id", "version", "name"}
- extension_required_fields = {"label", "url", "mount"}
- webhook_required_fields = {"name", "targetUrl", "query"}
-
- if manifest_missing_fields := manifest_required_fields.difference(manifest_data):
- for missing_field in manifest_missing_fields:
- errors[missing_field].append(
- ValidationError("Field required.", code=AppErrorCode.REQUIRED.value)
- )
-
- app_extensions_data = manifest_data.get("extensions", [])
- for extension in app_extensions_data:
- extension_fields = set(extension.keys())
- if missing_fields := extension_required_fields.difference(extension_fields):
- errors["extensions"].append(
- ValidationError(
- "Missing required fields for app extension: "
- f"{', '.join(missing_fields)}.",
- code=AppErrorCode.REQUIRED.value,
- )
- )
-
- webhooks = manifest_data.get("webhooks", [])
- for webhook in webhooks:
- webhook_fields = set(webhook.keys())
- if missing_fields := webhook_required_fields.difference(webhook_fields):
- errors["webhooks"].append(
- ValidationError(
- f"Missing required fields for webhook: "
- f"{', '.join(missing_fields)}.",
- code=AppErrorCode.REQUIRED.value,
- )
- )
-
-
def _parse_version(version_str: str) -> Version:
return Version(version_str)
@@ -353,14 +284,3 @@ def _clean_required_saleor_version(
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}
-
-
-def _clean_author(author) -> str | None:
- if author is None:
- return None
- if isinstance(author, str):
- if clean := author.strip():
- return clean
- raise ValidationError(
- "Incorrect value for field: author", code=AppErrorCode.INVALID.value
- )
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 724b08ec7d..b91bc6a66a 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -146,7 +146,7 @@ def test_creates_app_from_manifest_skips_sending_token_when_target_url_not_provi
def test_creates_app_from_manifest_installation_failed():
manifest_url = "http://localhost:3000/manifest-wrong"
- with pytest.raises(ValidationError, match="Incorrect format."):
+ with pytest.raises(ValidationError, match="Invalid target url."):
call_command("install_app", manifest_url)
app_job = AppInstallation.objects.get()
diff --git a/saleor/app/tests/test_app_tasks.py b/saleor/app/tests/test_app_tasks.py
index 5323735507..882bf3fdf4 100644
--- a/saleor/app/tests/test_app_tasks.py
+++ b/saleor/app/tests/test_app_tasks.py
@@ -52,7 +52,7 @@ def test_install_app_task_wrong_format_of_target_token_url():
install_app_task(app_installation.id, activate=False)
app_installation.refresh_from_db()
assert app_installation.status == JobStatus.FAILED
- assert app_installation.message == "tokenTargetUrl: ['Incorrect format.']"
+ assert app_installation.message == "tokenTargetUrl: ['Invalid target url.']"
assert not App.objects.all()
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index ef16556aac..892782e8b4 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -678,7 +678,9 @@ def test_install_app_with_webhook_incorrect_is_active_value(
error_dict = excinfo.value.error_dict
assert "webhooks" in error_dict
- assert error_dict["webhooks"][0].message == "Incorrect value for field: isActive."
+ assert error_dict["webhooks"][0].message == (
+ "Input should be a valid boolean, unable to interpret input"
+ )
def test_install_app_webhook_incorrect_query(
diff --git a/saleor/app/tests/test_manifest_validations.py b/saleor/app/tests/test_manifest_validations.py
new file mode 100644
index 0000000000..5d60ca7350
--- /dev/null
+++ b/saleor/app/tests/test_manifest_validations.py
@@ -0,0 +1,322 @@
+import pytest
+from pydantic import ValidationError as PydanticValidationError
+
+from ..error_codes import AppErrorCode
+from ..manifest_schema import ICON_MIME_TYPES, ManifestSchema
+
+MINIMAL_MANIFEST = {
+ "id": "app.example",
+ "name": "My App",
+ "version": "1.0.0",
+}
+
+
+def test_manifest_schema_valid_minimal():
+ # given / when
+ schema = ManifestSchema.model_validate(MINIMAL_MANIFEST)
+
+ # then
+ assert schema.id == MINIMAL_MANIFEST["id"]
+ assert schema.name == MINIMAL_MANIFEST["name"]
+ assert schema.version == MINIMAL_MANIFEST["version"]
+
+
+def test_manifest_schema_missing_required_fields():
+ # given
+ manifest_data = {}
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ error_fields = {e["loc"][0] for e in errors}
+ assert "id" in error_fields
+ assert "name" in error_fields
+ assert "version" in error_fields
+
+
+def test_manifest_schema_invalid_token_target_url():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "tokenTargetUrl": "not-a-valid-url",
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ assert len(errors) == 1
+ assert errors[0]["loc"][0] == "tokenTargetUrl"
+ assert errors[0]["ctx"]["error_code"] == AppErrorCode.INVALID_URL_FORMAT.value
+
+
+def test_manifest_schema_valid_token_target_url():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "tokenTargetUrl": "https://example.com/register",
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.token_target_url == "https://example.com/register"
+
+
+def test_manifest_schema_invalid_author_empty_string():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "author": " ",
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ assert len(errors) == 1
+ assert errors[0]["loc"][0] == "author"
+ assert errors[0]["ctx"]["error_code"] == AppErrorCode.INVALID.value
+
+
+def test_manifest_schema_valid_author_none():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "author": None,
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.author is None
+
+
+def test_manifest_schema_valid_author_strips_whitespace():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "author": " Acme Ltd ",
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.author == "Acme Ltd"
+
+
+def test_manifest_schema_brand_missing_logo_default():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "brand": {"logo": {}},
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ assert any(e["loc"][-1] == "default" for e in errors)
+
+
+def test_manifest_schema_brand_invalid_url():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "brand": {"logo": {"default": "not-a-url"}},
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ assert len(errors) == 1
+ assert errors[0]["ctx"]["error_code"] == AppErrorCode.INVALID_URL_FORMAT.value
+
+
+def test_manifest_schema_brand_invalid_mime_type():
+ # given
+ assert "image/jpeg" not in ICON_MIME_TYPES
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "brand": {"logo": {"default": "https://example.com/logo.jpg"}},
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ assert len(errors) == 1
+ assert errors[0]["ctx"]["error_code"] == AppErrorCode.INVALID_URL_FORMAT.value
+
+
+def test_manifest_schema_brand_valid_png():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "brand": {"logo": {"default": "https://example.com/logo.png"}},
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.brand is not None
+ assert schema.brand.logo.default == "https://example.com/logo.png"
+
+
+def test_manifest_schema_extensions_null_defaults_to_empty_list():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "extensions": None,
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.extensions == []
+
+
+def test_manifest_schema_webhooks_null_defaults_to_empty_list():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "webhooks": None,
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.webhooks == []
+
+
+def test_manifest_schema_extension_missing_required_fields():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "extensions": [{"url": "https://example.com/ext"}],
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ error_fields = {e["loc"][-1] for e in errors}
+ assert "label" in error_fields
+ assert "mount" in error_fields
+
+
+def test_manifest_schema_webhook_missing_required_fields():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "webhooks": [{"name": "my-webhook"}],
+ }
+
+ # when
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ManifestSchema.model_validate(manifest_data)
+
+ # then
+ errors = exc_info.value.errors()
+ error_fields = {e["loc"][-1] for e in errors}
+ assert "targetUrl" in error_fields
+ assert "query" in error_fields
+
+
+def test_manifest_schema_webhook_is_active_defaults_to_true():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "webhooks": [
+ {
+ "name": "my-webhook",
+ "targetUrl": "https://example.com/webhook",
+ "query": "subscription { event { ... on OrderCreated { order { id } } } }",
+ }
+ ],
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.webhooks[0].is_active is True
+
+
+def test_manifest_schema_full_input():
+ # given
+ manifest_data = {
+ "id": "app.example",
+ "name": "My App",
+ "version": "1.0.0",
+ "tokenTargetUrl": "https://example.com/token",
+ "appUrl": "https://example.com",
+ "homepageUrl": "https://example.com",
+ "supportUrl": "https://example.com/support",
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.token_target_url == manifest_data["tokenTargetUrl"]
+ assert schema.app_url == manifest_data["appUrl"]
+ assert schema.homepage_url == manifest_data["homepageUrl"]
+ assert schema.support_url == manifest_data["supportUrl"]
+
+
+def test_manifest_schema_extra_fields_ignored():
+ # given
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "unknownField": "some value",
+ "anotherExtra": 42,
+ }
+
+ # when
+ schema = ManifestSchema.model_validate(manifest_data)
+
+ # then
+ assert schema.id == MINIMAL_MANIFEST["id"]
+
+
+def test_manifest_schema_deprecated_fields_accepted():
+ # given — deprecated fields are excluded from schema but must not cause a
+ # validation error, and must remain accessible in the original dict so that
+ # downstream code (installation_utils, app_fetch_manifest) can still read them
+ data_privacy = "We do not store your data."
+ configuration_url = "https://example.com/config"
+ manifest_data = {
+ **MINIMAL_MANIFEST,
+ "dataPrivacy": data_privacy,
+ "configurationUrl": configuration_url,
+ }
+
+ # when
+ ManifestSchema.model_validate(manifest_data)
+
+ # then — original dict is untouched; downstream readers can still access the values
+ assert manifest_data["dataPrivacy"] == data_privacy
+ assert manifest_data["configurationUrl"] == configuration_url
diff --git a/saleor/app/tests/test_validators.py b/saleor/app/tests/test_validators.py
index 690a5cb784..371c7939ca 100644
--- a/saleor/app/tests/test_validators.py
+++ b/saleor/app/tests/test_validators.py
@@ -7,12 +7,10 @@ from ...app.validators import (
)
from ..error_codes import AppErrorCode
from ..manifest_validations import (
- _clean_author,
_clean_extension_url,
_clean_required_saleor_version,
_parse_version,
)
-from ..validators import brand_validator
def test_validate_url():
@@ -67,33 +65,6 @@ def test_clean_required_saleor_version_raise_for_saleor_version():
assert error.value.code == AppErrorCode.UNSUPPORTED_SALEOR_VERSION.value
- ("author", "cleaned"), [(None, None), (" Acme Ltd ", "Acme Ltd")]
-)
-def test_clean_author(author, cleaned):
- assert _clean_author(author) == cleaned
-
-
-def test_brand_validator_required_fields():
- with pytest.raises(ValidationError) as error:
- brand_validator({"logo": {}})
- assert error.value.code == AppErrorCode.REQUIRED.value
-
-
- "url",
- [
- "example.com/logo.png",
- "https://exmple.com/logo",
- "https://exmple.com/logo.jpg",
- ],
-)
-def test_brand_validator_with_invalid_logo_url(url):
- with pytest.raises(ValidationError) as error:
- brand_validator({"logo": {"default": url}})
- assert error.value.code == AppErrorCode.INVALID_URL_FORMAT.value
-
-
def test_new_tab_relative_url_without_app_url(app_manifest):
# given
app_manifest["appUrl"] = None
diff --git a/saleor/app/validators.py b/saleor/app/validators.py
index 3e7983a2ed..6621d985f4 100644
--- a/saleor/app/validators.py
+++ b/saleor/app/validators.py
@@ -1,10 +1,7 @@
-import mimetypes
import re
-from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
-from ..thumbnail import ICON_MIME_TYPES
from .error_codes import AppErrorCode
@@ -26,21 +23,3 @@ image_url_validator = AppURLValidator(
message="Incorrect value for field: logo.default.",
code=AppErrorCode.INVALID_URL_FORMAT.value,
)
-
-
-def brand_validator(brand):
- if brand is None:
- return
- try:
- logo_url = brand["logo"]["default"]
- except (TypeError, KeyError) as e:
- raise ValidationError(
- "Missing required field: logo.default.", code=AppErrorCode.REQUIRED.value
- ) from e
- image_url_validator(logo_url)
- filetype = mimetypes.guess_type(logo_url)[0]
- if filetype not in ICON_MIME_TYPES:
- raise ValidationError(
- "Invalid file type for field: logo.default.",
- code=AppErrorCode.INVALID_URL_FORMAT.value,
- )
diff --git a/saleor/graphql/app/mutations/app_install.py b/saleor/graphql/app/mutations/app_install.py
index 51f12c94f1..c1f13f61db 100644
--- a/saleor/graphql/app/mutations/app_install.py
+++ b/saleor/graphql/app/mutations/app_install.py
@@ -17,8 +17,10 @@ from ..utils import ensure_can_manage_permissions
class AppInstallInput(BaseInputObjectType):
- app_name = graphene.String(description="Name of the app to install.")
- manifest_url = graphene.String(description="URL to app's manifest in JSON format.")
+ app_name = graphene.String(description="Name of the app to install.", required=True)
+ manifest_url = graphene.String(
+ description="URL to app's manifest in JSON format.", required=True
+ )
activate_after_installation = graphene.Boolean(
default_value=True,
required=False,
@@ -65,9 +67,9 @@ class AppInstall(DeprecatedModelMutation):
cleaned_input = super().clean_input(info, instance, data, **kwargs)
# clean and prepare permissions
- if "permissions" in cleaned_input:
+ permissions = cleaned_input.pop("permissions", None)
+ if permissions:
requestor = get_user_or_app_from_context(info.context)
- permissions = cleaned_input.pop("permissions")
cleaned_input["permissions"] = get_permissions(permissions)
ensure_can_manage_permissions(requestor, permissions)
return cleaned_input
diff --git a/saleor/graphql/app/mutations/app_problem_create.py b/saleor/graphql/app/mutations/app_problem_create.py
index 6c25cbb998..5df06257df 100644
--- a/saleor/graphql/app/mutations/app_problem_create.py
+++ b/saleor/graphql/app/mutations/app_problem_create.py
@@ -116,7 +116,7 @@ class AppProblemCreate(BaseMutation):
validated = AppProblemCreateValidatedInput(**input_data)
except PydanticValidationError as exc:
raise pydantic_to_validation_error(
- exc, error_code=AppProblemCreateErrorCodeEnum.INVALID.value
+ exc, default_error_code=AppProblemCreateErrorCodeEnum.INVALID.value
) from exc
now = timezone.now()
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 e49be4c499..d62923d37a 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -331,7 +331,7 @@ def test_app_fetch_manifest_missing_fields(
assert errors[0] == {
"code": "REQUIRED",
"field": missing_field,
- "message": "Field required.",
+ "message": "Field required",
}
@@ -379,7 +379,7 @@ def test_app_fetch_manifest_missing_extension_fields(
assert errors[0] == {
"code": "REQUIRED",
"field": "extensions",
- "message": f"Missing required fields for app extension: {missing_field}.",
+ "message": "Field required",
}
diff --git a/saleor/graphql/app/tests/mutations/test_app_install.py b/saleor/graphql/app/tests/mutations/test_app_install.py
index aac327d6ec..709adecdd2 100644
--- a/saleor/graphql/app/tests/mutations/test_app_install.py
+++ b/saleor/graphql/app/tests/mutations/test_app_install.py
@@ -10,7 +10,7 @@ from ....tests.utils import get_graphql_content
INSTALL_APP_MUTATION = """
mutation AppInstall(
- $app_name: String, $manifest_url: String, $permissions: [PermissionEnum!]){
+ $app_name: String!, $manifest_url: String!, $permissions: [PermissionEnum!]){
appInstall(
input:{appName: $app_name, manifestUrl: $manifest_url,
permissions:$permissions}){
@@ -191,3 +191,49 @@ def test_install_app_mutation_with_the_same_identifier_twice(
"identifier: "
"['App with the same identifier is already installed: Sample app objects']"
)
+
+
+def test_install_app_mutation_with_invalid_manifest_url_returns_error(
+ permission_manage_apps,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ staff_user.user_permissions.set([permission_manage_apps])
+ variables = {
+ "app_name": "New external integration",
+ "manifest_url": "not-a-valid-url",
+ "permissions": [],
+ }
+
+ # when
+ data = _mutate_app_install(staff_api_client, variables)
+
+ # then
+ errors = data["errors"]
+ assert not data["appInstallation"]
+ assert len(errors) == 1
+ error = errors[0]
+ assert error["field"] == "manifestUrl"
+ assert error["code"] == AppErrorCode.INVALID_URL_FORMAT.name
+
+
+def test_install_app_mutation_with_null_permissions(
+ permission_manage_apps,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ staff_user.user_permissions.set([permission_manage_apps])
+ variables = {
+ "app_name": "test app",
+ "manifest_url": "http://localhost:3000/manifest",
+ "permissions": None,
+ }
+
+ # when
+ data = _mutate_app_install(staff_api_client, variables)
+
+ # then
+ assert data["appInstallation"]
+ assert not data["errors"]
diff --git a/saleor/graphql/error.py b/saleor/graphql/error.py
index abe6bec49e..4702e00ad4 100644
--- a/saleor/graphql/error.py
+++ b/saleor/graphql/error.py
@@ -4,16 +4,26 @@ from pydantic import ValidationError as PydanticValidationError
def pydantic_to_validation_error(
- exc: PydanticValidationError, error_code: str = "invalid"
+ exc: PydanticValidationError, default_error_code: str = "invalid"
) -> ValidationError:
- """Convert Pydantic ValidationError to Django ValidationError."""
+ """Convert Pydantic ValidationError to Django ValidationError.
+
+ Each pydantic error can carry a per-error code by raising
+ PydanticCustomError with ``{"error_code": ...}`` in its context dict.
+ Falls back to ``"required"`` for missing-field errors, and to
+ ``default_error_code`` for all other built-in constraint errors.
+ """
errors: dict[str, ValidationError] = {}
for error in exc.errors():
field = str(error["loc"][0]) if error["loc"] else "input"
+ if error.get("type") == "missing":
+ code = "required"
+ else:
+ code = error.get("ctx", {}).get("error_code", default_error_code)
errors[field] = ValidationError(
error["msg"],
- code=error_code,
+ code=code,
)
return ValidationError(errors)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 015623c5c3..e5c05eff5a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -32145,10 +32145,10 @@ type AppInstall @doc(category: "Apps") {
input AppInstallInput @doc(category: "Apps") {
"""Name of the app to install."""
- appName: String
+ appName: String!
"""URL to app's manifest in JSON format."""
- manifestUrl: String
+ manifestUrl: String!
"""Determine if app will be set active or not."""
activateAfterInstallation: Boolean = true
diff --git a/saleor/graphql/tests/test_error.py b/saleor/graphql/tests/test_error.py
index 865ed0eb62..a9882650f7 100644
--- a/saleor/graphql/tests/test_error.py
+++ b/saleor/graphql/tests/test_error.py
@@ -1,8 +1,9 @@
from typing import Annotated
import pytest
-from pydantic import BaseModel, Field, StringConstraints
+from pydantic import BaseModel, Field, StringConstraints, field_validator
from pydantic import ValidationError as PydanticValidationError
+from pydantic_core import PydanticCustomError
from ..error import pydantic_to_validation_error
@@ -12,6 +13,21 @@ class SampleModel(BaseModel):
age: Annotated[int, Field(ge=0)]
+class ModelWithCustomErrorCode(BaseModel):
+ url: str
+
+ @field_validator("url")
+ @classmethod
+ def validate_url(cls, v: str) -> str:
+ if not v.startswith("https://"):
+ raise PydanticCustomError(
+ "invalid_url_format",
+ "Enter a valid URL.",
+ {"error_code": "invalid_url_format"},
+ )
+ return v
+
+
def test_pydantic_to_validation_error_single_field():
# given
with pytest.raises(PydanticValidationError) as exc_info:
@@ -65,10 +81,41 @@ def test_pydantic_to_validation_error_uses_custom_error_code():
SampleModel(name="ab", age=5)
# when
- error = pydantic_to_validation_error(exc_info.value, error_code="custom_code")
+ error = pydantic_to_validation_error(
+ exc_info.value, default_error_code="custom_code"
+ )
# then
assert error.message_dict == {
"name": ["String should have at least 3 characters"],
}
assert error.error_dict["name"][0].code == "custom_code"
+
+
+def test_pydantic_to_validation_error_per_error_code_overrides_global():
+ # given
+ with pytest.raises(PydanticValidationError) as exc_info:
+ ModelWithCustomErrorCode(url="http://not-https.com")
+
+ # when
+ # Global fallback is "invalid", but the validator embeds "invalid_url_format"
+ error = pydantic_to_validation_error(exc_info.value, default_error_code="invalid")
+
+ # then
+ assert error.message_dict == {"url": ["Enter a valid URL."]}
+ assert error.error_dict["url"][0].code == "invalid_url_format"
+
+
+def test_pydantic_to_validation_error_falls_back_to_global_when_no_ctx_code():
+ # given
+ with pytest.raises(PydanticValidationError) as exc_info:
+ SampleModel(name="ab", age=5)
+
+ # when
+ # Built-in constraint (min_length) carries no error_code in ctx
+ error = pydantic_to_validation_error(
+ exc_info.value, default_error_code="fallback_code"
+ )
+
+ # then
+ assert error.error_dict["name"][0].code == "fallback_code"