: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(warehouse-sources): stop blaming read roles for App Store Connect 403s (#85796)
posthog[bot]7e36cbd77510
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.pyindex 992e12fe2201..0142f5752f04 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py@@ -16,6 +16,8 @@ import jwtimport requestsfrom structlog.types import FilteringBoundLogger+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (ANALYTICS_GRANULARITY,ANALYTICS_MAX_INSTANCES_PER_RUN,@@ -76,6 +78,67 @@ class AppStoreConnectUrlError(Exception):"""A request or pagination URL points somewhere other than the App Store Connect API origin."""+class AppStoreConnectPermissionError(Exception):+ """A 403 from App Store Connect: the key's role can't perform this call. Non-retryable."""+++# 403 on a report or resource read. The key's role can't read this data, so the fix is a role+# that can. `AppStoreConnectSource.get_non_retryable_errors` matches on this text to fail fast.+APP_STORE_CONNECT_READ_FORBIDDEN_ERROR = (+ "Your App Store Connect API key does not have permission to read this data. Give the key the "+ "Admin, Finance, or Sales role that can read it, then reconnect."+)++# 403 on `POST /v1/analyticsReportRequests`. Apple lets only an Admin key create an analytics+# report request, so a Finance or Sales key reads reports and still loses this create. Named+# separately so the message points at Admin rather than the read roles the key already holds.+APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR = (+ "Your App Store Connect API key cannot start analytics reports. Apple lets only an Admin key "+ "create an analytics report request. Give the key the Admin role, then reconnect."+)++# The app's ONGOING analytics report request stopped after a period of inactivity, and the key's+# role can't create the replacement Apple now needs.+APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR = (+ "Your App Store Connect analytics report request stopped because of inactivity. Apple needs a "+ "new request, which only an Admin key can create. Give the key the Admin role, then reconnect."+)+++@frozen+class _AppleApiError:+ code: str | None+ title: str | None+ detail: str | None+++def _parse_apple_error(response: requests.Response) -> _AppleApiError:+ """Pull the first JSON:API error out of an App Store Connect 4xx body.++ Apple returns ``{"errors": [{"code", "title", "detail", ...}]}``, but an edge or proxy can+ return non-JSON, so parse defensively and leave fields ``None`` when the body has no usable error.+ """+ try:+ body = response.json()+ except ValueError:+ return _AppleApiError(code=None, title=None, detail=None)+ errors = body.get("errors") if isinstance(body, dict) else None+ first = errors[0] if isinstance(errors, list) and errors and isinstance(errors[0], dict) else {}+ return _AppleApiError(+ code=first.get("code") if isinstance(first.get("code"), str) else None,+ title=first.get("title") if isinstance(first.get("title"), str) else None,+ detail=first.get("detail") if isinstance(first.get("detail"), str) else None,+ )+++def _apple_error_suffix(error: _AppleApiError, status_code: int) -> str:+ """Apple's own words appended to a raised message so support sees what Apple actually said."""+ parts = [part for part in (error.code, error.title, error.detail) if part]+ if parts:+ return f"Apple said: {'; '.join(parts)} (HTTP {status_code})"+ return f"HTTP {status_code}"++def _require_api_url(url: str) -> str:"""Reject any URL that isn't ``https://api.appstoreconnect.apple.com`` on the default HTTPS port.@@ -218,6 +281,21 @@ def _get(if response.status_code in tolerate:return response+ if response.status_code == 403:+ # A read the key's role can't perform. Carry Apple's own error into the message and a+ # structured log instead of asserting a role the key may already hold.+ apple_error = _parse_apple_error(response)+ logger.error(+ "App Store Connect read forbidden",+ url=url,+ apple_code=apple_error.code,+ apple_title=apple_error.title,+ apple_detail=apple_error.detail,+ )+ raise AppStoreConnectPermissionError(+ f"{APP_STORE_CONNECT_READ_FORBIDDEN_ERROR} ({_apple_error_suffix(apple_error, 403)})"+ )+if not response.ok:logger.error(f"App Store Connect API error: status={response.status_code}, body={response.text[:500]}, url={url}"@@ -814,7 +892,9 @@ def _ensure_report_request("""list_url = f"{BASE_URL}/v1/apps/{app_id}/analyticsReportRequests"- def _active_request_id() -> str | None:+ def _active_request_id() -> tuple[str | None, bool]:+ """Returns ``(active_request_id, saw_stopped)`` — the active request to reuse, and whether an+ ONGOING request stopped due to inactivity was skipped, so the create 403 can name that cause."""body = _get(session,list_url,@@ -823,16 +903,18 @@ def _ensure_report_request(params={"filter[accessType]": "ONGOING", "limit": MAX_PAGE_SIZE},).json()data = body.get("data") if isinstance(body, dict) else None+ saw_stopped = Falsefor resource in data or []:if not isinstance(resource, dict) or not resource.get("id"):continueattributes = resource.get("attributes")if isinstance(attributes, dict) and attributes.get("stoppedDueToInactivity"):+ saw_stopped = Truecontinue- return str(resource["id"])- return None+ return str(resource["id"]), saw_stopped+ return None, saw_stopped- existing = _active_request_id()+ existing, saw_stopped = _active_request_id()if existing:return existing, False@@ -849,11 +931,30 @@ def _ensure_report_request(token_provider=token_provider,logger=logger,payload=payload,- tolerate=(409,),+ tolerate=(403, 409),)+ if response.status_code == 403:+ # Apple gates this create on Admin, but a Sales or Finance key reads reports fine, so a bare+ # read-role message would name a role the key already holds. Tell the operator the create+ # needs Admin, and say when the trigger was an inactivity-stopped request instead.+ apple_error = _parse_apple_error(response)+ logger.error(+ "App Store Connect analytics report request create forbidden",+ app_id=app_id,+ stopped_due_to_inactivity=saw_stopped,+ apple_code=apple_error.code,+ apple_title=apple_error.title,+ apple_detail=apple_error.detail,+ )+ message = (+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR+ if saw_stopped+ else APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR+ )+ raise AppStoreConnectPermissionError(f"{message} ({_apple_error_suffix(apple_error, 403)})")if response.status_code == 409:# A concurrent sync (or a request the accessType filter hid) beat us to it.- return _active_request_id(), False+ return _active_request_id()[0], Falsebody = response.json()data = body.get("data") if isinstance(body, dict) else Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.pyindex b2aa8b83af3b..1018a340ad18 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py@@ -10,6 +10,9 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,+ APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,AppStoreConnectResumeConfig,app_store_connect_source,check_credentials,@@ -61,7 +64,9 @@ class AppStoreConnectSource(ResumableSource[AppStoreConnectSourceConfig, AppStorAn Account Holder or Admin creates an API key under **Users and Access → Integrations → App Store Connect API** in App Store Connect. Copy the issuer ID and key ID from that page, then paste the contents of the `.p8` private key file you download. Apple only lets you download that file once, so keep a copy.-Sales and subscription reports also need your vendor number (App Store Connect → **Payments and Financial Reports**) and a key with the Finance, Sales, or Admin role. Leave it blank if you only want app, review and build data."""+Sales and subscription reports also need your vendor number (App Store Connect → **Payments and Financial Reports**) and a key with the Finance, Sales, or Admin role. Leave it blank if you only want app, review and build data.++The analytics tables need a key with the Admin role. Apple lets only an Admin key start an analytics report."""restatement_note = restatement_caption()if restatement_note:caption = f"{caption}\n\n{restatement_note}"@@ -141,7 +146,15 @@ Sales and subscription reports also need your vendor number (App Store Connect# Match the stable status text plus the base host, not the per-request path and cursor.return {"401 Client Error: Unauthorized for url: https://api.appstoreconnect.apple.com": "App Store Connect rejected your API key. Check the issuer ID, key ID and private key, or generate a new key, then reconnect.",- "403 Client Error: Forbidden for url: https://api.appstoreconnect.apple.com": "Your App Store Connect API key does not have access to this data. Give the key a role that can read it (Finance or Sales for reports), then reconnect.",+ # A 403 on the analytics report request create. Apple gates it on Admin, not the read+ # roles. Kept before the read message so the create case never inherits the read wording.+ APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR: APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,+ # A 403 on the create where the app's ongoing request had stopped for inactivity.+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR: APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,+ # A 403 on a read. The key's role genuinely can't read this table.+ APP_STORE_CONNECT_READ_FORBIDDEN_ERROR: APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,+ # Any 403 that didn't come through the custom raises still fails fast with the read message.+ "403 Client Error: Forbidden for url: https://api.appstoreconnect.apple.com": APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,}def get_retryable_errors(self) -> set[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.pyindex 5f1d2b68eb56..08dcdfe86bee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py@@ -13,13 +13,18 @@ from cryptography.hazmat.primitives.asymmetric import ecfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,+ APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,BASE_URL,JWT_AUDIENCE,JWT_LIFETIME_SECONDS,AppStoreConnectAuthError,+ AppStoreConnectPermissionError,AppStoreConnectResumeConfig,AppStoreConnectTokenProvider,AppStoreConnectUrlError,+ _ensure_report_request,_find_analytics_report,_flatten_resource,_get,@@ -1347,3 +1352,50 @@ class TestSourceResponse:else:assert response.partition_keys is Noneassert response.partition_mode is None+++def _forbidden_response(**fields: str) -> MagicMock:+ return _json_response({"errors": [fields]}, status_code=403)+++class TestForbiddenErrors:+ def test_read_403_carries_apples_words_and_the_read_message(self) -> None:+ session = MagicMock()+ session.get.return_value = _forbidden_response(+ code="FORBIDDEN_ERROR", detail="The role of this API key cannot read this resource"+ )++ with pytest.raises(AppStoreConnectPermissionError) as exc:+ _get(session, f"{BASE_URL}/v1/salesReports", token_provider=_FakeTokenProvider(), logger=MagicMock())++ message = str(exc.value)+ assert APP_STORE_CONNECT_READ_FORBIDDEN_ERROR in message+ assert "FORBIDDEN_ERROR" in message+ assert "The role of this API key cannot read this resource" in message++ @parameterized.expand(+ [+ ("fresh_create", [], APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR),+ (+ "stopped_for_inactivity",+ [_resource("analyticsReportRequests", "REQ1", accessType="ONGOING", stoppedDueToInactivity=True)],+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,+ ),+ ]+ )+ def test_create_403_reports_the_create_role_not_a_read_role(+ self, _name: str, requests_page: list[dict[str, Any]], expected: str+ ) -> None:+ session = MagicMock()+ session.get.return_value = _json_response(_page(requests_page))+ session.post.return_value = _forbidden_response(code="FORBIDDEN_ERROR", detail="Admin role required")++ with pytest.raises(AppStoreConnectPermissionError) as exc:+ _ensure_report_request(session, _FakeTokenProvider(), MagicMock(), "A1")++ message = str(exc.value)+ assert expected in message+ # Apple's own words reach the raised message, and the create case never blames Finance or+ # Sales — the read roles the key demonstrably uses on the sales_reports table.+ assert "Admin role required" in message+ assert "Finance" not in message and "Sales" not in messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.pyindex 85e81cc5d4d5..2dc64eefee50 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py@@ -12,6 +12,9 @@ from posthog.schema import ()from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR,+ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,+ APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,AppStoreConnectResumeConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (@@ -22,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.source import (AppStoreConnectSource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstoreconnect import (AppStoreConnectSourceConfig,)@@ -30,6 +34,15 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeSOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.source"+def _resolve_friendly_error(error_message: str) -> str | None:+ # Mirrors external_data_job: the first matching key's friendly message is the one shown.+ errors = AppStoreConnectSource().get_non_retryable_errors()+ for key, friendly in errors.items():+ if error_message_matches(error_message, [key]):+ return friendly+ return None++def _config(vendor_number: str | None = "85234567") -> AppStoreConnectSourceConfig:return AppStoreConnectSourceConfig(issuer_id="57246542-96fe-1a63-e053-0824d011072a",@@ -205,6 +218,26 @@ class TestAppStoreConnectSource:assert any("403" in key for key in errors)assert all(message for message in errors.values())+ @parameterized.expand(+ [+ ("analytics_create", APP_STORE_CONNECT_ANALYTICS_CREATE_FORBIDDEN_ERROR),+ ("analytics_inactive", APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR),+ ("read", APP_STORE_CONNECT_READ_FORBIDDEN_ERROR),+ ]+ )+ def test_each_forbidden_case_resolves_to_its_own_copy(self, _name: str, constant: str) -> None:+ # The source raises `<constant> (Apple said: ... (HTTP 403))`; the mapping must resolve each+ # distinct case to its own copy, so the analytics create and inactivity cases never inherit+ # the read wording that names Finance or Sales — the roles the failing key already holds.+ raised = f"{constant} (Apple said: FORBIDDEN_ERROR (HTTP 403))"++ friendly = _resolve_friendly_error(raised)++ assert friendly == constant+ if constant is not APP_STORE_CONNECT_READ_FORBIDDEN_ERROR:+ assert friendly is not None+ assert "Finance" not in friendly and "Sales" not in friendly+@parameterized.expand([(