Skip to content

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

POC: Setting to block customer and anonymous traffic (#19490)

Lukasz Ostrowski1518a613e6b9
diff --git a/AGENTS.md b/AGENTS.md
index 6b39ff4dcc..1ddb662936 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,6 +25,25 @@ many processes at once. Write code with that in mind:
- **Make tasks idempotent and safe to retry** — the broker may deliver a task more than once, and pods
can be killed/rescheduled mid-run.
+## Multi-tenancy: never rely on `settings.SITE_ID`
+
+A deployment may serve **several sites from one process**, and `SITE_ID` may be unset or differ from
+what a dev environment has. Never read it directly to identify the current site, and never assume
+there is only one.
+
+- **Resolve the site with `Site.objects.get_current()`** (or the `get_site_promise` dataloader in the
+ GraphQL layer). Both pick the site by `SITE_ID` when it is configured and fall back to the request
+ host when it is not — `settings.SITE_ID` alone silently collapses every tenant into one.
+- **Key anything per-site by the resolved site**, not by a constant. A cache key, module-level dict or
+ query filter that bakes in a single site lets one tenant read another's data.
+- **Don't assume a single row.** `Site.objects.get()` breaks as soon as a second site exists; filter by
+ the resolved site instead.
+
+`Site.objects.get_current()` reads the patched process-global `THREADED_SITE_CACHE`
+(`saleor/site/patch_sites.py`), which is never invalidated by `Site`/`SiteSettings` saves. So a value
+read through it can be stale after a write in the same process — see *Writing tests* for what that
+means for assertions.
+
## Graphql
### API versioning
@@ -99,6 +118,12 @@ database/cache or collide with another worktree's stack.
def test_something(_case, value): ...
```
- When a mutation input is optional/nullable, test the explicit `null` value in addition to omitting the field — they are distinct inputs and can be handled differently.
+- **Never assume a cache is cold — or warm.** Caches are process-global and survive across tests, so
+ what warmed them depends on test ordering. To assert a write landed, read the row back
+ (`obj.refresh_from_db(fields=(...))`) rather than through a cached accessor like
+ `Site.objects.get_current()`; to count queries, warm the cache first so the count is the steady
+ state; otherwise bust it explicitly (`Site.objects.clear_cache()`). A test that passes only because
+ a cache happened to be empty will fail as soon as an unrelated caller warms it.
### Assert precisely (the #1 source of review comments)
diff --git a/docs/adr/0006-storefront-traffic-blocking-accepted-risks.md b/docs/adr/0006-storefront-traffic-blocking-accepted-risks.md
new file mode 100644
index 0000000000..de58135851
--- /dev/null
+++ b/docs/adr/0006-storefront-traffic-blocking-accepted-risks.md
@@ -0,0 +1,43 @@
+# Accepted risks for storefront traffic blocking
+
+**Tags:** graphql, security, storefront, oidc
+
+Merchants can disable direct **storefront traffic** to the GraphQL API so only
+staff users and apps are allowed to call the API directly. This is intended as a
+way to limit public traffic-control.
+
+The feature deliberately accepts a few risks to keep the implementation simple.
+
+## Risk: cache evictions & replica delays
+
+The enforcement decision uses a short-lived cache for `allow_storefront_traffic`.
+On cache miss, the setting may be read from a DB replica which can mean a recent
+setting change can cause public traffic to be allowed while it should have been
+blcked instead.
+
+This is accepted because the setting taking time to propagate doesn't pose any
+real impact to merchants. This is an unrealistic risk and therefore shouldn't
+accounted for.
+
+This includes:
+- Cache evictions due to high memory pressure
+- Cache expiration (TTL exceeded)
+- Replication lag (miliseconds to multiple seconds)
+
+## Risk: rejection happens after request parsing and validation
+
+Blocked anonymous or customer traffic is rejected after parsing the body and
+after performing some other preparations to process the request, including
+running user-input validations (such as query cost).
+
+This means unauthenticated traffic hitting the HTTP workers while the storefront
+traffic is disabled requires considerable resources to process the requests prior
+to returning HTTP 401.
+
+This is accepted because moving the check earlier would require significant changes
+to the way Saleor handles HTTP requests without actually bringing any value to the
+project.
+
+The feature is only intended to be used for restricting public access, and not
+as way to guard against attacks; instead a WAF and other controls should be put
+in place by the deployer.
diff --git a/docs/adr/0007-storefront-traffic-blocking-applies-to-introspection-and-auth.md b/docs/adr/0007-storefront-traffic-blocking-applies-to-introspection-and-auth.md
new file mode 100644
index 0000000000..48fe2cb098
--- /dev/null
+++ b/docs/adr/0007-storefront-traffic-blocking-applies-to-introspection-and-auth.md
@@ -0,0 +1,30 @@
+# Storefront traffic blocking applies to introspection and authentication
+
+**Tags:** graphql, security, storefront, oidc
+
+When storefront traffic is disabled (`Shop.allowStorefrontTraffic = false`), the
+guard runs in the GraphQL view before the document is executed and rejects every
+non-privileged request with HTTP 401. It does not inspect the operation, so it
+also rejects:
+
+- **Introspection queries** — the schema is not readable without staff or app
+ credentials.
+- **Authentication operations** — `tokenCreate`, `tokenRefresh`,
+ `externalObtainAccessTokens` and friends. A customer cannot obtain a token, so
+ a customer can never become privileged enough to pass the guard.
+
+This is by design. Exempting operations would mean parsing and classifying the
+document before the check, adding an allowlist that must be kept in sync with
+every new auth-related mutation, and leaving a public surface that defeats the
+point of the setting.
+
+The setting is intended for deployments that put a **proxy in front of the whole
+API layer** — the proxy holds app or staff credentials (or terminates the
+storefront's own auth) and is the only thing talking to Saleor directly. In that
+topology introspection and login both happen through the proxy, so nothing needs
+to be exempt.
+
+Merchants that need public login or public introspection should not enable this
+setting.
+
+See also: [0006](0006-storefront-traffic-blocking-accepted-risks.md).
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 0f3c94b3ad..0c915e34eb 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -1321,7 +1321,7 @@ def test_add_checkout_lines_gift_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(143):
+ with django_assert_num_queries(141):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/conftest.py b/saleor/graphql/conftest.py
new file mode 100644
index 0000000000..618fb26862
--- /dev/null
+++ b/saleor/graphql/conftest.py
@@ -0,0 +1,22 @@
+import pytest
+from django.contrib.sites.models import Site
+
+from .storefront_traffic import set_allow_storefront_traffic_cache
+
+
[email protected](autouse=True)
+def _warm_storefront_traffic_cache():
+ """Keep the storefront-traffic guard from adding DB queries per request.
+
+ ``is_storefront_traffic_blocked`` resolves the current site and lazily loads the
+ shop setting, caching both. In production those caches are warm, so the guard
+ performs no DB query. Warm them here as well so query-count benchmarks measure
+ the steady state and stay deterministic regardless of test ordering — a test must
+ never assume either cache is cold.
+
+ Tests that exercise the blocking path (e.g. ``storefront_traffic_disabled``)
+ explicitly clear/override the cache after this autouse fixture runs, so they
+ are unaffected.
+ """
+ Site.objects.get_current()
+ set_allow_storefront_traffic_cache(True)
diff --git a/saleor/graphql/core/context.py b/saleor/graphql/core/context.py
index a44afd71fb..9c1566ff11 100644
--- a/saleor/graphql/core/context.py
+++ b/saleor/graphql/core/context.py
@@ -60,10 +60,17 @@ def get_database_connection_name(context: SaleorContext) -> str:
def setup_context_user(context: SaleorContext) -> None:
- if hasattr(context.user, "_wrapped") and (
- context.user._wrapped is empty or context.user._wrapped is None # type: ignore[union-attr]
- ):
- context.user._setup() # type: ignore[union-attr]
+ """Replace the lazy ``context.user`` proxy with the resolved user object.
+
+ Resolve the ``SimpleLazyObject`` if it has not been accessed yet, then unwrap
+ it unconditionally. Unwrapping only in the ``empty``/``None`` case leaves the
+ proxy in place whenever something (e.g. the storefront-traffic guard) already
+ forced authentication earlier in the request, so downstream code would see a
+ ``SimpleLazyObject`` instead of a plain ``User``.
+ """
+ if hasattr(context.user, "_wrapped"):
+ if context.user._wrapped is empty: # type: ignore[union-attr]
+ context.user._setup() # type: ignore[union-attr]
context.user = context.user._wrapped # type: ignore[union-attr]
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index bcae5185bb..e61cad4dab 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -16,6 +16,11 @@ from ....core.telemetry import Scope, Unit
from ....tests.utils import get_metric_data, get_span_by_name
from ...api import backend, schema
from ...metrics import METRIC_GRAPHQL_BATCH_SIZE
+from ...storefront_traffic import (
+ STOREFRONT_TRAFFIC_ERROR_CODE,
+ STOREFRONT_TRAFFIC_ERROR_MESSAGE,
+ clear_allow_storefront_traffic_cache,
+)
from ...tests.fixtures import API_PATH
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
from ...utils import INTERNAL_ERROR_MESSAGE
@@ -453,47 +458,43 @@ query IntrospectionQuery {
INTROSPECTION_RESULT = {"__schema": {"queryType": {"name": "Query"}}}
[email protected]("saleor.graphql.views.cache.set")
[email protected]("saleor.graphql.views.cache.get")
+# Patch the `cache` name in the views module rather than `cache.get`/`cache.set` on the
+# cache object itself: the object is shared, so patching its methods would also capture
+# the storefront traffic guard's own lookups and break the call assertions below.
[email protected]("saleor.graphql.views.cache")
@override_settings(DEBUG=False, OBSERVABILITY_REPORT_ALL_API_CALLS=False)
-def test_introspection_query_is_cached(cache_get_mock, cache_set_mock, api_client):
- cache_get_mock.return_value = None
+def test_introspection_query_is_cached(cache_mock, api_client):
+ cache_mock.get.return_value = None
cache_key = generate_cache_key(INTROSPECTION_QUERY)
response = api_client.post_graphql(INTROSPECTION_QUERY)
content = get_graphql_content(response)
assert content["data"] == INTROSPECTION_RESULT
- cache_get_mock.assert_called_once_with(cache_key)
- cache_set_mock.assert_called_once_with(
+ cache_mock.get.assert_called_once_with(cache_key)
+ cache_mock.set.assert_called_once_with(
cache_key, ExecutionResult(data=INTROSPECTION_RESULT)
)
[email protected]("saleor.graphql.views.cache.set")
[email protected]("saleor.graphql.views.cache.get")
[email protected]("saleor.graphql.views.cache")
@override_settings(DEBUG=False, OBSERVABILITY_REPORT_ALL_API_CALLS=False)
-def test_introspection_query_is_cached_only_once(
- cache_get_mock, cache_set_mock, api_client
-):
- cache_get_mock.return_value = ExecutionResult(data=INTROSPECTION_RESULT)
+def test_introspection_query_is_cached_only_once(cache_mock, api_client):
+ cache_mock.get.return_value = ExecutionResult(data=INTROSPECTION_RESULT)
cache_key = generate_cache_key(INTROSPECTION_QUERY)
response = api_client.post_graphql(INTROSPECTION_QUERY)
content = get_graphql_content(response)
assert content["data"] == INTROSPECTION_RESULT
- cache_get_mock.assert_called_once_with(cache_key)
- cache_set_mock.assert_not_called()
+ cache_mock.get.assert_called_once_with(cache_key)
+ cache_mock.set.assert_not_called()
[email protected]("saleor.graphql.views.cache.set")
[email protected]("saleor.graphql.views.cache.get")
[email protected]("saleor.graphql.views.cache")
@override_settings(DEBUG=True, OBSERVABILITY_REPORT_ALL_API_CALLS=False)
-def test_introspection_query_is_not_cached_in_debug_mode(
- cache_get_mock, cache_set_mock, api_client
-):
+def test_introspection_query_is_not_cached_in_debug_mode(cache_mock, api_client):
response = api_client.post_graphql(INTROSPECTION_QUERY)
content = get_graphql_content(response)
assert content["data"] == INTROSPECTION_RESULT
- cache_get_mock.assert_not_called()
- cache_set_mock.assert_not_called()
+ cache_mock.get.assert_not_called()
+ cache_mock.set.assert_not_called()
def test_generate_cache_key_use_saleor_version():
@@ -592,3 +593,167 @@ def test_marks_slow_queries(rf, get_test_spans):
assert (
span.status.description == "Slow request. Exceeded time limit of 30.0 seconds."
)
+
+
+EXPECTED_STOREFRONT_TRAFFIC_ERROR = {
+ "errors": [
+ {
+ "message": STOREFRONT_TRAFFIC_ERROR_MESSAGE,
+ "extensions": {"code": STOREFRONT_TRAFFIC_ERROR_CODE},
+ }
+ ]
+}
+
+
+def set_allow_storefront_traffic(site_settings):
+ """Set the storefront traffic flag and keep the guard cache honest."""
+
+ def set_flag(allowed):
+ site_settings.allow_storefront_traffic = allowed
+ site_settings.save(update_fields=["allow_storefront_traffic"])
+ clear_allow_storefront_traffic_cache()
+ return site_settings
+
+ yield set_flag
+ clear_allow_storefront_traffic_cache()
+
+
+def storefront_traffic_disabled(set_allow_storefront_traffic):
+ return set_allow_storefront_traffic(False)
+
+
+def test_storefront_traffic_allowed_by_default(site_settings):
+ assert site_settings.allow_storefront_traffic is True
+
+
+ ("_case", "client_fixture", "allow_storefront_traffic", "expected_status"),
+ [
+ ("anonymous_disabled", "api_client", False, 401),
+ ("anonymous_enabled", "api_client", True, 200),
+ ("app_disabled", "app_api_client", False, 200),
+ ("app_enabled", "app_api_client", True, 200),
+ ("customer_disabled", "user_api_client", False, 401),
+ ("customer_enabled", "user_api_client", True, 200),
+ ("staff_disabled", "staff_api_client", False, 200),
+ ("staff_enabled", "staff_api_client", True, 200),
+ ],
+)
+def test_request_per_principal(
+ _case,
+ client_fixture,
+ allow_storefront_traffic,
+ expected_status,
+ request,
+ set_allow_storefront_traffic,
+):
+ # given: anonymous and customer traffic follows the flag, apps and staff never do
+ set_allow_storefront_traffic(allow_storefront_traffic)
+ client = request.getfixturevalue(client_fixture)
+
+ # when
+ response = client.post_graphql("{ __typename }")
+
+ # then
+ assert response.status_code == expected_status
+ if expected_status == 401:
+ assert response.json() == EXPECTED_STOREFRONT_TRAFFIC_ERROR
+ else:
+ assert response.json()["data"] == {"__typename": "Query"}
+
+
+ ("_case", "authorization_header"),
+ [
+ ("invalid_token", "Bearer not-a-real-token"),
+ ("scheme_without_token", "Bearer"),
+ ("scheme_with_trailing_space", "Bearer "),
+ ("unknown_scheme", "Invalid"),
+ ("unknown_scheme_with_token", "Invalid not-a-real-token"),
+ ],
+)
+def test_unusable_authorization_header_blocked_when_disabled(
+ _case, authorization_header, api_client, storefront_traffic_disabled
+):
+ # given: an Authorization header that resolves to neither app nor user, flag off
+ # when
+ response = api_client.post_graphql(
+ "{ __typename }", HTTP_AUTHORIZATION=authorization_header
+ )
+
+ # then
+ assert response.status_code == 401
+ assert response.json() == EXPECTED_STOREFRONT_TRAFFIC_ERROR
+
+
+def test_anonymous_batch_rejected_when_disabled(
+ api_client, storefront_traffic_disabled, settings
+):
+ # given: a batch of anonymous queries, flag off
+ settings.GRAPHQL_BATCH_MAX_COUNT = 5
+ queries = [{"query": "{ __typename }"}, {"query": "{ __typename }"}]
+
+ # when
+ response = api_client.post(data=queries)
+
+ # then: every entry is rejected with 401 (the guard runs per operation)
+ assert response.status_code == 401
+ assert response.json() == [EXPECTED_STOREFRONT_TRAFFIC_ERROR] * len(queries)
+
+
+def test_anonymous_introspection_blocked_when_disabled(
+ api_client, storefront_traffic_disabled
+):
+ # given: an anonymous introspection query, flag off
+ # when
+ response = api_client.post_graphql("{ __schema { queryType { name } } }")
+
+ # then
+ assert response.status_code == 401
+ assert response.json() == EXPECTED_STOREFRONT_TRAFFIC_ERROR
+
+
+def test_real_public_query_blocked_when_disabled(
+ api_client, storefront_traffic_disabled, channel_USD
+):
+ # Representative real storefront read (a proxy-less storefront would call this
+ # anonymously). Proves a genuine operation - not just `{ __typename }` - is
+ # rejected before it executes when anonymous traffic is disabled.
+ query = """
+ query ($channel: String!) {
+ products(first: 1, channel: $channel) { edges { node { id } } }
+ }
+ """
+
+ # when
+ response = api_client.post_graphql(query, {"channel": channel_USD.slug})
+
+ # then
+ assert response.status_code == 401
+ assert response.json() == EXPECTED_STOREFRONT_TRAFFIC_ERROR
+
+
+def test_real_public_mutation_blocked_when_disabled(
+ api_client, storefront_traffic_disabled, customer_user
+):
+ # Representative real public mutation: `tokenCreate` (login). Proves that even
+ # logging in is blocked when locked down, forcing auth through the app/proxy.
+ query = """
+ mutation ($email: String!, $password: String!) {
+ tokenCreate(email: $email, password: $password) {
+ token
+ errors { field message }
+ }
+ }
+ """
+
+ # when
+ response = api_client.post_graphql(
+ query, {"email": customer_user.email, "password": "password"}
+ )
+
+ # then
+ assert response.status_code == 401
+ assert response.json() == EXPECTED_STOREFRONT_TRAFFIC_ERROR
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c599506c5a..06fd55df95 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -14994,6 +14994,13 @@ type Shop implements ObjectWithMetadata {
"""
trackInventoryByDefault: Boolean
+ """
+ Determines whether the GraphQL API accepts storefront requests (anonymous requests and authenticated non-staff customers). When disabled, only apps and staff users may call the API directly; all other requests are rejected with an HTTP 401 and the `STOREFRONT_TRAFFIC_NOT_ALLOWED` error code.
+
+ Added in Saleor 3.23.
+ """
+ allowStorefrontTraffic: Boolean!
+
"""Default weight unit."""
defaultWeightUnit: WeightUnitsEnum
@@ -23228,6 +23235,13 @@ input ShopSettingsInput {
"""Enable possibility to login without account confirmation."""
allowLoginWithoutConfirmation: Boolean
+ """
+ Determines whether the GraphQL API accepts storefront requests (anonymous requests and authenticated non-staff customers). When disabled, only apps and staff users may call the API directly; all other requests are rejected with an HTTP 401 and the `STOREFRONT_TRAFFIC_NOT_ALLOWED` error code.
+
+ Added in Saleor 3.23.
+ """
+ allowStorefrontTraffic: Boolean
+
"""
Shop public metadata. Can be read by any API client authorized to read the object it's attached to.
diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.py
index ce41a39abd..e6ec28570f 100644
--- a/saleor/graphql/shop/mutations/shop_settings_update.py
+++ b/saleor/graphql/shop/mutations/shop_settings_update.py
@@ -19,6 +19,7 @@ from ...core.utils import WebhookEventInfo
from ...meta.inputs import MetadataInput, MetadataInputDescription
from ...plugins.dataloaders import get_plugin_manager_promise
from ...site.dataloaders import get_site_promise
+from ...storefront_traffic import set_allow_storefront_traffic_cache
from ..enums import AccountConfirmModeEnum, PasswordLoginModeEnum
from ..types import Shop
@@ -74,6 +75,15 @@ class ShopSettingsInput(graphene.InputObjectType):
allow_login_without_confirmation = graphene.Boolean(
description="Enable possibility to login without account confirmation."
)
+ allow_storefront_traffic = graphene.Boolean(
+ description=(
+ "Determines whether the GraphQL API accepts storefront requests "
+ "(anonymous requests and authenticated non-staff customers). When "
+ "disabled, only apps and staff users may call the API directly; all "
+ "other requests are rejected with an HTTP 401 and the "
+ "`STOREFRONT_TRAFFIC_NOT_ALLOWED` error code." + ADDED_IN_323
+ ),
+ )
metadata = common_types.NonNullList(
MetadataInput,
description="Shop public metadata. "
@@ -271,6 +281,9 @@ class ShopSettingsUpdate(BaseMutation):
cls.clean_instance(info, site)
site.save(update_fields=["name"])
+ should_update_storefront_traffic_cache = (
+ "allow_storefront_traffic" in cleaned_input
+ )
instance = cls.construct_instance(instance, cleaned_input)
cls.validate_and_update_metadata(
instance, metadata_collection, private_metadata_collection
@@ -278,6 +291,12 @@ class ShopSettingsUpdate(BaseMutation):
cls.clean_instance(info, instance)
instance.save()
+ if should_update_storefront_traffic_cache:
+ # Note: we do not use any locks here as we do not expect any use-case
+ # where this mutation would be called concurrently with different
+ # modes.
+ set_allow_storefront_traffic_cache(instance.allow_storefront_traffic)
+
if (
instance.metadata != old_metadata
or instance.private_metadata != old_private_metadata
diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
index 1b0cd9a1ad..0e5e3497c7 100644
--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py
@@ -6,7 +6,15 @@ import pytest
from .....core.error_codes import ShopErrorCode
from .....core.jwt import JWT_OWNER_FIELD
from .....site.models import Site
-from ....tests.utils import get_graphql_content, get_graphql_content_from_response
+from ....storefront_traffic import (
+ get_allow_storefront_traffic,
+ set_allow_storefront_traffic_cache,
+)
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
from ...enums import AccountConfirmModeEnum, PasswordLoginModeEnum
SHOP_SETTINGS_UPDATE_MUTATION = """
@@ -844,8 +852,10 @@ def test_shop_settings_update_name(
data = content["data"]["shopSettingsUpdate"]
assert not data["errors"]
assert data["shop"]["name"] == new_name
- site = Site.objects.get_current()
- assert site.name == new_name
+ # Read the row back rather than `Site.objects.get_current()`, which may serve a
+ # site cached earlier in the process and miss the update.
+ site_settings.site.refresh_from_db(fields=("name",))
+ assert site_settings.site.name == new_name
def test_shop_settings_update_name_too_long(
@@ -869,5 +879,70 @@ def test_shop_settings_update_name_too_long(
errors = content["data"]["shopSettingsUpdate"]["errors"]
assert len(errors) == 1
assert errors[0]["field"] == "name"
- site = Site.objects.get_current()
- assert site.name == original_name
+ # Read the row back rather than `Site.objects.get_current()`, which may serve a
+ # site cached earlier in the process and hide a write that should not have
+ # happened.
+ site_settings.site.refresh_from_db(fields=("name",))
+ assert site_settings.site.name == original_name
+
+
+SHOP_SETTINGS_UPDATE_STOREFRONT_TRAFFIC_MUTATION = """
+ mutation updateSettings($input: ShopSettingsInput!) {
+ shopSettingsUpdate(input: $input) {
+ shop { allowStorefrontTraffic }
+ errors { field message code }
+ }
+ }
+"""
+
+
+def test_shop_settings_update_sets_allow_storefront_traffic(
+ staff_api_client, site_settings, permission_manage_settings
+):
+ # given
+ site_settings.allow_storefront_traffic = True
+ site_settings.save(update_fields=["allow_storefront_traffic"])
+ set_allow_storefront_traffic_cache(True)
+ variables = {"input": {"allowStorefrontTraffic": False}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHOP_SETTINGS_UPDATE_STOREFRONT_TRAFFIC_MUTATION,
+ variables,
+ permissions=[permission_manage_settings],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shopSettingsUpdate"]
+ assert data["errors"] == []
+ assert data["shop"]["allowStorefrontTraffic"] is False
+ site_settings.refresh_from_db()
+ assert site_settings.allow_storefront_traffic is False
+ assert get_allow_storefront_traffic() is False
+
+
+ ("_case", "client_fixture"),
+ [
+ ("staff_without_permission", "staff_api_client"),
+ ("anonymous", "api_client"),
+ ],
+)
+def test_shop_settings_update_allow_storefront_traffic_requires_permission(
+ _case, client_fixture, request, site_settings
+):
+ # given: no MANAGE_SETTINGS granted
+ assert site_settings.allow_storefront_traffic is True
+ variables = {"input": {"allowStorefrontTraffic": False}}
+ client = request.getfixturevalue(client_fixture)
+
+ # when
+ response = client.post_graphql(
+ SHOP_SETTINGS_UPDATE_STOREFRONT_TRAFFIC_MUTATION, variables
+ )
+
+ # then
+ assert_no_permission(response)
+ site_settings.refresh_from_db(fields=("allow_storefront_traffic",))
+ assert site_settings.allow_storefront_traffic is True
diff --git a/saleor/graphql/shop/tests/queries/test_shop_allow_storefront_traffic.py b/saleor/graphql/shop/tests/queries/test_shop_allow_storefront_traffic.py
new file mode 100644
index 0000000000..c318d5063d
--- /dev/null
+++ b/saleor/graphql/shop/tests/queries/test_shop_allow_storefront_traffic.py
@@ -0,0 +1,35 @@
+from ....tests.utils import get_graphql_content
+
+SHOP_ALLOW_STOREFRONT_TRAFFIC_QUERY = """
+ query {
+ shop { allowStorefrontTraffic }
+ }
+"""
+
+
+def test_shop_allow_storefront_traffic_defaults_to_true(api_client, site_settings):
+ # given: freshly created site settings (default)
+ # then: the model default is True
+ assert site_settings.allow_storefront_traffic is True
+
+ # when: read through the API (public, no auth needed)
+ response = api_client.post_graphql(SHOP_ALLOW_STOREFRONT_TRAFFIC_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["shop"]["allowStorefrontTraffic"] is True
+
+
+def test_shop_allow_storefront_traffic_reflects_stored_value(
+ staff_api_client, site_settings
+):
+ # given
+ site_settings.allow_storefront_traffic = False
+ site_settings.save(update_fields=["allow_storefront_traffic"])
+
+ # when: staff client is authenticated, so enforcement never triggers here
+ response = staff_api_client.post_graphql(SHOP_ALLOW_STOREFRONT_TRAFFIC_QUERY)
+ content = get_graphql_content(response)
+
+ # then
+ assert content["data"]["shop"]["allowStorefrontTraffic"] is False
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 17294fd2f1..e9fa9259ce 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -341,6 +341,16 @@ class Shop(graphene.ObjectType):
"This field is used as a default value for `ProductVariant.trackInventory`."
)
)
+ allow_storefront_traffic = graphene.Boolean(
+ description=(
+ "Determines whether the GraphQL API accepts storefront requests "
+ "(anonymous requests and authenticated non-staff customers). When "
+ "disabled, only apps and staff users may call the API directly; all "
+ "other requests are rejected with an HTTP 401 and the "
+ "`STOREFRONT_TRAFFIC_NOT_ALLOWED` error code." + ADDED_IN_323
+ ),
+ required=True,
+ )
default_weight_unit = WeightUnitsEnum(description="Default weight unit.")
translation = TranslationField(ShopTranslation, type_name="shop", resolver=None)
reserve_stock_duration_anonymous_user = PermissionsField(
@@ -625,6 +635,11 @@ class Shop(graphene.ObjectType):
def resolve_track_inventory_by_default(_, _info, site):
return site.settings.track_inventory_by_default
+ @staticmethod
+ @load_site_callback
+ def resolve_allow_storefront_traffic(_, _info, site):
+ return site.settings.allow_storefront_traffic
+
@staticmethod
@load_site_callback
def resolve_default_weight_unit(_, _info, site):
diff --git a/saleor/graphql/storefront_traffic.py b/saleor/graphql/storefront_traffic.py
new file mode 100644
index 0000000000..231d88921d
--- /dev/null
+++ b/saleor/graphql/storefront_traffic.py
@@ -0,0 +1,104 @@
+import warnings
+
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.core.cache import cache
+from jwt import InvalidTokenError
+
+from ..account.models import User
+from ..core.auth import get_token_from_request
+from ..site.models import SiteSettings
+from .core import SaleorContext
+
+STOREFRONT_TRAFFIC_ERROR_CODE = "STOREFRONT_TRAFFIC_NOT_ALLOWED"
+STOREFRONT_TRAFFIC_ERROR_MESSAGE = "Storefront traffic is not allowed."
+STOREFRONT_TRAFFIC_CACHE_TIMEOUT = 5 * 60
+
+
+def _get_allow_storefront_traffic_cache_key() -> str:
+ """Namespace the cache key per site, so tenants cannot read each other's flag.
+
+ ``get_current`` reads the process-global site cache, so this costs no query once
+ that cache is warm — which it is in production and, via the autouse fixture in
+ ``saleor/graphql/conftest.py``, in tests.
+ """
+ site = Site.objects.get_current()
+ return f"allow_storefront_traffic:{site.pk}"
+
+
+def set_allow_storefront_traffic_cache(allow_storefront_traffic: bool) -> None:
+ cache.set(
+ _get_allow_storefront_traffic_cache_key(),
+ allow_storefront_traffic,
+ STOREFRONT_TRAFFIC_CACHE_TIMEOUT,
+ )
+
+
+def clear_allow_storefront_traffic_cache() -> None:
+ cache.delete(_get_allow_storefront_traffic_cache_key())
+
+
+def get_allow_storefront_traffic() -> bool:
+ cache_key = _get_allow_storefront_traffic_cache_key()
+ allow_storefront_traffic = cache.get(cache_key)
+ if allow_storefront_traffic is None:
+ allow_storefront_traffic = (
+ SiteSettings.objects.using(settings.DATABASE_CONNECTION_REPLICA_NAME)
+ .values_list("allow_storefront_traffic", flat=True)
+ .get(site=Site.objects.get_current())
+ )
+ set_allow_storefront_traffic_cache(allow_storefront_traffic)
+ return allow_storefront_traffic
+
+
+def _is_staff_user(request: SaleorContext) -> bool:
+ """Resolve the request's user and report whether it is a staff member.
+
+ ``get_context_value`` only binds ``request.user`` as a ``SimpleLazyObject``, so
+ reading it here is what actually runs the authentication stack (a JWT decode plus
+ a database read). Call this last, once the cheaper checks have failed to settle
+ the decision on their own.
+ """
+ if not get_token_from_request(request):
+ # No credentials at all, so there is no user to resolve.
+ return False
+
+ try:
+ # Needed because Saleor implicitly authenticates the user when accessing the
+ # property `.user` (magic). Binding the SimpleLazyObject does not
+ # authenticate — the first attribute access does. Force it inside this try
+ # (via `if not user`) so the implicit auth and any InvalidTokenError it
+ # raises are caught here.
+ user = request.user
+ if not user:
+ return False
+ except InvalidTokenError:
+ return False
+
+ if isinstance(user, User) is False:
+ warnings.warn(
+ f"An invalid user object was found: {user}",
+ stacklevel=3,
+ )
+ return False
+
+ return user.is_staff
+
+
+def is_storefront_traffic_blocked(request: SaleorContext) -> bool:
+ """Return True when a request must be rejected as disallowed storefront traffic.
+
+ App-authenticated and staff-user requests may always call the API directly.
+ Other requests follow the cached shop setting.
+
+ The checks run cheapest first. ``request.app`` is already resolved by
+ ``get_context_value``, so reading it is free. The shop setting is a cached
+ lookup. Only when traffic is actually disabled do we resolve ``request.user``
+ and pay for authentication — on the common path, where traffic is allowed, that
+ cost is never incurred.
+ """
+ if request.app:
+ return False
+ if get_allow_storefront_traffic():
+ return False
+ return not _is_staff_user(request)
diff --git a/saleor/graphql/tests/test_storefront_traffic.py b/saleor/graphql/tests/test_storefront_traffic.py
new file mode 100644
index 0000000000..c76187a59d
--- /dev/null
+++ b/saleor/graphql/tests/test_storefront_traffic.py
@@ -0,0 +1,134 @@
+from types import SimpleNamespace
+
+import pytest
+from jwt import InvalidTokenError
+
+from saleor.core.auth import SALEOR_AUTH_HEADER
+from saleor.graphql.storefront_traffic import (
+ clear_allow_storefront_traffic_cache,
+ is_storefront_traffic_blocked,
+)
+
+
+def _make_request(app=None, user=None, authenticated=False):
+ """Build a fake request. ``authenticated`` adds an auth token to the META.
+
+ An anonymous request (no token) is short-circuited by the guard before
+ ``request.user`` is resolved, so user-authenticated cases must carry a token.
+ """
+ meta = {SALEOR_AUTH_HEADER: "token"} if authenticated else {}
+ return SimpleNamespace(app=app, user=user, META=meta)
+
+
+def _set_allow_storefront_traffic(site_settings, allowed):
+ site_settings.allow_storefront_traffic = allowed
+ site_settings.save(update_fields=["allow_storefront_traffic"])
+ clear_allow_storefront_traffic_cache()
+
+
[email protected](autouse=True)
+def _clear_storefront_traffic_cache():
+ clear_allow_storefront_traffic_cache()
+ yield
+ clear_allow_storefront_traffic_cache()
+
+
+def test_blocks_anonymous_request_when_disabled(site_settings):
+ # given
+ _set_allow_storefront_traffic(site_settings, False)
+ request = _make_request(app=None, user=None)
+
+ # when / then
+ assert is_storefront_traffic_blocked(request) is True
+
+
+def test_allows_anonymous_request_when_enabled(site_settings):
+ # given
+ _set_allow_storefront_traffic(site_settings, True)
+ request = _make_request(app=None, user=None)
+
+ # when / then
+ assert is_storefront_traffic_blocked(request) is False
+
+
+def test_allows_app_request_when_disabled(site_settings, app):
+ # given: an app is always allowed, regardless of the flag
+ _set_allow_storefront_traffic(site_settings, False)
+ request = _make_request(app=app, user=None)
+
+ # when / then
+ assert is_storefront_traffic_blocked(request) is False
+
+
+ ("_case", "user_fixture", "allow_storefront_traffic", "expected_blocked"),
+ [
+ ("customer_disabled", "customer_user", False, True),
+ ("customer_enabled", "customer_user", True, False),
+ ("staff_disabled", "staff_user", False, False),
+ ("staff_enabled", "staff_user", True, False),
+ ],
+)
+def test_user_traffic(
+ _case,
+ user_fixture,
+ allow_storefront_traffic,
+ expected_blocked,
+ request,
+ site_settings,
+):
+ # given: a user-authenticated request — customers follow the flag, staff always allowed
+ _set_allow_storefront_traffic(site_settings, allow_storefront_traffic)
+ user = request.getfixturevalue(user_fixture)
+ req = _make_request(app=None, user=user, authenticated=True)
+
+ # when / then
+ assert is_storefront_traffic_blocked(req) is expected_blocked
+
+
+ ("_case", "allow_storefront_traffic", "expected_blocked", "expected_user_reads"),
+ [
+ # The flag alone settles the allowed case, so the user is never resolved.
+ ("enabled", True, False, 0),
+ ("disabled", False, True, 1),
+ ],
+)
+def test_invalid_token_user_resolution(
+ _case,
+ allow_storefront_traffic,
+ expected_blocked,
+ expected_user_reads,
+ site_settings,
+):
+ # given: evaluating request.user raises for an invalid/stale token
+ _set_allow_storefront_traffic(site_settings, allow_storefront_traffic)
+ user_reads = []
+
+ class Request:
+ app = None
+ META = {SALEOR_AUTH_HEADER: "token"}
+
+ @property
+ def user(self):
+ user_reads.append(True)
+ raise InvalidTokenError("Invalid token.")
+
+ # when
+ blocked = is_storefront_traffic_blocked(Request())
+
+ # then
+ assert blocked is expected_blocked
+ # Without this the expected result could also be reached by never reading
+ # `.user`, leaving the InvalidTokenError branch untested.
+ assert len(user_reads) == expected_user_reads
+
+
+def test_unexpected_user_object_is_not_privileged(site_settings):
+ # given
+ _set_allow_storefront_traffic(site_settings, False)
+ request = _make_request(app=None, user=object(), authenticated=True)
+
+ # when / then
+ with pytest.warns(UserWarning, match="An invalid user object was found"):
+ assert is_storefront_traffic_blocked(request) is True
diff --git a/saleor/graphql/tests/test_tracing.py b/saleor/graphql/tests/test_tracing.py
index 645c539121..da0cc9f2c0 100644
--- a/saleor/graphql/tests/test_tracing.py
+++ b/saleor/graphql/tests/test_tracing.py
@@ -554,7 +554,7 @@ def test_graphql_query_span_set_status_error_invalid_query(
mock_start_span.return_value.__enter__.return_value = mock_span
request = rf.post(
- path="/graphql",
+ path="/graphql/",
data=data,
content_type="application/json",
)
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index a7c2316252..57f21b8c2e 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -48,6 +48,11 @@ from .metrics import (
record_request_duration,
)
from .query_cost_map import COST_MAP, QUERY_COST_FAILED_OPERATION
+from .storefront_traffic import (
+ STOREFRONT_TRAFFIC_ERROR_CODE,
+ STOREFRONT_TRAFFIC_ERROR_MESSAGE,
+ is_storefront_traffic_blocked,
+)
from .utils import (
format_error,
get_source_service_name_value,
@@ -58,6 +63,20 @@ from .utils.validators import check_if_query_contains_only_schema
INT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"
+# Sentinel result returned by `execute_graphql_request` when a request is rejected
+# as disallowed storefront traffic. `get_response` matches it by identity and maps
+# it to a 401 without running it through `format_error` (which would relocate and
+# annotate the error and log it as a failed query).
+STOREFRONT_TRAFFIC_BLOCKED = ExecutionResult(invalid=True)
+STOREFRONT_TRAFFIC_BLOCKED_RESPONSE: GraphQLOperationResult = {
+ "errors": [
+ {
+ "message": STOREFRONT_TRAFFIC_ERROR_MESSAGE,
+ "extensions": {"code": STOREFRONT_TRAFFIC_ERROR_CODE},
+ }
+ ]
+}
+
def default_serializer(obj):
if isinstance(obj, decimal.Decimal):
@@ -288,6 +307,12 @@ class GraphQLView(View):
) -> tuple[GraphQLOperationResult | None, int]:
with observability.report_gql_operation() as operation:
execution_result = self.execute_graphql_request(request, data)
+ # The request was rejected as disallowed storefront traffic, so the query
+ # was never executed and there is no result to format. Return the canned
+ # error with a 401 and skip the `format_error` / observability handling
+ # below, which is meant for real execution failures.
+ if execution_result is STOREFRONT_TRAFFIC_BLOCKED:
+ return STOREFRONT_TRAFFIC_BLOCKED_RESPONSE, 401
status_code = 200
result: GraphQLOperationResult = {}
if execution_result.errors:
@@ -463,6 +488,13 @@ class GraphQLView(View):
span.set_attribute(saleor_attributes.SALEOR_APP_NAME, app.name)
try:
+ # Reject disallowed storefront traffic before executing. App and
+ # staff-user requests are always allowed; anonymous and customer
+ # requests follow the cached shop setting. Checked here so it reuses
+ # the single context created above (cleaned by the `finally`) rather
+ # than building and tearing down a second one.
+ if is_storefront_traffic_blocked(context):
+ return STOREFRONT_TRAFFIC_BLOCKED
response = None
error_type = None
should_use_cache_for_scheme = query_contains_schema & (
diff --git a/saleor/site/migrations/0052_sitesettings_allow_storefront_traffic.py b/saleor/site/migrations/0052_sitesettings_allow_storefront_traffic.py
new file mode 100644
index 0000000000..e22ca73f48
--- /dev/null
+++ b/saleor/site/migrations/0052_sitesettings_allow_storefront_traffic.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.16 on 2026-07-16 09:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0051_merge_20260717_1400"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sitesettings",
+ name="allow_storefront_traffic",
+ field=models.BooleanField(default=True, db_default=True),
+ ),
+ ]
diff --git a/saleor/site/migrations/0053_merge_20260730_0700.py b/saleor/site/migrations/0053_merge_20260730_0700.py
new file mode 100644
index 0000000000..6c24a25d27
--- /dev/null
+++ b/saleor/site/migrations/0053_merge_20260730_0700.py
@@ -0,0 +1,12 @@
+# Generated by Django 5.2.16 on 2026-07-30 07:00
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("site", "0052_drop_digital_content_settings"),
+ ("site", "0052_sitesettings_allow_storefront_traffic"),
+ ]
+
+ operations = []
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 31d0866f50..710b03a1f2 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -74,6 +74,7 @@ class SiteSettings(ModelWithMetadata):
customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)
fulfillment_auto_approve = models.BooleanField(default=True)
fulfillment_allow_unpaid = models.BooleanField(default=True)
+ allow_storefront_traffic = models.BooleanField(default=True, db_default=True)
preserve_all_address_fields = models.BooleanField(
default=False,
db_default=False,
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index 3d40909026..bb614627c1 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -21,6 +21,11 @@ def lazy_re_compile(regex, flags=0):
POPULATE_DEFAULTS = False
+# Every xdist worker gets its own database but they all share one Redis, so without a
+# per-worker namespace a value cached by one worker is read by all the others.
+if xdist_worker := os.environ.get("PYTEST_XDIST_WORKER"): # noqa: F405
+ CACHES["default"]["KEY_PREFIX"] = xdist_worker # noqa: F405
+
CELERY_TASK_ALWAYS_EAGER = True
PUBLIC_URL = "https://example.com"