: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): validate Shopify permissions per schema (#66459)
Daniel RCa65f73e2dd3b
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex b57e3c579556..eefb35f7dd2e 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -509,6 +509,10 @@ Called with `schema_name=None` at source-create (one cheap probe to confirm theIf the API distinguishes 401 (bad token) from 403 (valid token, missing scope), **accept 403 at source-create** — users may legitimately only grant scopes for the endpoints they want to sync. Re-raise 403 only when `schema_name` is set. Sync-time 403s are handled separately by `get_non_retryable_errors()`.+For per-table scope status in the schema picker, override `get_endpoint_permissions(config, team_id, endpoints) -> {name: None | reason}`: probe each endpoint and return `None` when reachable or a short reason when not. The `database_schema` action surfaces it as each table's `permission_error`, so the user sees which tables need extra scopes and deselects them — it must **never** block source-create. The base default reports everything reachable.++When you do surface a missing scope, name it — providers usually state it (``Required access: `read_x` access scope.``), so parse that into your own message instead of dumping the raw exception or collapsing it to a bare table list. Probe whatever field the **sync query** needs (not just `id`) so the per-table check reflects what syncing that table actually requires. Keep the probe narrow: only a real denial is a missing scope — a throttle, 5xx, or network blip is not, so route those through the retryable path rather than bucketing every exception as "missing permission".+## Document required token scopesIf the API issues OAuth scopes or per-resource access tokens, declare every scope the source actually calls so users know what to grant — don't make them grant the full set defensively.@@ -642,6 +646,7 @@ After changing source fields, re-run `pnpm run generate:source-configs` and `pnp- Pod OOMs on a busy table: primary key not actually unique (usually a fan-out child missing the parent id in its key) — duplicate rows accumulate and every merge multi-matches them; often paired with a paginator that re-walks full history each sync because the time filter only applies to page one.- `sort_mode="asc"` declared on an API that returns newest-first: the watermark checkpoints to ≈now after the first batch and mid-sync shutdowns lose data ordering guarantees.- Endless retries for bad credentials: missing `get_non_retryable_errors`.+- Source won't connect despite a valid token: `validate_credentials(schema_name=None)` probes every resource's scope instead of just the token, so one missing scope — often on a table the user won't sync — blocks the whole source. Probe only the token at create; report per-table scope via `get_endpoint_permissions`.- Resumable state never saved: forgot to call `save_state` after yielding a batch; or saved before yield and a crash causes data loss.- Webhook rows not landing: schema `is_webhook=False`, or `initial_sync_complete=False`.- Dependent resource path `KeyError`: pre-format static path placeholders (see Fan-out).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 16263c01c410..f3158cc4d53f 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@@ -1,4 +1,3 @@-import osimport reimport jsonimport dataclasses@@ -75,14 +74,31 @@ class ShopifyResumeConfig:class ShopifyPermissionError(Exception):- """Exception raised when Shopify access token lacks permissions for specific resources."""+ """Raised when the access token can't read some resources.++ `missing_permissions` maps resource -> Shopify's GraphQL error; the surface layer turns it+ into a user message via `missing_permissions_message`.+ """def __init__(self, missing_permissions: dict[str, str]):self.missing_permissions = missing_permissions- message = f"Shopify access token lacks permissions for: {', '.join(missing_permissions.keys())}"- if os.getenv("DEBUG") == "1":- message = f"Shopify access token lacks permissions for: {missing_permissions}"- super().__init__(message)+ super().__init__(f"Shopify access token lacks permissions for: {', '.join(missing_permissions)}")+++# Shopify names the scope a denied field needs as "Required access: `read_x` access scope."+_REQUIRED_SCOPE_RE = re.compile(r"`(read_\w+|write_\w+)`")+++def missing_permissions_message(missing_permissions: dict[str, str]) -> str:+ """User-facing summary naming each unreadable resource and the scope it needs."""+ parts = []+ for resource, error in missing_permissions.items():+ scopes = _REQUIRED_SCOPE_RE.findall(error)+ parts.append(f"{resource} (needs {', '.join(scopes)})" if scopes else resource)+ return (+ f"Your Shopify access token can't read {', '.join(parts)}. "+ "Reconnect your Shopify integration and grant the listed access scopes."+ )# Shopify's GraphQL Admin API rate-limits on a cost-based leaky bucket, so a single bucket@@ -428,25 +444,52 @@ def shopify_source()-def validate_credentials(shopify_store_id: str, shopify_client_id: str, shopify_client_secret: str) -> bool:- """- Validates Shopify API credentials and checks permissions for all required resources.- This function will:- - Return True if the access token is valid and has all required permissions- - Raise ShopifyPermissionError if the access token is valid but lacks permissions for specific resources- - Raise Exception if the access token is invalid or there's any other error+def _format_graphql_errors(errors: Any) -> str:+ """Join the `message` fields from a Shopify GraphQL `errors` payload into one string."""+ if isinstance(errors, list):+ messages = [error.get("message") if isinstance(error, dict) else str(error) for error in errors]+ joined = "; ".join(message for message in messages if message)+ if joined:+ return joined+ return str(errors)+++def _authenticated_session(store_id: str, client_id: str, client_secret: str) -> tuple[str, requests.Session]:+ """Fetch an access token and return the GraphQL URL plus a session that carries it."""+ api_url = SHOPIFY_API_URL.format(store_id, SHOPIFY_API_VERSION)+ access_token = _get_shopify_access_token(store_id, client_id, client_secret)+ sess = make_tracked_session(headers={"Content-Type": "application/json", "X-Shopify-Access-Token": access_token})+ return api_url, sess+++def _probe_resource_permission(api_url: str, sess: requests.Session, resource: ShopifyGraphQLObject) -> str | None:+ """Probe read access to one resource: None if reachable, else the GraphQL error naming the+ missing scope. Throttle/5xx and HTTP/network failures raise — they aren't permission gaps."""+ res = sess.post(api_url, json={"query": resource.permissions_query})+ res.raise_for_status()+ data = res.json()+ retryable_error = _get_retryable_error(data)+ if retryable_error is not None:+ raise retryable_error+ if "errors" in data:+ return _format_graphql_errors(data["errors"])+ return None+++def validate_credentials(+ shopify_store_id: str, shopify_client_id: str, shopify_client_secret: str, resources: list[str] | None = None+) -> bool:+ """Validate Shopify credentials.++ - resources=None: only verify the access token, so connecting isn't blocked by a table the+ user may not sync (per-table scopes are surfaced via `check_endpoint_permissions` instead).+ - resources=[...]: also verify read access to those resources, raising ShopifyPermissionError+ naming any whose scope is missing."""store_id = normalize_store_id(shopify_store_id)- api_url = SHOPIFY_API_URL.format(store_id, SHOPIFY_API_VERSION)- shopify_access_token = _get_shopify_access_token(store_id, shopify_client_id, shopify_client_secret)- sess = make_tracked_session(- headers={- "Content-Type": "application/json",- "X-Shopify-Access-Token": shopify_access_token,- }- )+ api_url, sess = _authenticated_session(store_id, shopify_client_id, shopify_client_secret)- # tests the validity of the access token (valid tokens can always access the shop resource)+ # A valid token can always read the shop resource.try:res = sess.post(api_url, json={"query": SHOPIFY_ACCESS_TOKEN_CHECK})res.raise_for_status()@@ -456,19 +499,42 @@ def validate_credentials(shopify_store_id: str, shopify_client_id: str, shopify_except Exception as e:raise Exception(f"Failed to verify your Shopify credentials: {e}")- # test fine grained permissions+ if resources is None:+ return True+missing_permissions: dict[str, str] = {}- for resource_name, resource in SHOPIFY_GRAPHQL_OBJECTS.items():- try:- res = sess.post(api_url, json={"query": resource.permissions_query})- res.raise_for_status()- data = res.json()- if "errors" in data:- missing_permissions[resource_name] = (- f"Failed to verify Shopify access privileges for resource {resource_name}: {data['errors']}"- )- except Exception as e:- missing_permissions[resource_name] = str(e)+ for name in resources:+ resource = SHOPIFY_GRAPHQL_OBJECTS.get(resolve_schema_name(name))+ if resource is None:+ continue+ error = _probe_resource_permission(api_url, sess, resource)+ if error is not None:+ missing_permissions[name] = errorif missing_permissions:raise ShopifyPermissionError(missing_permissions)return True+++def check_endpoint_permissions(+ shopify_store_id: str, shopify_client_id: str, shopify_client_secret: str, endpoints: list[str]+) -> dict[str, str | None]:+ """Per-endpoint read-scope probe for the schema picker: {name: None} if reachable, else a+ message naming the missing scope. A throttle/5xx/transport blip on one endpoint leaves that+ table unknown rather than aborting the batch; only failing to obtain the access token raises."""+ store_id = normalize_store_id(shopify_store_id)+ api_url, sess = _authenticated_session(store_id, shopify_client_id, shopify_client_secret)+ results: dict[str, str | None] = {}+ for name in endpoints:+ resource = SHOPIFY_GRAPHQL_OBJECTS.get(resolve_schema_name(name))+ if resource is None:+ results[name] = None+ continue+ try:+ error = _probe_resource_permission(api_url, sess, resource)+ except (ShopifyRetryableError, requests.RequestException):+ # A throttle/5xx/transport blip on one endpoint isn't a permission verdict. Leave it+ # unknown (reachable) so the rest of the batch keeps its results instead of the whole+ # probe aborting — the real scope check still runs when the user adds that schema.+ error = None+ results[name] = missing_permissions_message({name: error}) if error is not None else None+ return resultsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.pyindex bfc8bf900ae2..5d2d3bf58327 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/source.py@@ -30,6 +30,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shSHOPIFY_PAYMENT_REQUIRED_ERROR_MESSAGE,ShopifyPermissionError,ShopifyResumeConfig,+ check_endpoint_permissions as check_shopify_endpoint_permissions,+ missing_permissions_message,shopify_source,validate_credentials as validate_shopify_credentials,)@@ -115,18 +117,27 @@ class ShopifySource(ResumableSource[ShopifySourceConfig, ShopifyResumeConfig]):def validate_credentials(self, config: ShopifySourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ # No schema_name → just probe the token, so connecting isn't blocked by a table the user+ # may not sync. With schema_name → also check that one resource's read scope.+ resources = [schema_name] if schema_name is not None else Nonetry:if validate_shopify_credentials(- config.shopify_store_id, config.shopify_client_id, config.shopify_client_secret+ config.shopify_store_id, config.shopify_client_id, config.shopify_client_secret, resources):return True, Nonereturn False, "Invalid Shopify credentials"except ShopifyPermissionError as e:- missing_resources = ", ".join(e.missing_permissions.keys())- return False, f"Shopify access token lacks permissions for {missing_resources}"+ return False, missing_permissions_message(e.missing_permissions)except Exception as e:return False, str(e)+ def get_endpoint_permissions(+ self, config: ShopifySourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ return check_shopify_endpoint_permissions(+ config.shopify_store_id, config.shopify_client_id, config.shopify_client_secret, endpoints+ )+def get_schemas(self,config: ShopifySourceConfig,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_validate_credentials.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_validate_credentials.pynew file mode 100644index 000000000000..eb9c51e10556--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_validate_credentials.py@@ -0,0 +1,129 @@+from typing import Any++from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ShopifySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.source import ShopifySource++_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"+++def _access_denied(message: str) -> dict[str, Any]:+ return {"errors": [{"message": message, "extensions": {"code": "ACCESS_DENIED"}}]}+++def _post_returning(deny_if_query_contains: dict[str, dict[str, Any]]):+ """A fake `sess.post` that returns Shopify-shaped JSON keyed on the GraphQL query text.++ Each key is a substring of a probe query; when a request's query contains it, the mapped+ payload is returned (e.g. an access-denied or throttled body). Anything else — including the+ `{ shop { id } }` token check and the `id` probes — comes back clean.+ """++ def post(_url: str, json: dict[str, Any] | None = None, **_kwargs: Any) -> mock.MagicMock:+ query = (json or {}).get("query", "")+ payload: dict[str, Any] = {"data": {}}+ for needle, denied_payload in deny_if_query_contains.items():+ if needle in query:+ payload = denied_payload+ break+ response = mock.MagicMock()+ response.json.return_value = payload+ return response++ return post+++def _config() -> ShopifySourceConfig:+ return ShopifySourceConfig(shopify_store_id="my-store", shopify_client_id="cid", shopify_client_secret="secret")+++def _patches(post):+ return (+ mock.patch(_TOKEN_PATH, return_value="tok"),+ mock.patch(_SESSION_PATH, return_value=mock.MagicMock(post=mock.MagicMock(side_effect=post))),+ )+++def _validate(post, schema_name: str | None = None) -> tuple[bool, str | None]:+ token_patch, session_patch = _patches(post)+ with token_patch, session_patch:+ return ShopifySource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+++def _endpoint_permissions(post, endpoints: list[str]) -> dict[str, str | None]:+ token_patch, session_patch = _patches(post)+ with token_patch, session_patch:+ return ShopifySource().get_endpoint_permissions(_config(), team_id=1, endpoints=endpoints)+++def test_validating_a_schema_names_the_missing_scope():+ # Validating one schema surfaces our own message naming the scope to grant, parsed from+ # Shopify's error — not the raw GraphQL text.+ denied = _access_denied("Access denied for orders field. Required access: `read_orders` access scope.")+ valid, error = _validate(_post_returning({"orders": denied}), schema_name="orders")++ assert valid is False+ assert error is not None+ assert "orders" in error+ assert "read_orders" in error+ assert "Access denied for orders field" not in error+++def test_throttle_is_not_reported_as_a_permission_error():+ # A throttle arrives as a 200 with an `errors` payload too; it must surface as the real+ # (retryable) rate-limit error, not be mislabeled as a missing permission.+ throttled = {"errors": [{"message": "Throttled", "extensions": {"code": "THROTTLED"}}]}+ valid, error = _validate(_post_returning({"orders": throttled}), schema_name="orders")++ assert valid is False+ assert error is not None+ assert "lacks permissions" not in error+ assert "rate limit" in error+++def test_connect_is_not_blocked_by_a_missing_table_scope():+ # Connecting (no schema_name) only probes the token, so a missing scope on a table the user+ # may not sync — collections needing read_product_listings — must not block the whole source.+ denied = _access_denied(+ "Access denied for availablePublicationsCount field. Required access: `read_product_listings` access scope."+ )+ valid, error = _validate(_post_returning({"collections": denied}), schema_name=None)++ assert valid is True+ assert error is None+++def test_endpoint_permissions_reports_each_table_without_blocking():+ # The schema picker probes each table independently: readable tables come back None and a+ # table missing a scope reports it, without failing the others.+ denied = _access_denied(+ "Access denied for availablePublicationsCount field. Required access: `read_product_listings` access scope."+ )+ result = _endpoint_permissions(_post_returning({"collections": denied}), ["orders", "products", "collections"])++ assert result["orders"] is None+ assert result["products"] is None+ assert result["collections"] is not None+ assert "read_product_listings" in result["collections"]+++def test_endpoint_permissions_survive_a_throttle_on_one_table():+ # A throttle on one endpoint must not abort the batch — otherwise it raises out of the whole+ # probe and the view blanks every table's status. The genuine denial on another table must+ # still come through.+ throttled = {"errors": [{"message": "Throttled"}]}+ denied = _access_denied(+ "Access denied for availablePublicationsCount field. Required access: `read_product_listings` access scope."+ )+ result = _endpoint_permissions(+ _post_returning({"products": throttled, "collections": denied}),+ ["orders", "products", "collections"],+ )++ assert result["orders"] is None+ assert result["products"] is None+ assert "read_product_listings" in (result["collections"] or "")