:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): degrade Shopify orders query to granted scopes (#67052)
estefania97591c7a259b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.pyindex 5daee31b022b..5d4cc1b1b3ef 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py@@ -5,11 +5,12 @@ from .queries.catalogs import CATALOGS_QUERYfrom .queries.collections import COLLECTIONS_QUERYfrom .queries.customers import CUSTOMERS_QUERYfrom .queries.discount_nodes import DISCOUNT_NODES_QUERY-from .queries.orders import ORDERS_QUERY+from .queries.orders import ORDERS_QUERY, build_orders_queryfrom .queries.products import PRODUCTS_QUERYfrom .utils import ShopifyGraphQLObjectSHOPIFY_ACCESS_TOKEN_URL = "https://{}.myshopify.com/admin/oauth/access_token"+SHOPIFY_ACCESS_SCOPES_URL = "https://{}.myshopify.com/admin/oauth/access_scopes.json"SHOPIFY_ACCESS_TOKEN_GRANT = "client_credentials"SHOPIFY_API_VERSION = "2025-10"SHOPIFY_API_URL = "https://{}.myshopify.com/admin/api/{}/graphql.json"@@ -87,6 +88,7 @@ SHOPIFY_GRAPHQL_OBJECTS = {name=ORDERS,query=ORDERS_QUERY,permissions_query="{ orders(first: 1) { nodes { id } } }",+ protected_query_builder=build_orders_query,),PRODUCTS: ShopifyGraphQLObject(name=PRODUCTS,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/queries/orders.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/queries/orders.pyindex 7f1a23b28bce..954249af79e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/queries/orders.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/queries/orders.py@@ -15,8 +15,40 @@ from .fragments import (ORDERS_SORTKEY = "UPDATED_AT"-# NOTE: 250 is the max allowable query size for nested connections-ORDERS_QUERY = f"""+# Fields gated behind scopes beyond `read_orders` -> scopes that unlock them (any one suffices).+# Lets a `read_orders`-only token still import the rest of the order instead of "Access denied".+ORDERS_PROTECTED_FIELDS: dict[str, set[str]] = {+ "fulfillmentOrders": {+ "read_merchant_managed_fulfillment_orders",+ "read_third_party_fulfillment_orders",+ "read_assigned_fulfillment_orders",+ },+ "paymentTerms": {"read_payment_terms"},+}++_FULFILLMENT_ORDERS_BLOCK = f"fulfillmentOrders(first: 250) {NODE_CONNECTION_ID_FRAGMENT}"++_PAYMENT_TERMS_BLOCK = f"""paymentTerms {{+ due+ dueInDays+ id+ order {ID_NAME_CREATED_UPDATED_FRAGMENT}+ overdue+ paymentTermsName+ paymentTermsType+ translatedName+ }}"""+++def build_orders_query(granted_scopes: set[str]) -> str:+ """Orders query with each protected-field selection included only when its scope is granted."""+ fulfillment_orders = (+ _FULFILLMENT_ORDERS_BLOCK if granted_scopes & ORDERS_PROTECTED_FIELDS["fulfillmentOrders"] else ""+ )+ payment_terms = _PAYMENT_TERMS_BLOCK if granted_scopes & ORDERS_PROTECTED_FIELDS["paymentTerms"] else ""++ # NOTE: 250 is the max allowable query size for nested connections+ return f"""query PaginatedOrders($pageSize: Int!, $cursor: String, $query: String) {{orders(first: $pageSize, after: $cursor, sortKey: {ORDERS_SORTKEY},@@ -88,7 +120,7 @@ query PaginatedOrders($pageSize: Int!, $cursor: String, $query: String) {{estimatedTaxesevents(first: 250) {NODE_CONNECTION_ID_FRAGMENT}fulfillable- fulfillmentOrders(first: 250) {NODE_CONNECTION_ID_FRAGMENT}+ {fulfillment_orders}fulfillments(first: 250) {{idcreatedAt@@ -129,16 +161,7 @@ query PaginatedOrders($pageSize: Int!, $cursor: String, $query: String) {{originalTotalDutiesSet {MONEY_BAG_FRAGMENT}originalTotalPriceSet {MONEY_BAG_FRAGMENT}paymentGatewayNames- paymentTerms {{- due- dueInDays- id- order {ID_NAME_CREATED_UPDATED_FRAGMENT}- overdue- paymentTermsName- paymentTermsType- translatedName- }}+ {payment_terms}phonepoNumberpresentmentCurrencyCode@@ -210,3 +233,7 @@ query PaginatedOrders($pageSize: Int!, $cursor: String, $query: String) {{}}}}}}"""+++# Full query (all scopes granted); the sync path rebuilds it from the token's real scopes.+ORDERS_QUERY = build_orders_query({scope for scopes in ORDERS_PROTECTED_FIELDS.values() for scope in scopes})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.pyindex f3158cc4d53f..6963a8578872 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.ut)from .constants import (+ SHOPIFY_ACCESS_SCOPES_URL,SHOPIFY_ACCESS_TOKEN_CHECK,SHOPIFY_ACCESS_TOKEN_GRANT,SHOPIFY_ACCESS_TOKEN_URL,@@ -335,6 +336,19 @@ def _get_shopify_access_token(shopify_store_id: str, shopify_client_id: str, shoreturn access_res.json()["access_token"]+def _get_granted_scopes(store_id: str, sess: requests.Session) -> set[str] | None:+ """The token's granted scope handles, or None on any failure — best-effort so a blip degrades+ the query rather than failing the sync."""+ try:+ res = sess.get(SHOPIFY_ACCESS_SCOPES_URL.format(store_id))+ res.raise_for_status()+ data = res.json()+ except (requests.RequestException, ValueError):+ return None+ scopes = data.get("access_scopes", []) if isinstance(data, dict) else []+ return {scope["handle"] for scope in scopes if isinstance(scope, dict) and "handle" in scope}++def shopify_source(shopify_store_id: str,shopify_client_id: str,@@ -359,6 +373,24 @@ def shopify_source(if not graphql_object:raise Exception(f"Shopify object does not exist: {schema_name}")+ # Drop fields the token lacks the scope to read, so a partially scoped token imports the+ # rest instead of hard-failing on "Access denied for <field>". Falls back to the minimal+ # query when scopes can't be detected.+ if graphql_object.protected_query_builder is not None:+ granted_scopes = _get_granted_scopes(store_id, sess)+ if granted_scopes is None:+ granted_scopes = set()+ logger.warning(+ f"Shopify: could not detect granted scopes for {schema_name}; syncing without protected fields"+ )+ graphql_object = ShopifyGraphQLObject(+ name=graphql_object.name,+ query=graphql_object.protected_query_builder(granted_scopes),+ display_name=graphql_object.display_name,+ permissions_query=graphql_object.permissions_query,+ protected_query_builder=graphql_object.protected_query_builder,+ )+logger.debug(f"Shopify: reading from resource {schema_name}")resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_orders_query.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_orders_query.pynew file mode 100644index 000000000000..053ee2cc37bc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_orders_query.py@@ -0,0 +1,81 @@+from typing import Any++from unittest import mock++import graphql+import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.queries.orders import (+ ORDERS_PROTECTED_FIELDS,+ ORDERS_QUERY,+ build_orders_query,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify import shopify_source++_TOKEN_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify._get_shopify_access_token"+)+_SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shopify.make_tracked_session"++_ALL_SCOPES = {scope for scopes in ORDERS_PROTECTED_FIELDS.values() for scope in scopes}+++def test_orders_query_omits_protected_fields_without_their_scopes():+ # The original bug: a read_orders-only token gets the full query, which reaches for+ # fulfillmentOrders/paymentTerms and hard-fails with "Access denied for <field>".+ query = build_orders_query({"read_orders"})++ assert "fulfillmentOrders" not in query+ assert "paymentTerms" not in query+ assert graphql.parse(query) is not None++[email protected](sorted(ORDERS_PROTECTED_FIELDS["fulfillmentOrders"]))+def test_any_fulfillment_scope_alone_includes_fulfillment_orders(scope: str):+ # Shopify exposes fulfillmentOrders under any of three scopes; granting just one must unlock it.+ query = build_orders_query({scope})++ assert "fulfillmentOrders" in query+ assert "paymentTerms" not in query+++def test_orders_query_includes_all_protected_fields_with_full_scopes():+ assert "fulfillmentOrders" in ORDERS_QUERY+ assert "paymentTerms" in ORDERS_QUERY+ assert ORDERS_QUERY == build_orders_query(_ALL_SCOPES)+++def test_scope_detection_failure_falls_back_to_minimal_query():+ # If the access-scopes lookup fails we must degrade to the minimal query, not attempt the full+ # one — otherwise a transient blip reintroduces the "Access denied" hard-fail this fix removes.+ captured: dict[str, str] = {}++ def post(_url: str, json: dict[str, Any] | None = None, **_kwargs: Any) -> mock.MagicMock:+ captured["query"] = (json or {}).get("query", "")+ response = mock.MagicMock(status_code=200)+ response.json.return_value = {"data": {"orders": {"nodes": [], "pageInfo": {"hasNextPage": False}}}}+ return response++ def get(_url: str, **_kwargs: Any) -> mock.MagicMock:+ raise requests.ConnectionError("scopes endpoint unreachable")++ sess = mock.MagicMock(post=mock.MagicMock(side_effect=post), get=mock.MagicMock(side_effect=get))+ resumable = mock.MagicMock(can_resume=mock.MagicMock(return_value=False))++ with mock.patch(_TOKEN_PATH, return_value="tok"), mock.patch(_SESSION_PATH, return_value=sess):+ response = shopify_source(+ shopify_store_id="my-store",+ shopify_client_id="cid",+ shopify_client_secret="secret",+ graphql_object_name="orders",+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ logger=mock.MagicMock(),+ resumable_source_manager=resumable,+ should_use_incremental_field=False,+ )+ list(response.items())++ assert "fulfillmentOrders" not in captured["query"]+ assert "paymentTerms" not in captured["query"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/utils.pyindex b806433feb63..b7a5544d635f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/utils.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom typing import Anyfrom uuid import uuid4@@ -9,6 +10,7 @@ class ShopifyGraphQLObject:query: str,display_name: str | None = None,permissions_query: str | None = None,+ protected_query_builder: Callable[[set[str]], str] | None = None,):# shopify graphql responses typically look like this:# {@@ -31,6 +33,9 @@ class ShopifyGraphQLObject:# optional display name for cases where the shopify name makes less sense to usersself.display_name: str | None = display_nameself.permissions_query: str | None = permissions_query+ # optional: rebuilds `query` from the token's granted scopes so a partially scoped token+ # degrades gracefully instead of hard-failing on a field it can't read (see queries/orders.py)+ self.protected_query_builder: Callable[[set[str]], str] | None = protected_query_builderdef unwrap(payload: Any, path: str):