Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce `PUBLIC_URL` environment variable (#13841)
Przemysław Łada7bf181353377
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a8d7b067a..0e0c477aa7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes- Fix thumbnail redirects sometimes failing with an unsafe redirect warning - #14023 by @patrys+- New environment variable `PUBLIC_URL` to define URL on which Saleor is hosted (e.g., https://api.example.com/). Takes precedence over `ENABLE_SSL` and `Shop.domain` for URL generation - #13841 by @przlada# 3.16.0diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 18eca43dd9..e48b84a82c 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -7,7 +7,6 @@ import requestsfrom celery.exceptions import MaxRetriesExceededErrorfrom celery.utils.log import get_task_loggerfrom django.conf import settings-from django.contrib.sites.models import Sitefrom django.core.exceptions import ObjectDoesNotExist, ValidationErrorfrom django.core.files import Filefrom django.core.files.storage import default_storage@@ -19,7 +18,7 @@ from .. import schema_versionfrom ..app.headers import AppHeaders, DeprecatedAppHeadersfrom ..celeryconf import appfrom ..core.http_client import HTTPClient-from ..core.utils import build_absolute_uri+from ..core.utils import build_absolute_uri, get_domainfrom ..permission.enums import get_permission_namesfrom ..plugins.manager import PluginsManagerfrom ..thumbnail import ICON_MIME_TYPES@@ -54,7 +53,7 @@ def validate_app_install_response(response: Response):def send_app_token(target_url: str, token: str):- domain = Site.objects.get_current().domain+ domain = get_domain()headers = {"Content-Type": "application/json",# X- headers will be deprecated in Saleor 4.0, proper headers are without X-diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.pyindex ba8178e338..8155b0c502 100644--- a/saleor/app/management/commands/create_app.py+++ b/saleor/app/management/commands/create_app.py@@ -1,7 +1,6 @@import jsonfrom typing import Any, Dict, Optional-from django.contrib.sites.models import Sitefrom django.core.management import BaseCommand, CommandErrorfrom django.core.management.base import CommandParserfrom django.urls import reverse@@ -10,7 +9,7 @@ from requests.exceptions import RequestExceptionfrom .... import schema_versionfrom ....app.headers import AppHeaders, DeprecatedAppHeadersfrom ....core.http_client import HTTPClient-from ....core.utils import build_absolute_uri+from ....core.utils import build_absolute_uri, get_domainfrom ...models import Appfrom .utils import clean_permissions@@ -43,7 +42,7 @@ class Command(BaseCommand):)def send_app_data(self, target_url, data: Dict[str, Any]):- domain = Site.objects.get_current().domain+ domain = get_domain()headers = {# X- headers will be deprecated in Saleor 4.0, proper headers are without X-DeprecatedAppHeaders.DOMAIN: domain,diff --git a/saleor/core/jwt_manager.py b/saleor/core/jwt_manager.pyindex f616e080b1..d075669562 100644--- a/saleor/core/jwt_manager.py+++ b/saleor/core/jwt_manager.py@@ -8,7 +8,6 @@ from authlib.jose import JsonWebKeyfrom cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom django.conf import settings-from django.contrib.sites.models import Sitefrom django.core.exceptions import ImproperlyConfiguredfrom django.core.management.color import color_stylefrom django.urls import reverse@@ -16,7 +15,7 @@ from django.utils.module_loading import import_stringfrom jwt import api_jwsfrom jwt.algorithms import RSAAlgorithm-from .utils import build_absolute_uri+from .utils import build_absolute_uri, get_domainlogger = logging.getLogger(__name__)@@ -72,7 +71,7 @@ class JWTManager(JWTManagerBase):@classmethoddef get_domain(cls) -> str:- return Site.objects.get_current().domain+ return get_domain()@classmethoddef get_private_key(cls) -> rsa.RSAPrivateKey:diff --git a/saleor/core/notification/utils.py b/saleor/core/notification/utils.pyindex b99d4e518c..eb633e1a48 100644--- a/saleor/core/notification/utils.py+++ b/saleor/core/notification/utils.py@@ -1,7 +1,7 @@from django.contrib.sites.models import Sitefrom django.contrib.staticfiles.storage import staticfiles_storage-from ..utils import build_absolute_uri+from ..utils import build_absolute_uri, get_domainLOGO_URL = "images/saleor-logo-sign.png"@@ -9,7 +9,7 @@ LOGO_URL = "images/saleor-logo-sign.png"def get_site_context():site: Site = Site.objects.get_current()site_context = {- "domain": site.domain,+ "domain": get_domain(),"site_name": site.name,"logo_url": build_absolute_uri(staticfiles_storage.url(LOGO_URL)),}diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex 3600d22f55..e5d81ac37e 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -22,6 +22,8 @@ from ..utils import (build_absolute_uri,generate_unique_slug,get_client_ip,+ get_domain,+ is_ssl_enabled,prepare_unique_attribute_value_slug,random_data,)@@ -225,6 +227,68 @@ def test_build_absolute_uri_with_host(site_settings, settings):assert url == f"http://{host}/{location}"+ "public_url", ["https://api.example.com", "http://api.example.com"]+)[email protected]("enable_ssl", [True, False])[email protected]("host", [None, "test.com"])+def test_build_absolute_uri_with_public_url(+ public_url, enable_ssl, host, site_settings, settings+):+ # given+ location = "images/close.svg"+ settings.PUBLIC_URL = public_url+ settings.ENABLE_SSL = enable_ssl+ # when+ url = build_absolute_uri(location, host)+ # then+ assert url == f"{public_url}/{location}"+++def test_build_absolute_uri_with_public_url_and_absolute_location(+ site_settings, settings+):+ # given+ location = "https://example.com/static/images/image.jpg"+ settings.PUBLIC_URL = "https://api.example.com"+ # when+ url = build_absolute_uri(location)+ # then+ assert url == location++[email protected]("enable_ssl", [True, False])+def test_is_ssl_enabled(enable_ssl, settings):+ # given+ settings.ENABLE_SSL = enable_ssl+ # then+ assert is_ssl_enabled() == enable_ssl+++ "public_url, expected",+ [("https://api.example.com", True), ("http://api.example.com", False)],+)[email protected]("enable_ssl", [True, False])+def test_is_ssl_enabled_with_public_url(public_url, expected, enable_ssl, settings):+ # given+ settings.PUBLIC_URL = public_url+ settings.ENABLE_SSL = enable_ssl+ # then+ assert is_ssl_enabled() == expected+++def test_get_domain(site_settings, settings):+ assert get_domain() == site_settings.site.domain+++def test_get_domain_with_public_url(site_settings, settings):+ # given+ domain = "api.example.com"+ settings.PUBLIC_URL = f"https://{domain}"+ assert get_domain() == domain++def test_delete_sort_order_with_null_value(menu_item):"""Ensures there is no error when trying to delete a sortable item,which triggers a shifting of the sort orders--which can be null."""diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex 911cec90e3..9c4643b6f5 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,6 +1,6 @@import socketfrom typing import TYPE_CHECKING, Iterable, Optional, Union-from urllib.parse import urljoin+from urllib.parse import urljoin, urlparsefrom celery.utils.log import get_task_loggerfrom django.conf import settings@@ -20,15 +20,35 @@ if TYPE_CHECKING:from django.utils.safestring import SafeText+def get_domain(site: Optional[Site] = None) -> str:+ if settings.PUBLIC_URL:+ return urlparse(settings.PUBLIC_URL).netloc+ if site is None:+ site = Site.objects.get_current()+ return site.domain+++def get_public_url(domain: Optional[str] = None) -> str:+ if settings.PUBLIC_URL:+ return settings.PUBLIC_URL+ host = domain or Site.objects.get_current().domain+ protocol = "https" if settings.ENABLE_SSL else "http"+ return f"{protocol}://{host}"+++def is_ssl_enabled() -> bool:+ if settings.PUBLIC_URL:+ return urlparse(settings.PUBLIC_URL).scheme.lower() == "https"+ return settings.ENABLE_SSL++def build_absolute_uri(location: str, domain: Optional[str] = None) -> str:"""Create absolute uri from location.If provided location is absolute uri by itself, it returns unchanged value,otherwise if provided location is relative, absolute uri is built and returned."""- host = domain or Site.objects.get_current().domain- protocol = "https" if settings.ENABLE_SSL else "http" # type: ignore[misc] # circular import # noqa: E501- current_uri = f"{protocol}://{host}"+ current_uri = get_public_url(domain)location = urljoin(current_uri, location)return iri_to_uri(location)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 25024ea651..b08ffbeebb 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -14399,14 +14399,16 @@ type Mutation {): StaffNotificationRecipientDelete @doc(category: "Users")"""- Updates site domain of the shop.+ Updates site domain of the shop.++ DEPRECATED: this mutation will be removed in Saleor 4.0. Use `PUBLIC_URL` environment variable instead.Requires one of the following permissions: MANAGE_SETTINGS."""shopDomainUpdate("""Fields required to update site."""input: SiteDomainInput- ): ShopDomainUpdate @doc(category: "Shop")+ ): ShopDomainUpdate @doc(category: "Shop") @deprecated(reason: "\\n\\nDEPRECATED: this mutation will be removed in Saleor 4.0. Use `PUBLIC_URL` environment variable instead.")"""Updates shop settings.@@ -19782,7 +19784,9 @@ type StaffNotificationRecipientDelete @doc(category: "Users") {}"""-Updates site domain of the shop.+Updates site domain of the shop.++DEPRECATED: this mutation will be removed in Saleor 4.0. Use `PUBLIC_URL` environment variable instead.Requires one of the following permissions: MANAGE_SETTINGS."""diff --git a/saleor/graphql/shop/mutations/shop_domain_update.py b/saleor/graphql/shop/mutations/shop_domain_update.pyindex dfd314d2b3..798ab0165f 100644--- a/saleor/graphql/shop/mutations/shop_domain_update.py+++ b/saleor/graphql/shop/mutations/shop_domain_update.py@@ -2,6 +2,7 @@ import graphenefrom ....permission.enums import SitePermissionsfrom ...core import ResolveInfo+from ...core.descriptions import DEPRECATED_IN_3X_MUTATIONfrom ...core.doc_category import DOC_CATEGORY_SHOPfrom ...core.mutations import BaseMutationfrom ...core.types import ShopError@@ -24,7 +25,11 @@ class ShopDomainUpdate(BaseMutation):input = SiteDomainInput(description="Fields required to update site.")class Meta:- description = "Updates site domain of the shop."+ description = (+ "Updates site domain of the shop."+ + DEPRECATED_IN_3X_MUTATION+ + " Use `PUBLIC_URL` environment variable instead."+ )doc_category = DOC_CATEGORY_SHOPpermissions = (SitePermissions.MANAGE_SETTINGS,)error_type_class = ShopErrordiff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.pyindex f34e749128..bc0de30b09 100644--- a/saleor/graphql/shop/schema.py+++ b/saleor/graphql/shop/schema.py@@ -80,7 +80,10 @@ class ShopMutations(graphene.ObjectType):staff_notification_recipient_update = StaffNotificationRecipientUpdate.Field()staff_notification_recipient_delete = StaffNotificationRecipientDelete.Field()- shop_domain_update = ShopDomainUpdate.Field()+ shop_domain_update = ShopDomainUpdate.Field(+ deprecation_reason=DEPRECATED_IN_3X_MUTATION+ + " Use `PUBLIC_URL` environment variable instead."+ )shop_settings_update = ShopSettingsUpdate.Field()shop_fetch_tax_rates = ShopFetchTaxRates.Field(deprecation_reason=DEPRECATED_IN_3X_MUTATIONdiff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 3f74bf5dc0..d995f500e1 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -9,7 +9,7 @@ from ... import __version__, schema_versionfrom ...account import models as account_modelsfrom ...channel import models as channel_modelsfrom ...core.models import ModelWithMetadata-from ...core.utils import build_absolute_uri+from ...core.utils import build_absolute_uri, get_domain, is_ssl_enabledfrom ...permission.auth_filters import AuthorizationFiltersfrom ...permission.enums import SitePermissions, get_permissionsfrom ...site import models as site_models@@ -428,8 +428,8 @@ class Shop(graphene.ObjectType):@load_site_callbackdef resolve_domain(_, _info, site):return Domain(- host=site.domain,- ssl_enabled=settings.ENABLE_SSL,+ host=get_domain(site),+ ssl_enabled=is_ssl_enabled(),url=build_absolute_uri("/"),)diff --git a/saleor/graphql/webhook/subscription_payload.py b/saleor/graphql/webhook/subscription_payload.pyindex 5a843ab10c..84bb7e3dd1 100644--- a/saleor/graphql/webhook/subscription_payload.py+++ b/saleor/graphql/webhook/subscription_payload.py@@ -10,7 +10,7 @@ from promise import Promisefrom ...app.models import Appfrom ...core.exceptions import PermissionDenied-from ...settings import get_host+from ...core.utils import get_domainfrom ..core import SaleorContextfrom ..utils import format_error@@ -35,7 +35,7 @@ def initialize_request(request.path = "/graphql/"request.path_info = "/graphql/"request.method = "GET"- request.META = {"SERVER_NAME": SimpleLazyObject(get_host), "SERVER_PORT": "80"}+ request.META = {"SERVER_NAME": SimpleLazyObject(get_domain), "SERVER_PORT": "80"}if settings.ENABLE_SSL:request.META["HTTP_X_FORWARDED_PROTO"] = "https"request.META["SERVER_PORT"] = "443"diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.pyindex 16982f1dc5..dc1d181bc0 100644--- a/saleor/payment/gateways/stripe/plugin.py+++ b/saleor/payment/gateways/stripe/plugin.py@@ -1,12 +1,12 @@import loggingfrom typing import TYPE_CHECKING, List, Optional, Tuple-from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFoundfrom django.http.request import split_domain_port+from ....core.utils import get_domainfrom ....graphql.core.enums import PluginErrorCodefrom ....plugins.base_plugin import BasePlugin, ConfigurationTypeFieldfrom ... import TransactionKind@@ -21,6 +21,15 @@ from ...interface import (from ...models import Transactionfrom ...utils import price_from_minor_unit, price_to_minor_unitfrom ..utils import get_supported_currencies+from .consts import (+ ACTION_REQUIRED_STATUSES,+ AUTHORIZED_STATUS,+ PLUGIN_ID,+ PLUGIN_NAME,+ PROCESSING_STATUS,+ SUCCESS_STATUS,+ WEBHOOK_PATH,+)from .stripe_api import (cancel_payment_intent,capture_payment_intent,@@ -39,15 +48,6 @@ from .webhooks import handle_webhookif TYPE_CHECKING:from ....plugins.models import PluginConfiguration-from .consts import (- ACTION_REQUIRED_STATUSES,- AUTHORIZED_STATUS,- PLUGIN_ID,- PLUGIN_NAME,- PROCESSING_STATUS,- SUCCESS_STATUS,- WEBHOOK_PATH,-)logger = logging.getLogger(__name__)@@ -509,7 +509,7 @@ class StripeGatewayPlugin(BasePlugin):# check saved domain. Make sure that it is not localhost domain. We are not able# to subscribe to stripe webhooks with localhost.- domain = Site.objects.get_current().domain+ domain = get_domain()localhost_domains = ["localhost", "127.0.0.1"]domain, _ = split_domain_port(domain)if not domain:diff --git a/saleor/payment/gateways/stripe/stripe_api.py b/saleor/payment/gateways/stripe/stripe_api.pyindex 263b022aac..f4dfc17695 100644--- a/saleor/payment/gateways/stripe/stripe_api.py+++ b/saleor/payment/gateways/stripe/stripe_api.py@@ -5,13 +5,12 @@ from typing import Dict, List, Optional, Tuplefrom urllib.parse import urljoinimport stripe-from django.contrib.sites.models import Sitefrom django.urls import reversefrom stripe.error import AuthenticationError, InvalidRequestError, StripeErrorfrom stripe.stripe_object import StripeObjectfrom ....core.tracing import opentracing_trace-from ....core.utils import build_absolute_uri+from ....core.utils import build_absolute_uri, get_domainfrom ...interface import PaymentMethodInfofrom ...utils import price_to_minor_unitfrom .consts import (@@ -60,7 +59,7 @@ def _extra_log_data(error: StripeError, payment_intent_id: Optional[str] = None)def subscribe_webhook(api_key: str, channel_slug: str) -> Optional[StripeObject]:- domain = Site.objects.get_current().domain+ domain = get_domain()api_path = reverse("plugins-per-channel",kwargs={"plugin_id": PLUGIN_ID, "channel_slug": channel_slug},diff --git a/saleor/settings.py b/saleor/settings.pyindex e054806d42..577d1f1e73 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -4,7 +4,8 @@ import osimport os.pathimport warningsfrom datetime import timedelta-from typing import List+from typing import List, Optional+from urllib.parse import urlparseimport dj_database_urlimport dj_email_url@@ -18,6 +19,7 @@ from celery.schedules import crontabfrom django.conf import global_settingsfrom django.core.exceptions import ImproperlyConfiguredfrom django.core.management.utils import get_random_secret_key+from django.core.validators import URLValidatorfrom graphql.execution import executorfrom pytimeparse import parsefrom sentry_sdk.integrations.celery import CeleryIntegration@@ -45,6 +47,15 @@ def get_bool_from_env(name, default_value):return default_value+def get_url_from_env(name, *, schemes=None) -> Optional[str]:+ if name in os.environ:+ value = os.environ[name]+ message = f"{value} is an invalid value for {name}"+ URLValidator(schemes=schemes, message=message)(value)+ return value+ return None++DEBUG = get_bool_from_env("DEBUG", True)SITE_ID = 1@@ -136,7 +147,15 @@ EMAIL_BACKEND: str = email_config.get("EMAIL_BACKEND", "")EMAIL_USE_TLS: bool = email_config.get("EMAIL_USE_TLS", False)EMAIL_USE_SSL: bool = email_config.get("EMAIL_USE_SSL", False)-ENABLE_SSL = get_bool_from_env("ENABLE_SSL", False)+ENABLE_SSL: bool = get_bool_from_env("ENABLE_SSL", False)++# URL on which Saleor is hosted (e.g., https://api.example.com/). This has precedence+# over ENABLE_SSL and Shop.domain when generating URLs pointing to itself.+PUBLIC_URL: Optional[str] = get_url_from_env("PUBLIC_URL", schemes=["http", "https"])+if PUBLIC_URL:+ if os.environ.get("ENABLE_SSL") is not None:+ warnings.warn("ENABLE_SSL is ignored on URL generation if PUBLIC_URL is set.")+ ENABLE_SSL = urlparse(PUBLIC_URL).scheme.lower() == "https"if ENABLE_SSL:SECURE_SSL_REDIRECT = not DEBUG@@ -407,17 +426,6 @@ DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH = 78COUNTRIES_OVERRIDE = {"EU": "European Union"}--def get_host():- from django.contrib.sites.models import Site-- return Site.objects.get_current().domain---PAYMENT_HOST = get_host--PAYMENT_MODEL = "order.Payment"-MAX_USER_ADDRESSES = int(os.environ.get("MAX_USER_ADDRESSES", 100))TEST_RUNNER = "saleor.tests.runner.PytestTestRunner"diff --git a/saleor/webhook/observability/utils.py b/saleor/webhook/observability/utils.pyindex 0e3cacd657..d19b36d96c 100644--- a/saleor/webhook/observability/utils.py+++ b/saleor/webhook/observability/utils.py@@ -9,12 +9,12 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optionalfrom asgiref.local import Localfrom django.conf import settings-from django.contrib.sites.models import Sitefrom django.core.cache import cachefrom django.utils import timezonefrom graphql import GraphQLDocumentfrom pytimeparse import parse+from ...core.utils import get_domainfrom ..event_types import WebhookEventAsyncTypefrom ..utils import get_webhooks_for_eventfrom .buffers import get_buffer@@ -66,7 +66,7 @@ def get_webhooks(timeout=CACHE_TIMEOUT) -> List[WebhookData]:if webhooks_data is None:webhooks_data = []if webhooks := get_webhooks_for_event(WebhookEventAsyncType.OBSERVABILITY):- domain = Site.objects.get_current().domain+ domain = get_domain()for webhook in webhooks:webhooks_data.append(WebhookData(diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex f98e6dd3b1..4004ccd3ef 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -6,12 +6,12 @@ from urllib.parse import urlparsefrom celery import groupfrom celery.utils.log import get_task_loggerfrom django.conf import settings-from django.contrib.sites.models import Sitefrom ....celeryconf import appfrom ....core import EventDeliveryStatusfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_trace+from ....core.utils import get_domainfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,initialize_request,@@ -181,7 +181,7 @@ def send_webhook_request_async(self, event_delivery_id):return Nonewebhook = delivery.webhook- domain = Site.objects.get_current().domain+ domain = get_domain()attempt = create_attempt(delivery, self.request.id)delivery_status = EventDeliveryStatus.SUCCESStry:diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 0df6fc8735..8291f376f0 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -6,13 +6,13 @@ from urllib.parse import urlparsefrom celery.utils.log import get_task_loggerfrom django.conf import settings-from django.contrib.sites.models import Sitefrom django.core.cache import cachefrom ....celeryconf import appfrom ....core import EventDeliveryStatusfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_trace+from ....core.utils import get_domainfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,initialize_request,@@ -90,7 +90,7 @@ def _send_webhook_request_sync(data = event_payload.payloadwebhook = delivery.webhookparts = urlparse(webhook.target_url)- domain = Site.objects.get_current().domain+ domain = get_domain()message = data.encode("utf-8")signature = signature_for_payload(message, webhook.secret_key)