: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): accept expo robot and sso user tokens (#116746)
posthog[bot]acadea9a9e05
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/expo/expo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/expo/expo.pyindex e76bb25d6a9c..dcf3af482a1d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/expo/expo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/expo/expo.py@@ -3,9 +3,11 @@ from collections.abc import Iteratorfrom typing import Any, Optionalimport requests+import structlogfrom structlog.types import FilteringBoundLoggerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.url_utils import redact_literal_valuesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.expo.settings import EXPO_ENDPOINTS, build_query@@ -14,7 +16,15 @@ EXPO_GRAPHQL_URL = "https://api.expo.dev/graphql"PAGE_SIZE = 100REQUEST_TIMEOUT_SECONDS = 60-_VIEWER_QUERY = "query PostHogExpoViewer { viewer { id username } }"+# Expo types `viewer` as `User`, so it does not resolve for robot or SSO user tokens.+# `meActor` returns the `Actor` interface, which covers every account type.+_ACTOR_QUERY = "query PostHogExpoActor { meActor { id } }"+_REJECTED_TOKEN_HINT = "Create a new one at expo.dev under Access tokens."+# `get_non_retryable_errors` in source.py matches sync errors that start with this prefix.+_API_ERROR_PREFIX = "Expo API error: "+_MAX_ERROR_DETAIL_CHARS = 200++logger = structlog.get_logger(__name__)class ExpoAPIError(Exception):@@ -45,26 +55,37 @@ def _run_query(session: requests.Session, query: str, variables: Optional[dict[serrors = payload.get("errors")if errors:message = "; ".join(str(error.get("message", error)) for error in errors)- raise ExpoAPIError(f"Expo API error: {message}")+ raise ExpoAPIError(f"{_API_ERROR_PREFIX}{message}")return payload.get("data") or {}+def _error_detail(error: Exception, access_token: str) -> str:+ # Expo's error text goes into logs and into the message the user sees, so mask the token in case Expo echoes it.+ detail = redact_literal_values(str(error), (access_token,)).removeprefix(_API_ERROR_PREFIX)+ return detail[:_MAX_ERROR_DETAIL_CHARS].rstrip(".")++def validate_credentials(access_token: str, project_id: str) -> tuple[bool, Optional[str]]:session = _get_session(access_token)try:- data = _run_query(session, _VIEWER_QUERY)- except ExpoAPIError:- return False, "Expo rejected this access token. Create a new one at expo.dev under Access tokens."+ data = _run_query(session, _ACTOR_QUERY)+ except ExpoAPIError as error:+ detail = _error_detail(error, access_token)+ logger.warning("expo_source.validate_credentials_failed", cause="token_graphql_error", error=detail)+ return False, f"Expo rejected this access token ({detail}). {_REJECTED_TOKEN_HINT}"except requests.HTTPError as error:status = error.response.status_code if error.response is not None else None+ logger.warning("expo_source.validate_credentials_failed", cause="token_http_error", status_code=status)if status in (401, 403):- return False, "Expo rejected this access token. Create a new one at expo.dev under Access tokens."+ return False, f"Expo rejected this access token (HTTP {status}). {_REJECTED_TOKEN_HINT}"return False, f"Expo returned an unexpected error ({status}) while checking this access token."- except Exception:+ except Exception as error:+ logger.warning("expo_source.validate_credentials_failed", cause="token_unreachable", error=type(error).__name__)return False, "Could not reach the Expo API. Check your connection and try again."- if not (data.get("viewer") or {}).get("id"):- return False, "Expo rejected this access token. Create a new one at expo.dev under Access tokens."+ if not (data.get("meActor") or {}).get("id"):+ logger.warning("expo_source.validate_credentials_failed", cause="token_no_actor")+ return False, f"Expo did not return an account for this access token. {_REJECTED_TOKEN_HINT}"try:# A valid token still needs access to this specific project, so probe one row.@@ -75,12 +96,20 @@ def validate_credentials(access_token: str, project_id: str) -> tuple[bool, Opti)if (project_data.get("app") or {}).get("byId") is None:raise ExpoAPIError("Expo project not found")- except (ExpoAPIError, requests.HTTPError):+ except (ExpoAPIError, requests.HTTPError) as error:+ logger.warning(+ "expo_source.validate_credentials_failed",+ cause="project_inaccessible",+ error=_error_detail(error, access_token),+ )return False, ("Expo could not read this project. Check the project ID, and that the token's account owns it. ""Run `eas project:info` to see the ID.")- except Exception:+ except Exception as error:+ logger.warning(+ "expo_source.validate_credentials_failed", cause="project_unreachable", error=type(error).__name__+ )return False, "Could not reach the Expo API. Check your connection and try again."return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/expo/tests/test_expo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/expo/tests/test_expo.pyindex 848095be4605..fa33ec51d5f3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/expo/tests/test_expo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/expo/tests/test_expo.py@@ -80,22 +80,33 @@ class TestExpoCredentials:def test_a_valid_token_with_project_access_passes(self) -> None:session = mock.MagicMock()session.post.side_effect = [- _response({"data": {"viewer": {"id": "u1", "username": "someone"}}}),+ _response({"data": {"meActor": {"id": "r1"}}}),_response(_rows("builds", 1)),]with mock.patch(f"{_MODULE}._get_session", return_value=session):assert validate_credentials("token", "app") == (True, None)- def test_a_rejected_token_is_reported(self) -> None:+ # Expo gives robot and SSO user tokens no `viewer`, so the probe must ask for `meActor`.+ assert "meActor" in session.post.call_args_list[0].kwargs["json"]["query"]++ @pytest.mark.parametrize(+ "actor_response, expected",+ [+ ({"errors": [{"message": "Token has been revoked."}]}, "(Token has been revoked)"),+ ({"errors": [{"message": "Unknown token tok_secret_123"}]}, "(Unknown token REDACTED)"),+ ({"data": {"meActor": None}}, "did not return an account"),+ ],+ )+ def test_a_rejected_token_is_reported(self, actor_response: dict[str, Any], expected: str) -> None:session = mock.MagicMock()- session.post.return_value = _response({"errors": [{"message": "Unauthorized"}]})+ session.post.return_value = _response(actor_response)with mock.patch(f"{_MODULE}._get_session", return_value=session):- valid, message = validate_credentials("token", "app")+ valid, message = validate_credentials("tok_secret_123", "app")assert valid is False- assert message is not None and "access token" in message+ assert message is not None and "access token" in message and expected in message@pytest.mark.parametrize("project_response",@@ -107,7 +118,7 @@ class TestExpoCredentials:def test_a_valid_token_without_project_access_names_the_project(self, project_response: dict[str, Any]) -> None:session = mock.MagicMock()session.post.side_effect = [- _response({"data": {"viewer": {"id": "u1"}}}),+ _response({"data": {"meActor": {"id": "u1"}}}),_response(project_response),]