: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(revenuecat): accept keys without the projects permission at setup (#115308)
Tom Owers19bacb32493d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.pyindex 57512de0393b..75e569174a8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/revenuecat.py@@ -205,6 +205,31 @@ def _format_http_error(error: requests.HTTPError, forbidden_hint: str | None = Nreturn "RevenueCat could not complete the request. Try again in a few minutes, and check the RevenueCat status page if it keeps failing."+_READ_FORBIDDEN_HINT = "Give your v2 secret API key read permission for the data you want to sync, then reconnect."+++def _validate_project_read_access(session: requests.Session, project_id: str) -> tuple[bool, str | None]:+ """Accept the key when it can read at least one endpoint the sync uses in ``project_id``."""+ last_forbidden: requests.HTTPError | None = None+ for endpoint in REVENUECAT_API_ENDPOINTS.values():+ url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, endpoint.path_suffix)}"+ try:+ response = session.get(url, params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ except requests.HTTPError as e:+ if e.response is not None and e.response.status_code == 403:+ last_forbidden = e+ continue+ return False, _format_http_error(e, forbidden_hint=_READ_FORBIDDEN_HINT)+ except requests.RequestException as e:+ LOGGER.warning("Could not reach RevenueCat to validate credentials", error=str(e))+ return False, UNREACHABLE_MESSAGE+ return True, None+ if last_forbidden is not None:+ return False, _format_http_error(last_forbidden, forbidden_hint=_READ_FORBIDDEN_HINT)+ return True, None++def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, str | None]:"""Confirm the key works and (when set) that it can reach ``project_id``.@@ -218,20 +243,19 @@ def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, st"double-check the project id"."""session = _session(api_key)+ normalized_project_id = _normalize_project_id(project_id)try:accessible_ids = _list_accessible_project_ids(session)except requests.HTTPError as e:- return False, _format_http_error(- e,- forbidden_hint=(- "Give your v2 secret API key read permission for the data you want to sync, then reconnect."- ),- )+ # Listing projects needs a projects permission the sync never uses, so a key scoped to just+ # the synced resources is denied here. Check the project's own endpoints instead.+ if normalized_project_id and e.response is not None and e.response.status_code == 403:+ return _validate_project_read_access(session, normalized_project_id)+ return False, _format_http_error(e, forbidden_hint=_READ_FORBIDDEN_HINT)except requests.RequestException as e:LOGGER.warning("Could not reach RevenueCat to validate credentials", error=str(e))return False, UNREACHABLE_MESSAGE- normalized_project_id = _normalize_project_id(project_id)if not normalized_project_id:return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.pyindex 26d6cfb2142f..c4178db21d5e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/revenuecat/tests/test_revenuecat.py@@ -148,6 +148,33 @@ class TestValidateCredentials:# The status code is for error tracking, not for the person reading the source setup form.assert str(status_code) not in error+ @parameterized.expand(+ [+ ("one_resource_readable", [403, 200], True, None),+ ("no_resource_readable", [403] * 5, False, "denied"),+ ("project_missing", [404], False, "could not find"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._session")+ def test_checks_project_endpoints_when_listing_projects_is_denied(+ self, _name, endpoint_statuses, expected_success, expected_substring, mock_session+ ):+ mock_session.return_value.get.side_effect = [_http_error_response(403)] + [+ _ok_json_response({"items": []}) if status == 200 else _http_error_response(status)+ for status in endpoint_statuses+ ]++ success, error = api_client.validate_credentials("sk_test", project_id="proj_test")++ assert success is expected_success+ if expected_substring is None:+ assert error is None+ else:+ assert error is not None+ assert expected_substring in error.lower()+ probed_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert probed_url.startswith(f"{REVENUECAT_API_BASE_URL}/projects/proj_test/")+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.revenuecat.revenuecat._session")def test_returns_false_on_network_error(self, mock_session):mock_session.return_value.get.side_effect = requests.ConnectionError("dns fail")