Skip to content

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

Add AppFetchManifest mutation

Maciej Korycinski78eaea6ed038
diff --git a/saleor/app/error_codes.py b/saleor/app/error_codes.py
index 1d5e295ef2..ebbace2a9e 100644
--- a/saleor/app/error_codes.py
+++ b/saleor/app/error_codes.py
@@ -6,6 +6,10 @@ class AppErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"
INVALID_STATUS = "invalid_status"
+ INVALID_PERMISSION = "invalid_permission"
+ INVALID_MANIFEST_URL = "invalid_manifest_url"
+ INVALID_MANIFEST_FORMAT = "invalid_manifest_format"
+ MANIFEST_URL_CANT_CONNECT = "manifest_url_cant_connect"
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.py
index 8aa661a741..eef51fbf63 100644
--- a/saleor/graphql/app/mutations.py
+++ b/saleor/graphql/app/mutations.py
@@ -1,4 +1,7 @@
+from typing import List
+
import graphene
+import requests
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
@@ -6,13 +9,21 @@ from ...app import models
from ...app.error_codes import AppErrorCode
from ...app.tasks import install_app_task
from ...core import JobStatus
-from ...core.permissions import AppPermission, get_permissions
+from ...core.permissions import (
+ AppPermission,
+ get_permissions,
+ get_permissions_enum_list,
+)
from ..account.utils import can_manage_app
from ..core.enums import PermissionEnum
-from ..core.mutations import ModelDeleteMutation, ModelMutation
+from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import AppError
-from ..utils import get_user_or_app_from_context, requestor_is_superuser
-from .types import App, AppToken
+from ..utils import (
+ format_permissions_for_display,
+ get_user_or_app_from_context,
+ requestor_is_superuser,
+)
+from .types import App, AppToken, Manifest
from .utils import ensure_can_manage_permissions
@@ -320,7 +331,7 @@ class AppInstall(ModelMutation):
url_validator(url)
except (ValidationError, AttributeError):
msg = "Enter a valid URL."
- code = AppErrorCode.INVALID.value
+ code = AppErrorCode.INVALID_MANIFEST_URL.value
raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
@classmethod
@@ -342,3 +353,98 @@ class AppInstall(ModelMutation):
def post_save_action(cls, info, instance, cleaned_input):
activate_after_installation = cleaned_input["activate_after_installation"]
install_app_task.delay(instance.pk, activate_after_installation)
+
+
+class AppFetchManifest(BaseMutation):
+ manifest = graphene.Field(Manifest)
+
+ class Arguments:
+ manifest_url = graphene.String(required=True)
+
+ class Meta:
+ description = "Fetch and validate manifest."
+ permissions = (AppPermission.MANAGE_APPS,)
+ error_type_class = AppError
+ error_type_field = "app_errors"
+
+ @classmethod
+ def success_response(cls, instance):
+ """Return a success response."""
+ return cls(**{"manifest": instance, "errors": []})
+
+ @classmethod
+ def fetch_manifest(cls, manifest_url):
+ try:
+ response = requests.get(manifest_url)
+ response.raise_for_status()
+ return response.json()
+ except requests.HTTPError:
+ msg = "Unable to fetch manifest data."
+ code = AppErrorCode.MANIFEST_URL_CANT_CONNECT.value
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+ except ValueError:
+ msg = "Incorrect structure of manifest."
+ code = AppErrorCode.INVALID_MANIFEST_FORMAT.value
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+ except Exception:
+ msg = "Can't fetch manifest data. Please try later."
+ code = AppErrorCode.INVALID.valuer
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+
+ @classmethod
+ def clean_manifest_url(cls, manifest_url):
+ url_validator = URLValidator()
+ try:
+ url_validator(manifest_url)
+ except (ValidationError, AttributeError):
+ msg = "Enter a valid URL."
+ code = AppErrorCode.INVALID_MANIFEST_URL.value
+ raise ValidationError({"manifest_url": ValidationError(msg, code=code)})
+
+ @classmethod
+ def construct_instance(cls, instance, cleaned_data):
+ return Manifest(
+ identifier=cleaned_data.get("id"),
+ name=cleaned_data.get("name"),
+ about=cleaned_data.get("about"),
+ data_privacy=cleaned_data.get("dataPrivacy"),
+ data_privacy_url=cleaned_data.get("dataPrivacyUrl"),
+ homepage_url=cleaned_data.get("homepageUrl"),
+ support_url=cleaned_data.get("supportUrl"),
+ configuration_url=cleaned_data.get("configurationUrl"),
+ app_url=cleaned_data.get("appUrl"),
+ version=cleaned_data.get("version"),
+ token_target_url=cleaned_data.get("tokenTargetUrl"),
+ permissions=cleaned_data.get("permissions"),
+ )
+
+ @classmethod
+ def clean_permissions(cls, required_permissions: List[str]):
+ missing_permissions = []
+ all_permissions = {perm[0]: perm[1] for perm in get_permissions_enum_list()}
+ for perm in required_permissions:
+ if not all_permissions.get(perm):
+ missing_permissions.append(perm)
+ if missing_permissions:
+ error_msg = "Given permissions don't exist"
+ code = AppErrorCode.INVALID_PERMISSION.value
+ params = {"permissions": missing_permissions}
+ raise ValidationError(
+ {"permissions": ValidationError(error_msg, code=code, params=params)}
+ )
+
+ permissions = get_permissions(
+ [all_permissions[perm] for perm in required_permissions]
+ )
+ return format_permissions_for_display(permissions)
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ manifest_url = data.get("manifest_url")
+ cls.clean_manifest_url(manifest_url)
+ manifest_data = cls.fetch_manifest(manifest_url)
+ manifest_data["permissions"] = cls.clean_permissions(
+ manifest_data.get("permissions")
+ )
+ instance = cls.construct_instance(instance=None, cleaned_data=manifest_data)
+ return cls.success_response(instance)
diff --git a/saleor/graphql/app/schema.py b/saleor/graphql/app/schema.py
index 4d58aa996c..922a732415 100644
--- a/saleor/graphql/app/schema.py
+++ b/saleor/graphql/app/schema.py
@@ -9,6 +9,7 @@ from .mutations import (
AppCreate,
AppDelete,
AppDeleteFailedInstallation,
+ AppFetchManifest,
AppInstall,
AppRetryInstall,
AppTokenCreate,
@@ -67,3 +68,5 @@ class AppMutations(graphene.ObjectType):
app_install = AppInstall.Field()
app_retry_install = AppRetryInstall.Field()
app_delete_failed_installation = AppDeleteFailedInstallation.Field()
+
+ app_fetch_manifest = AppFetchManifest.Field()
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index 6d92fb11d9..4a7fe0fa25 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -13,6 +13,24 @@ from ..webhook.types import Webhook
from .enums import AppTypeEnum
+class Manifest(graphene.ObjectType):
+ identifier = graphene.String(required=True)
+ version = graphene.String(required=True)
+ name = graphene.String(required=True)
+ about = graphene.String()
+ permissions = graphene.List(Permission)
+ app_url = graphene.String()
+ configuration_url = graphene.String()
+ token_target_url = graphene.String()
+ data_privacy = graphene.String()
+ data_privacy_url = graphene.String()
+ homepage_url = graphene.String()
+ support_url = graphene.String()
+
+ class Meta:
+ description = "The manifest definition."
+
+
class AppToken(CountableDjangoObjectType):
name = graphene.String(description="Name of the authenticated token.")
auth_token = graphene.String(description="Last 4 characters of the token.")
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a9e1fea065..fc4fcd0d48 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -255,6 +255,10 @@ enum AppErrorCode {
GRAPHQL_ERROR
INVALID
INVALID_STATUS
+ INVALID_PERMISSION
+ INVALID_MANIFEST_URL
+ INVALID_MANIFEST_FORMAT
+ MANIFEST_URL_CANT_CONNECT
NOT_FOUND
REQUIRED
UNIQUE
@@ -262,6 +266,12 @@ enum AppErrorCode {
OUT_OF_SCOPE_PERMISSION
}
+type AppFetchManifest {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ manifest: Manifest
+ appErrors: [AppError!]!
+}
+
input AppFilterInput {
search: String
isActive: Boolean
@@ -2058,6 +2068,21 @@ type LanguageDisplay {
language: String!
}
+type Manifest {
+ identifier: String!
+ version: String!
+ name: String!
+ about: String
+ permissions: [Permission]
+ appUrl: String
+ configurationUrl: String
+ tokenTargetUrl: String
+ dataPrivacy: String
+ dataPrivacyUrl: String
+ homepageUrl: String
+ supportUrl: String
+}
+
type Margin {
start: Int
stop: Int
@@ -2535,6 +2560,7 @@ type Mutation {
appInstall(input: AppInstallInput!): AppInstall
appRetryInstall(activateAfterInstallation: Boolean = true, id: ID!): AppRetryInstall
appDeleteFailedInstallation(id: ID!): AppDeleteFailedInstallation
+ appFetchManifest(manifestUrl: String!): AppFetchManifest
requestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordReset
confirmAccount(email: String!, token: String!): ConfirmAccount
setPassword(token: String!, email: String!, password: String!): SetPassword
diff --git a/tests/api/app/mutations/test_app_fetch_manifest.py b/tests/api/app/mutations/test_app_fetch_manifest.py
new file mode 100644
index 0000000000..50dd99a4c3
--- /dev/null
+++ b/tests/api/app/mutations/test_app_fetch_manifest.py
@@ -0,0 +1,138 @@
+import pytest
+
+from tests.api.utils import assert_no_permission, get_graphql_content
+
+APP_FETCH_MANIFEST_MUTATION = """
+mutation AppFetchManifest($manifest_url: String!){
+ appFetchManifest(manifestUrl:$manifest_url){
+ manifest{
+ identifier
+ version
+ about
+ name
+ appUrl
+ configurationUrl
+ tokenTargetUrl
+ dataPrivacy
+ dataPrivacyUrl
+ homepageUrl
+ supportUrl
+ permissions{
+ code
+ }
+ }
+ appErrors{
+ field
+ message
+ code
+ }
+ }
+}
+"""
+
+
+def test_app_fetch_manifest(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"]["appErrors"]
+ manifest = content["data"]["appFetchManifest"]["manifest"]
+ assert not errors
+ assert manifest["identifier"] == "app2"
+ assert manifest["version"] == "1.0.0"
+ assert manifest["about"] == "Lorem ipsum"
+ assert manifest["name"] == "app"
+ assert manifest["appUrl"] == "http://localhost:8888/app"
+ assert manifest["configurationUrl"] == "htpp://localhost:8888/configuration"
+ assert manifest["tokenTargetUrl"] == "http://localhost:3000/register"
+ assert manifest["dataPrivacy"] == "Lorem ipsum"
+ assert manifest["dataPrivacyUrl"] == "http://localhost:8888/app-data-privacy"
+ assert manifest["homepageUrl"] == "http://localhost:8888/homepage"
+ assert manifest["supportUrl"] == "http://localhost:8888/support"
+ assert set([perm["code"] for perm in manifest["permissions"]]) == {
+ "MANAGE_ORDERS",
+ "MANAGE_USERS",
+ }
+
+
+def test_app_fetch_manifest_missing_permission(staff_api_client, staff_user):
+ manifest_url = "http://localhost:3000/manifest"
+ query = APP_FETCH_MANIFEST_MUTATION
+ variables = {
+ "manifest_url": manifest_url,
+ }
+ response = staff_api_client.post_graphql(query, variables=variables,)
+ assert_no_permission(response)
+
+
+def test_app_fetch_manifest_incorrect_permission_in_manifest(
+ staff_user, staff_api_client, permission_manage_apps
+):
+ manifest_url = "http://localhost:3000/manifest-with-wrong-perm"
+ 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"]["appErrors"]
+ manifest = content["data"]["appFetchManifest"]["manifest"]
+ assert len(errors) == 1
+ assert errors[0] == {
+ "field": "permissions",
+ "message": "Given permissions don't exist",
+ "code": "INVALID_PERMISSION",
+ }
+ assert not manifest
+
+
+def test_app_fetch_manifest_unable_to_connect(
+ staff_user, staff_api_client, permission_manage_apps
+):
+ manifest_url = "http://localhost:3000/manifest-doesnt-exist"
+ 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"]["appErrors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "field": "manifestUrl",
+ "message": "Unable to fetch manifest data.",
+ "code": "MANIFEST_URL_CANT_CONNECT",
+ }
+
+
+def test_app_fetch_manifest_wrong_format_of_response(
+ staff_user, staff_api_client, permission_manage_apps
+):
+ manifest_url = "http://localhost:3000/manifest-wrong-format"
+ 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"]["appErrors"]
+
+ assert len(errors) == 1
+ assert errors[0] == {
+ "field": "manifestUrl",
+ "message": "Incorrect structure of manifest.",
+ "code": "INVALID_MANIFEST_FORMAT",
+ }