: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(devex): stop reminting github tokens for dead installations (#68505)
Julian Bez578cdfe110a2
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 6ee1d201f062..d498a04a666e 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -22,7 +22,7 @@ import requestsimport structlogfrom prometheus_client import Counter-from posthog.egress.github.transport import github_request, raise_if_github_rate_limited+from posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limitedfrom posthog.sync import database_sync_to_async_poollogger = structlog.get_logger(__name__)@@ -343,17 +343,64 @@ class GitHubIntegrationBase:self._on_token_refreshed()self.integration.save()+ @staticmethod+ def _installation_permanently_unavailable(response: requests.Response) -> bool:+ """Whether a mint response (POST installations/{id}/access_tokens) shows the installation is+ permanently gone — 404 (uninstalled) or a 403 suspension — as opposed to a transient failure.++ A rate-limited 403 is transient and must return False, so a live installation is never mistaken+ for a dead one: the shared :func:`raise_if_github_rate_limited` detector is the single source of+ truth for that, and any 403 it doesn't flag as a rate limit is only treated as suspension when+ the body says so. When in doubt, return False and leave the row armed.+ """+ if response.status_code == 404:+ return True+ if response.status_code != 403:+ return False+ try:+ raise_if_github_rate_limited(response)+ except GitHubRateLimitError:+ return False+ try:+ body = (response.text or "").lower()+ except Exception:+ body = ""+ return "suspended" in body++ def _disarm_proactive_refresh_if_installation_gone(self, response: requests.Response) -> bool:+ """Stop the every-minute beat loop from re-minting a dead installation forever.++ ``access_token_expired()`` returns False when ``config`` lacks ``expires_in``/``refreshed_at``,+ so dropping those two keys permanently disarms proactive refresh for this row. Only fires for a+ permanently-gone installation (404 uninstalled / 403 suspended), never a transient failure.+ Self-healing: if the installation is later restored, a real API call 401s and ``api_request``'s+ refresh-retry mints successfully and re-persists the fields. Mutates ``config`` in memory and+ returns whether anything changed; the caller owns the save.+ """+ if not self._installation_permanently_unavailable(response):+ return False+ config = {**self.integration.config}+ if "expires_in" not in config and "refreshed_at" not in config:+ return False+ config.pop("expires_in", None)+ config.pop("refreshed_at", None)+ self.integration.config = config+ return True+def _on_token_refresh_failed(self, response: requests.Response) -> None:"""Called when the installation token refresh request fails.Override to persist error state, increment counters, etc. The base- implementation only logs.+ implementation logs and, for a permanently-gone installation, disarms the+ every-minute proactive refresh so a dead row isn't re-minted forever."""logger.warning("GitHubIntegration: installation token refresh failed",integration_id=self.integration.id,status_code=response.status_code,)+ if self._disarm_proactive_refresh_if_installation_gone(response):+ self.integration.save(update_fields=["config"])def _on_token_refreshed(self) -> None:"""Called after a successful token refresh, before ``save()``.diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 5c5219619807..94863d79d32b 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -2586,6 +2586,9 @@ class GitHubIntegration(GitHubIntegrationBase):def _on_token_refresh_failed(self, response: requests.Response) -> None:logger.warning(f"Failed to refresh token for {self}", response=response.text)self.integration.errors = ERROR_TOKEN_REFRESH_FAILED+ # A permanently-gone installation (uninstalled/suspended) drops expires_in/refreshed_at so the+ # every-minute beat loop stops re-minting it; the errors + config change persist in one save.+ self._disarm_proactive_refresh_if_installation_gone(response)oauth_refresh_counter.labels(self.integration.kind, "failed").inc()self.integration.save()diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 8db67b4a8568..c731bede2d6f 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -1285,6 +1285,43 @@ class TestGitHubIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.errors == ""+ @parameterized.expand(+ [+ ("uninstalled_404", 404, "Not Found", {}, True),+ ("suspended_403", 403, "This installation has been suspended.", {}, True),+ ("rate_limited_403", 403, "You have exceeded a secondary rate limit", {"retry-after": "60"}, False),+ ("transient_500", 500, "Server Error", {}, False),+ ]+ )+ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_refresh_disarms_proactive_refresh_only_for_dead_installation(+ self, _name, status_code, text, headers, expected_disarmed, mock_client_request, _mock_reload+ ):+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.text = text+ response.headers = headers+ response.json.return_value = {}+ mock_client_request.return_value = response++ integration = self.create_integration(+ config={"installation_id": "INSTALL", "expires_in": 3600, "refreshed_at": int(time.time()) - 3600},+ sensitive_config={"access_token": "ACCESS_TOKEN"},+ )++ with pytest.raises(GitHubIntegrationError):+ GitHubIntegration(integration).refresh_access_token()++ integration.refresh_from_db()+ if expected_disarmed:+ assert "expires_in" not in integration.config+ assert "refreshed_at" not in integration.config+ assert GitHubIntegration(integration).access_token_expired() is False+ else:+ assert integration.config["expires_in"] == 3600+ assert "refreshed_at" in integration.config+@patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_list_repositories_retries_transient_non_json_response(self, _mock_expired, mock_get):diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex 59e467c8d1b2..f34e1b0bb5eb 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -147,6 +147,8 @@ class UserGitHubIntegration(GitHubIntegrationBase):user_id=self.integration.user_id,status_code=response.status_code,)+ if self._disarm_proactive_refresh_if_installation_gone(response):+ self.integration.save(update_fields=["config"])def _on_token_refreshed(self) -> None:logger.info(diff --git a/posthog/tasks/integrations.py b/posthog/tasks/integrations.pyindex 37890bc5c08f..fe7d16343665 100644--- a/posthog/tasks/integrations.py+++ b/posthog/tasks/integrations.py@@ -61,18 +61,25 @@ def refresh_integration(id: int) -> int:integration = defer_repository_cache_fields(Integration.objects.all()).get(id=id)+ # Re-check freshness against the just-loaded row before minting. Under an INTEGRATIONS queue+ # backlog several duplicate refreshes can pile up for the same row; the first mints a fresh token+ # and this keeps the rest from re-minting one that's already valid.if integration.kind in OauthIntegration.supported_kinds:oauth_integration = OauthIntegration(integration)- oauth_integration.refresh_access_token()+ if oauth_integration.access_token_expired():+ oauth_integration.refresh_access_token()elif integration.kind in GoogleCloudIntegration.supported_kinds:gcloud_integration = GoogleCloudIntegration(integration)- gcloud_integration.refresh_access_token()+ if gcloud_integration.access_token_expired():+ gcloud_integration.refresh_access_token()elif integration.kind == "github":github_integration = GitHubIntegration(integration)- github_integration.refresh_access_token()+ if github_integration.access_token_expired():+ github_integration.refresh_access_token()elif integration.kind == "firebase":firebase_integration = FirebaseIntegration(integration)- firebase_integration.refresh_access_token()+ if firebase_integration.access_token_expired():+ firebase_integration.refresh_access_token()return 0diff --git a/posthog/tasks/test/test_integrations.py b/posthog/tasks/test/test_integrations.pyindex b5a739f0ddee..843607b97c46 100644--- a/posthog/tasks/test/test_integrations.py+++ b/posthog/tasks/test/test_integrations.py@@ -4,8 +4,10 @@ from typing import Optionalfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from parameterized import parameterized+from posthog.models.integration import Integration-from posthog.tasks.integrations import refresh_integrations+from posthog.tasks.integrations import refresh_integration, refresh_integrationsclass TestIntegrationsTasks(APIBaseTest):@@ -36,3 +38,21 @@ class TestIntegrationsTasks(APIBaseTest):refresh_integrations()# Both 3 and 4 should be refreshedassert refresh_integration_mock.call_args_list == [((integration_3.id,),), ((integration_4.id,),)]++ @parameterized.expand(+ [+ ("expired", int(time.time()) - 3600, True),+ ("fresh", int(time.time()), False),+ ]+ )+ def test_refresh_integration_mints_only_when_still_expired(+ self, _name: str, refreshed_at: float, expected_refreshed: bool+ ) -> None:+ # Duplicate tasks can queue up for one row under backlog; refresh_integration must re-check the+ # just-loaded row so a task that finds it already fresh skips the mint instead of re-minting.+ integration = self.create_integration("github", config={"refreshed_at": refreshed_at, "expires_in": 3600})++ with patch("posthog.models.integration.GitHubIntegration.refresh_access_token") as refresh_mock:+ refresh_integration(integration.id)++ assert refresh_mock.called is expected_refreshed