Skip to content

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

Allow to set up the app without providing tokenTargetUrl (#18805)

Maciej Korycinski7e42fc67ce72
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ecf1bff233..6878045d95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,7 @@ Validation is now performed on the frontend (Dashboard). This change increases v
- Improve user search. Use search vector functionality to enable searching users by email address, first name, last name, and addresses.
- Improved checkout search with search vectors. The `search_index_dirty` flag is set whenever indexed checkout data changes, and a background task runs every minute to update search vectors for dirty checkouts, processing the oldest first. Search results are returned in order of best match relevance.
- Add optional usage telemetry. - #18789 by @wcislo-saleor
+- The app can now be installed without providing a `tokenTargetUrl` in the manifest file.
### Deprecations
- Deprecate the `hasVariants` field on `ProductType`.
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index c15685c3d9..12fd522cca 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -27,7 +27,7 @@ from ..thumbnail.validators import validate_icon_image
from ..webhook.models import Webhook, WebhookEvent
from .error_codes import AppErrorCode
from .manifest_validations import clean_manifest_data
-from .models import App, AppExtension, AppInstallation
+from .models import App, AppExtension, AppInstallation, AppToken
from .types import DEFAULT_APP_TARGET, AppType
MAX_ICON_FILE_SIZE = 1024 * 1024 * 10 # 10MB
@@ -212,7 +212,9 @@ def fetch_manifest(manifest_url: str, timeout=settings.COMMON_REQUESTS_TIMEOUT):
return response.json()
-def install_app(app_installation: AppInstallation, activate: bool = False):
+def install_app(
+ app_installation: AppInstallation, activate: bool = False
+) -> tuple[App, AppToken | None]:
manifest_data = fetch_manifest(app_installation.manifest_url)
assigned_permissions = app_installation.permissions.all()
@@ -296,14 +298,16 @@ def install_app(app_installation: AppInstallation, activate: bool = False):
)
WebhookEvent.objects.bulk_create(webhook_events)
- _, token = app.tokens.create(name="Default token") # type: ignore[call-arg] # calling create on a related manager # noqa: E501
+ token = None
+ if tokent_target_url := manifest_data.get("tokenTargetUrl"):
+ _, token = app.tokens.create(name="Default token") # type: ignore[call-arg] # calling create on a related manager # noqa: E501
- try:
- send_app_token(target_url=manifest_data.get("tokenTargetUrl"), token=token)
- except requests.RequestException as e:
- fetch_brand_data_async(manifest_data, app_installation=app_installation)
- app.delete()
- raise e
+ try:
+ send_app_token(target_url=tokent_target_url, token=token)
+ except requests.RequestException as e:
+ fetch_brand_data_async(manifest_data, app_installation=app_installation)
+ app.delete()
+ raise e
PluginsManager(plugins=settings.PLUGINS).app_installed(app)
fetch_brand_data_async(manifest_data, app=app)
return app, token
diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.py
index fe6414f315..658131b21d 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -75,4 +75,8 @@ class Command(BaseCommand):
app_job.save(update_fields=["status"])
raise e
- return json.dumps({"auth_token": token}) if not quiet else None
+ response_message = None
+ if token and not quiet:
+ response_message = json.dumps({"auth_token": token})
+
+ return response_message
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index 579a7c0f4a..8deab11861 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -54,15 +54,17 @@ def _clean_extension_url(extension: dict, manifest_data: dict):
"""
extension_url = extension["url"]
- # Assume app URL is the one that originally received the token.
- app_url = manifest_data.get("tokenTargetUrl")
-
- if not app_url:
- raise ValidationError("Manifest is invalid, token_target_url is missing")
-
- # Only validate absolute URLs (with protocol)
- # Relative URLs (starting with '/') are allowed when tokenTargetUrl is provided
- if not extension_url.startswith("/"):
+ if extension_url.startswith("/"):
+ # Relative URLs (starting with '/') are allowed when appUrl is provided
+ # Assume app URL is the one that originally received the token.
+ app_url = manifest_data.get("appUrl")
+
+ if not app_url:
+ raise ValidationError(
+ "Relative extension URL (starting with /) "
+ "must be paired with appUrl in the app manifest"
+ )
+ else:
_clean_app_url(extension_url)
@@ -100,8 +102,8 @@ def clean_manifest_data(manifest_data, raise_for_saleor_version=False):
_validate_required_fields(manifest_data, errors)
try:
- if "tokenTargetUrl" in manifest_data:
- _clean_app_url(manifest_data["tokenTargetUrl"])
+ if token_target_url := manifest_data.get("tokenTargetUrl"):
+ _clean_app_url(token_target_url)
except (ValidationError, AttributeError):
errors["tokenTargetUrl"].append(
ValidationError(
@@ -294,7 +296,7 @@ def _clean_webhooks(manifest_data, errors):
def _validate_required_fields(manifest_data, errors):
- manifest_required_fields = {"id", "version", "name", "tokenTargetUrl"}
+ manifest_required_fields = {"id", "version", "name"}
extension_required_fields = {"label", "url", "mount"}
webhook_required_fields = {"name", "targetUrl", "query"}
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 6ff4d98b75..724b08ec7d 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -51,7 +51,10 @@ 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, app_manifest):
+def test_creates_app_from_manifest_sends_token_when_target_url_provided(
+ monkeypatch, app_manifest
+):
+ # given
mocked_get = Mock(return_value=Mock())
mocked_get.return_value.json = Mock(return_value=app_manifest)
@@ -70,8 +73,10 @@ def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
monkeypatch.setattr(HTTPSession, "request", _side_effect)
manifest_url = "http://localhost:3000/manifest"
+ # when
call_command("install_app", manifest_url)
+ # then
get_call = call(
"GET",
manifest_url,
@@ -96,6 +101,47 @@ def test_creates_app_from_manifest_sends_token(monkeypatch, app_manifest):
)
+def test_creates_app_from_manifest_skips_sending_token_when_target_url_not_provided(
+ monkeypatch, app_manifest
+):
+ # given
+ app_manifest.pop("tokenTargetUrl")
+
+ 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
+
+ def _side_effect(_self, method, *args, **kwargs):
+ if method == "GET":
+ func = mocked_get
+ elif method == "POST":
+ func = mocked_post
+ else:
+ raise NotImplementedError("Method not implemented", method)
+ return func(method, *args, **kwargs)
+
+ monkeypatch.setattr(HTTPSession, "request", _side_effect)
+ manifest_url = "http://localhost:3000/manifest"
+
+ # when
+ call_command("install_app", manifest_url)
+
+ # then
+ app = App.objects.get()
+ get_call = call(
+ "GET",
+ manifest_url,
+ headers={"Saleor-Schema-Version": schema_version},
+ timeout=ANY,
+ allow_redirects=False,
+ )
+ mocked_get.assert_has_calls([get_call, get_call])
+ assert not mocked_post.called
+ assert app.tokens.count() == 0
+
+
@pytest.mark.vcr
def test_creates_app_from_manifest_installation_failed():
manifest_url = "http://localhost:3000/manifest-wrong"
diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.py
index 71db12ac54..ef16556aac 100644
--- a/saleor/app/tests/test_installation_utils.py
+++ b/saleor/app/tests/test_installation_utils.py
@@ -737,7 +737,7 @@ def test_install_app_webhook_incorrect_custom_headers(
)
-def test_install_app_lack_of_token_target_url_in_manifest_data(
+def test_install_app_manifest_data_without_token_target_url(
app_manifest, app_installation, monkeypatch, permission_manage_products
):
# given
@@ -753,13 +753,11 @@ def test_install_app_lack_of_token_target_url_in_manifest_data(
app_installation.permissions.set([permission_manage_products])
- # when & then
- with pytest.raises(ValidationError) as excinfo:
- install_app(app_installation, activate=True)
+ # when
+ install_app(app_installation, activate=True)
- error_dict = excinfo.value.error_dict
- assert "tokenTargetUrl" in error_dict
- assert error_dict["tokenTargetUrl"][0].message == "Field required."
+ # then
+ assert App.objects.count() == 1
@pytest.fixture
diff --git a/saleor/app/tests/test_validators.py b/saleor/app/tests/test_validators.py
index 19300300dc..690a5cb784 100644
--- a/saleor/app/tests/test_validators.py
+++ b/saleor/app/tests/test_validators.py
@@ -106,4 +106,5 @@ def test_new_tab_relative_url_without_app_url(app_manifest):
app_manifest["extensions"] = [extension]
# when & then
- _clean_extension_url(extension, manifest_data=app_manifest)
+ with pytest.raises(ValidationError):
+ _clean_extension_url(extension, manifest_data=app_manifest)
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 e52c86a06d..e49be4c499 100644
--- a/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
+++ b/saleor/graphql/app/tests/mutations/test_app_fetch_manifest.py
@@ -921,6 +921,7 @@ def test_app_fetch_manifest_extension_with_relative_url(
staff_api_client, app_manifest, permission_manage_apps, monkeypatch
):
# given
+ app_manifest["appUrl"] = "http://127.0.0.1:5000"
app_manifest["extensions"] = [
{
"permissions": [],