: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
feat(integrations): fallback oauth client credentials on rotation (#70257)
Javier Bahamondes8837dafc41cb
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex d4d7bb61f551..5e937ee561e3 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -111,6 +111,7 @@ REFRESH_TERMINAL_FAILURE_COUNT = 5REFRESH_FAILURE_REASON_INVALID_GRANT = "invalid_grant"REFRESH_FAILURE_REASON_INVALID_CLIENT = "invalid_client"REFRESH_FAILURE_REASON_HTTP_5XX = "http_5xx"+REFRESH_FAILURE_REASON_NETWORK = "network"REFRESH_FAILURE_REASON_OTHER = "other"@@ -456,6 +457,8 @@ class OauthConfig:token_info_graphql_query: str | None = Nonetoken_info_config_fields: list[str] | None = Noneadditional_authorize_params: dict[str, str] | None = None+ client_id_fallback: str | None = None+ client_secret_fallback: str | None = None# When true, the authorize/token-exchange flow uses PKCE (RFC 7636, S256)pkce: bool = False# When set, disconnecting the integration also revokes the grant at the provider@@ -514,6 +517,15 @@ class OauthIntegration:@classmethod@cache_for(timedelta(minutes=5))def oauth_config_for_kind(cls, kind: str) -> OauthConfig:+ config = cls._build_oauth_config(kind)+ fallback = settings.OAUTH_CLIENT_FALLBACKS.get(kind)+ if fallback and fallback.get("client_secret"):+ config.client_secret_fallback = fallback["client_secret"]+ config.client_id_fallback = fallback.get("client_id") or config.client_id+ return config++ @classmethod+ def _build_oauth_config(cls, kind: str) -> OauthConfig:if kind == "slack":from_settings = get_instance_settings([@@ -1272,97 +1284,131 @@ class OauthIntegration:return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()- def refresh_access_token(self):- """- Refresh the access token for the integration if necessary- """- oauth_config = self.oauth_config_for_kind(self.integration.kind)-- # Clear out previous token refreshing errors, as they'll be re-set below if another error occurs- self.integration.errors = ""+ def _post_token_refresh(self, oauth_config: OauthConfig, client_id: str, client_secret: str) -> requests.Response:+ refresh_token = self.integration.sensitive_config["refresh_token"]+ kind = self.integration.kind# Reddit uses HTTP Basic Auth for token refresh- if self.integration.kind == "reddit-ads":- res = requests.post(+ if kind == "reddit-ads":+ return requests.post(oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),- data={- "refresh_token": self.integration.sensitive_config["refresh_token"],- "grant_type": "refresh_token",- },+ auth=HTTPBasicAuth(client_id, client_secret),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},# If I use a standard User-Agent, it will throw a 429 too many requests errorheaders={"User-Agent": "PostHog/1.0 by PostHogTeam"},timeout=10,)# Pinterest uses HTTP Basic Auth for token refresh- elif self.integration.kind == "pinterest-ads":- res = requests.post(+ elif kind == "pinterest-ads":+ return requests.post(oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_id, oauth_config.client_secret),- data={- "refresh_token": self.integration.sensitive_config["refresh_token"],- "grant_type": "refresh_token",- },+ auth=HTTPBasicAuth(client_id, client_secret),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},timeout=10,)- elif self.integration.kind == "tiktok-ads":- res = requests.post(+ elif kind == "tiktok-ads":+ return requests.post("https://open.tiktokapis.com/v2/oauth/token/",data={- "client_key": oauth_config.client_id, # TikTok uses client_key instead of client_id- "client_secret": oauth_config.client_secret,- "refresh_token": self.integration.sensitive_config["refresh_token"],+ "client_key": client_id, # TikTok uses client_key instead of client_id+ "client_secret": client_secret,+ "refresh_token": refresh_token,"grant_type": "refresh_token",},headers={"Content-Type": "application/x-www-form-urlencoded"},timeout=10,)- elif self.integration.kind == "bing-ads":+ elif kind == "bing-ads":# Microsoft Azure AD requires scope parameter on token refresh- res = requests.post(+ return requests.post(oauth_config.token_url,data={- "client_id": oauth_config.client_id,- "client_secret": oauth_config.client_secret,- "refresh_token": self.integration.sensitive_config["refresh_token"],+ "client_id": client_id,+ "client_secret": client_secret,+ "refresh_token": refresh_token,"grant_type": "refresh_token","scope": oauth_config.scope,},timeout=10,)- elif self.integration.kind == "stripe":+ elif kind == "stripe":# Stripe Apps OAuth: secret as HTTP Basic username, no client_id/client_secret in body.- res = requests.post(+ return requests.post(oauth_config.token_url,- auth=HTTPBasicAuth(oauth_config.client_secret, ""),- data={- "refresh_token": self.integration.sensitive_config["refresh_token"],- "grant_type": "refresh_token",- },+ auth=HTTPBasicAuth(client_secret, ""),+ data={"refresh_token": refresh_token, "grant_type": "refresh_token"},timeout=10,)else:- res = requests.post(+ return requests.post(oauth_config.token_url,data={- "client_id": oauth_config.client_id,- "client_secret": oauth_config.client_secret,- "refresh_token": self.integration.sensitive_config["refresh_token"],+ "client_id": client_id,+ "client_secret": client_secret,+ "refresh_token": refresh_token,"grant_type": "refresh_token",},timeout=10,)+ @staticmethod+ def _parse_token_refresh_response(res: requests.Response) -> dict:try:- config: dict = res.json()+ return res.json()except ValueError:# e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exception- config = {}+ return {}- if res.status_code != 200 or not config.get("access_token"):- logger.warning(f"Failed to refresh token for {self}", response=res.text)+ def refresh_access_token(self):+ """+ Refresh the access token for the integration if necessary+ """+ oauth_config = self.oauth_config_for_kind(self.integration.kind)++ # Clear out previous token refreshing errors, as they'll be re-set below if another error occurs+ self.integration.errors = ""++ res: requests.Response | None = None+ config: dict = {}+ used_fallback = False+ try:+ res = self._post_token_refresh(oauth_config, oauth_config.client_id, oauth_config.client_secret)+ config = self._parse_token_refresh_response(res)+ except requests.RequestException as e:+ # A network error (timeout, connection reset) is a failed refresh, not a crash. Without+ # this the Celery sweep task errors out before recording the failure, so the backoff and+ # the TOKEN_REFRESH_FAILED reconnect state are never persisted.+ logger.warning(f"Network error on primary credentials for {self}", error=str(e))++ # A rotated or migrated OAuth app leaves users with refresh tokens only the previous+ # credentials can refresh. Retry with the fallback pair — including when the primary hit a+ # network error — so they keep working until they reconnect.+ if (+ res is None or res.status_code != 200 or not config.get("access_token")+ ) and oauth_config.client_secret_fallback:+ try:+ res = self._post_token_refresh(+ oauth_config,+ oauth_config.client_id_fallback or oauth_config.client_id,+ oauth_config.client_secret_fallback,+ )+ config = self._parse_token_refresh_response(res)+ used_fallback = True+ except requests.RequestException as e:+ logger.warning(f"Network error on fallback credentials for {self}", error=str(e))+ res = None+ config = {}++ if res is None or res.status_code != 200 or not config.get("access_token"):+ logger.warning(+ f"Failed to refresh token for {self}", response=res.text if res is not None else "network error"+ )self.integration.errors = ERROR_TOKEN_REFRESH_FAILED- reason = oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)+ reason = (+ oauth_refresh_failure_reason(res.status_code, config, kind=self.integration.kind)+ if res is not None+ else REFRESH_FAILURE_REASON_NETWORK+ )attempt = record_refresh_failure(self.integration, reason=reason)oauth_refresh_counter.labels(kind=self.integration.kind, result="failed", reason=reason, attempt=attempt@@ -1389,7 +1435,12 @@ class OauthIntegration:self.integration.config["expires_in"] = expires_inself.integration.config["refreshed_at"] = int(time.time())reload_integrations_on_workers(self.integration.team_id, [self.integration.id])- oauth_refresh_counter.labels(kind=self.integration.kind, result="success", reason="", attempt="").inc()+ oauth_refresh_counter.labels(+ kind=self.integration.kind,+ result="success_fallback" if used_fallback else "success",+ reason="",+ attempt="",+ ).inc()self.integration.save()diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex a96a6109510e..7337e77be401 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -596,6 +596,86 @@ class TestOauthIntegrationModel(BaseTest):mock_reload.assert_not_called()+ def _mock_token_response(self, status_code: int, token: Optional[str]) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = {"access_token": token, "expires_in": 1000} if token else {}+ response.text = "error"+ return response++ @parameterized.expand(+ [+ # Primary works: the fallback must not fire, even when configured.+ ("primary_ok", True, [(200, "primary-token")], "primary-token", "", 1),+ # A token issued by the previous app only refreshes with the fallback pair.+ ("fallback_rescues", True, [(401, None), (200, "fallback-token")], "fallback-token", "", 2),+ # Both credentials failing still marks the integration errored so the reconnect banner shows.+ ("both_fail", True, [(401, None), (401, None)], None, "TOKEN_REFRESH_FAILED", 2),+ # Without a fallback configured, behavior is identical to before: a single attempt, no retry.+ ("no_fallback_no_retry", False, [(401, None)], None, "TOKEN_REFRESH_FAILED", 1),+ ]+ )+ def test_refresh_falls_back_to_previous_credentials(+ self, _name, has_fallback, responses, expected_token, expected_errors, expected_calls+ ):+ fallbacks = {"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}} if has_fallback else {}+ integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})++ with (+ self.settings(+ BING_ADS_CLIENT_ID="new-app-id",+ BING_ADS_CLIENT_SECRET="new-app-secret",+ OAUTH_CLIENT_FALLBACKS=fallbacks,+ ),+ patch("posthog.models.integration.reload_integrations_on_workers"),+ patch(+ "posthog.models.integration.requests.post",+ side_effect=[self._mock_token_response(status, token) for status, token in responses],+ ) as mock_post,+ ):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert mock_post.call_count == expected_calls+ assert integration.errors == expected_errors+ if expected_token is not None:+ assert integration.sensitive_config["access_token"] == expected_token++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_network_error_marks_failed_without_raising(self, mock_post, mock_reload):+ # A timeout must not escape refresh_access_token: the Celery sweep would error out before+ # recording the failure, leaving the integration without a backoff or the reconnect state.+ mock_post.side_effect = requests.Timeout("timed out")+ integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})++ with self.settings(BING_ADS_CLIENT_ID="new-app-id", BING_ADS_CLIENT_SECRET="new-app-secret"):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert integration.config.get("refresh_failure_count") == 1+ assert integration.config.get("refresh_next_attempt_at")++ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_refresh_primary_network_error_still_tries_fallback(self, mock_post, mock_reload):+ # A network error on the primary credentials must not skip the fallback attempt.+ mock_post.side_effect = [requests.Timeout("timed out"), self._mock_token_response(200, "fallback-token")]+ integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})++ with self.settings(+ BING_ADS_CLIENT_ID="new-app-id",+ BING_ADS_CLIENT_SECRET="new-app-secret",+ OAUTH_CLIENT_FALLBACKS={"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}},+ ):+ OauthIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ assert mock_post.call_count == 2+ assert integration.errors == ""+ assert integration.sensitive_config["access_token"] == "fallback-token"+@patch("posthog.models.integration.reload_integrations_on_workers")@patch("posthog.models.integration.requests.post")def test_refresh_access_token_resets_errors(self, mock_post, mock_reload):diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 469549cf8acc..9359b00d5e3f 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -48,6 +48,8 @@ META_ADS_APP_CLIENT_SECRET = get_from_env("META_ADS_APP_CLIENT_SECRET", "")BING_ADS_CLIENT_ID = get_from_env("BING_ADS_CLIENT_ID", "")BING_ADS_CLIENT_SECRET = get_from_env("BING_ADS_CLIENT_SECRET", "")+BING_ADS_CLIENT_ID_FALLBACK = get_from_env("BING_ADS_CLIENT_ID_FALLBACK", "")+BING_ADS_CLIENT_SECRET_FALLBACK = get_from_env("BING_ADS_CLIENT_SECRET_FALLBACK", "")BING_ADS_DEVELOPER_TOKEN = get_from_env("BING_ADS_DEVELOPER_TOKEN", "")REDDIT_ADS_CLIENT_ID = get_from_env("REDDIT_ADS_CLIENT_ID", "")@@ -121,3 +123,13 @@ HEATMAP_BROWSERLESS_TOKEN = get_from_env("HEATMAP_BROWSERLESS_TOKEN", "")HEATMAP_BROWSERLESS_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_TIMEOUT_MS", 180000, type_cast=int)HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS", 30000, type_cast=int)HEATMAP_BROWSERLESS_BLOCK_ADS = get_from_env("HEATMAP_BROWSERLESS_BLOCK_ADS", False, type_cast=str_to_bool)++# Legacy OAuth client credentials kept alive during an app or secret rotation.+# Refreshes fall back to these when the primary credentials fail, so tokens issued+# by a since-migrated app keep working until users reconnect.+OAUTH_CLIENT_FALLBACKS: dict[str, dict[str, str]] = {+ "bing-ads": {+ "client_id": BING_ADS_CLIENT_ID_FALLBACK,+ "client_secret": BING_ADS_CLIENT_SECRET_FALLBACK,+ },+}