: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(integrations): keep a github credential that needs reauthorization (#113257)
Vojta Bartošf2c4fa99d1fd
diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.pyindex 7db51688e14a..ce84e75e5a76 100644--- a/posthog/api/github_callback/personal_state.py+++ b/posthog/api/github_callback/personal_state.py@@ -16,7 +16,7 @@ from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_from posthog.egress.limiter.policies import Priorityfrom posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import User-from posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from posthog.models.user_integration import NEEDS_REAUTHORIZATION_Q, UserGitHubIntegration, UserIntegration_OBSERVABILITY_SOURCE = "integration"@@ -36,9 +36,11 @@ class PersonalGitHubDiscovery:def _newest_personal_github_integration(user: User) -> UserIntegration | None:+ # A row flagged for reauthorization holds no user tokens, so it is not a connection.return (UserIntegration.objects.filter(user=user, kind="github").exclude(sensitive_config={})+ .exclude(NEEDS_REAUTHORIZATION_Q).order_by("-created_at").first())@@ -66,7 +68,10 @@ def usable_personal_github_credential(user: User) -> PersonalGitHubCredential |not itself an error."""integrations = (- UserIntegration.objects.filter(user=user, kind="github").exclude(sensitive_config={}).order_by("-created_at")+ UserIntegration.objects.filter(user=user, kind="github")+ .exclude(sensitive_config={})+ .exclude(NEEDS_REAUTHORIZATION_Q)+ .order_by("-created_at"))for integration in integrations:try:diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 0b639d08feb8..b53bb16ab09d 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -7940,7 +7940,7 @@ class TestGitHubDiscoveryAudit(APIBaseTest):assert refreshed.json()["installations"] == []@patch("products.cdp.backend.internal_events.produce_internal_event")- def test_invalid_credential_discard_is_private_and_retained(self, produce: MagicMock) -> None:+ def test_invalid_credential_is_flagged_with_a_private_audit_record(self, produce: MagicMock) -> None:integration = UserIntegration.objects.create(user=self.user,kind="github",@@ -7949,6 +7949,7 @@ class TestGitHubDiscoveryAudit(APIBaseTest):"originating_organization_id": str(self.organization.id),"github_user": {"id": 101, "login": "synthetic-reader"},"user_refresh_token_expires_at": 1,+ "user_token_refreshed_at": int(time.time()) - 7200,},sensitive_config={"user_access_token": "synthetic-private-secret"},)@@ -7962,11 +7963,28 @@ class TestGitHubDiscoveryAudit(APIBaseTest):assert log.team_id is Noneassert log.organization_id == self.organization.idassert log.detail is not None- assert log.detail["trigger"]["payload"]["event"] == "credential_deleted"- assert not UserIntegration.objects.filter(pk=integration_id).exists()+ assert log.detail["trigger"]["payload"]["event"] == "credential_reauthorization_required"+ assert 7200 <= log.detail["trigger"]["payload"]["token_age_seconds"] < 7500+ assert UserIntegration.objects.filter(pk=integration_id).exists()assert "synthetic-private-secret" not in json.dumps(log.detail)produce.assert_not_called()+ def test_flagging_a_credential_deleted_by_a_disconnect_records_nothing(self) -> None:+ integration = UserIntegration.objects.create(+ user=self.user,+ kind="github",+ integration_id="9008",+ config={"originating_organization_id": str(self.organization.id)},+ sensitive_config={"user_access_token": "synthetic-private-secret"},+ )+ stale = UserGitHubIntegration(integration, source="test", priority=Priority.CRITICAL)+ UserIntegration.objects.filter(pk=integration.pk).delete()++ with self.captureOnCommitCallbacks(execute=True):+ stale._mark_needs_reauthorization("refresh rejected by GitHub: bad_refresh_token")++ assert not ActivityLog.objects.filter(item_id=str(integration.pk), activity="github_diagnostic").exists()+def test_github_audit_filters_unknown_fields_from_discovery_logs(self) -> None:candidate = {"installation_id": "9007", "account_name": "synthetic-owner", "token": "synthetic-secret"}with capture_logs() as captured:diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex 061f8ee0a0ef..752c7895ac5e 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -17,13 +17,16 @@ import requestsfrom parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient+from structlog.testing import capture_logs+from posthog.api.github_callback.personal_state import user_has_personal_github_integrationfrom posthog.api.github_callback.state import (load_authorize_state,parse_github_authorize_state_param,store_unified_authorize_state,)from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState+from posthog.api.user_integration import _has_unlinked_github_installationsfrom posthog.egress.limiter.policies import Priorityfrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.models.integration import (@@ -34,6 +37,7 @@ from posthog.models.integration import ()from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.user_integration import (+ NEEDS_REAUTHORIZATION_AT_CONFIG_KEY,GitHubInstallRequest,ReauthorizationRequired,UserGitHubIntegration,@@ -199,6 +203,16 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(data["installation_status"], "unavailable")self.assertEqual(data["repositories"], [{"id": 1, "name": "repo1", "full_name": "octocat/repo1"}])+ @parameterized.expand([("GET", "repos/"), ("POST", "repos/refresh/"), ("GET", "branches/?repo=octocat/repo1")])+ def test_github_installation_endpoints_reject_a_flagged_link(self, method, path):+ integration = _create_user_integration(self.user)+ integration.config = {**integration.config, NEEDS_REAUTHORIZATION_AT_CONFIG_KEY: 1}+ integration.save()++ response = self.client.generic(method, f"/api/users/@me/integrations/github/12345/{path}")++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+def test_list_returns_multiple_github_integrations(self):_create_user_integration(self.user, integration_id="12345")_create_user_integration(@@ -457,12 +471,25 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertIn("client_id=gh_client_123", url)self.assertIn("redirect_uri=https%3A%2F%2Fus.posthog.com%2Fcomplete%2Fgithub-link%2F", url)+ @parameterized.expand(+ [+ ("healthy_link", {}, "app_install", "github.com/apps/posthog-dev/installations/new"),+ (+ "flagged_link",+ {NEEDS_REAUTHORIZATION_AT_CONFIG_KEY: 1},+ "oauth_authorize",+ "github.com/login/oauth/authorize",+ ),+ ]+ )@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")@patch("posthog.api.github_callback.types.get_instance_settings",return_value={"GITHUB_APP_SLUG": "posthog-dev"},)- def test_github_start_posthog_code_skips_fast_path_when_already_linked(self, _mock_settings):+ def test_github_start_posthog_code_fast_path_with_an_existing_link(+ self, _name, link_config, expected_flow, expected_url, _mock_settings+ ):integration = Integration.objects.create(team=self.team,kind="github",@@ -475,7 +502,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):user=self.user,kind="github",integration_id=integration.integration_id,- config={},+ config=link_config,sensitive_config={},)response = self.client.post(@@ -485,8 +512,20 @@ class TestUserIntegrationEndpoints(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)data = response.json()- self.assertEqual(data.get("connect_flow"), "app_install")- self.assertIn("github.com/apps/posthog-dev/installations/new", data["install_url"])+ self.assertEqual(data.get("connect_flow"), expected_flow)+ self.assertIn(expected_url, data["install_url"])++ @parameterized.expand(+ [("healthy_link", {}, False), ("flagged_link", {NEEDS_REAUTHORIZATION_AT_CONFIG_KEY: 1}, True)]+ )+ @patch("posthog.api.user_integration.list_user_github_app_installations", return_value=[{"id": 12345678}])+ def test_has_unlinked_github_installations_counts_a_flagged_link_as_unlinked(+ self, _name, link_config, expected, _mock_list+ ):+ UserIntegration.objects.create(+ user=self.user, kind="github", integration_id="12345678", config=link_config, sensitive_config={}+ )+ self.assertIs(_has_unlinked_github_installations(self.user), expected)@parameterized.expand([("oauth_discover", "posthog_code"), ("app_install", None)])@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")@@ -1141,26 +1180,42 @@ class TestUserGitHubIntegration(APIBaseTest):gh = self._make_integration()self.assertFalse(gh.user_access_token_expired())+ @parameterized.expand(+ [+ ("github_returns_a_new_refresh_token", {"refresh_token": "ghr_new"}, "ghr_new", True),+ ("github_returns_no_refresh_token", {}, "ghr_refresh", False),+ ]+ )@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.models.user_integration.requests.post")- def test_refresh_user_access_token_updates_credentials(self, mock_post):+ def test_refresh_user_access_token_updates_credentials(+ self,+ _name: str,+ refresh_token_field: dict[str, str],+ expected_refresh_token: str,+ expected_rotated: bool,+ mock_post,+ ):mock_response = MagicMock()mock_response.json.return_value = {"access_token": "gho_new",- "refresh_token": "ghr_new",+ **refresh_token_field,"expires_in": 28800,"refresh_token_expires_in": 15897600,}mock_post.return_value = mock_responsegh = self._make_integration(credential_version="synthetic-old-version", identity_verified_at=123)- gh.refresh_user_access_token()+ with capture_logs() as logs, self.captureOnCommitCallbacks(execute=True):+ gh.refresh_user_access_token()gh.integration.refresh_from_db()self.assertNotEqual(gh.integration.config["credential_version"], "synthetic-old-version")self.assertEqual(gh.integration.config["identity_verified_at"], 123)self.assertEqual(gh.user_access_token, "gho_new")- self.assertEqual(gh.user_refresh_token, "ghr_new")+ self.assertEqual(gh.user_refresh_token, expected_refresh_token)+ refreshed = next(entry for entry in logs if entry["event"] == "credential_refreshed")+ self.assertIs(refreshed["refresh_token_rotated"], expected_rotated)@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.models.user_integration.requests.post")@@ -1193,7 +1248,7 @@ class TestUserGitHubIntegration(APIBaseTest):@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.models.user_integration.requests.post")- def test_refresh_discards_row_on_unrecoverable_error(self, mock_post):+ def test_refresh_keeps_the_row_and_flags_it_on_unrecoverable_error(self, mock_post):mock_response = MagicMock()mock_response.json.return_value = {"error": "bad_refresh_token"}mock_post.return_value = mock_response@@ -1201,7 +1256,14 @@ class TestUserGitHubIntegration(APIBaseTest):gh = self._make_integration()with self.assertRaises(ReauthorizationRequired):gh.refresh_user_access_token()- self.assertFalse(UserIntegration.objects.filter(user=self.user, kind="github").exists())+ with self.assertRaises(ReauthorizationRequired):+ gh.get_usable_user_access_token()++ row = UserIntegration.objects.get(user=self.user, kind="github")+ self.assertEqual(row.config["needs_reauthorization_reason"], "refresh rejected by GitHub: bad_refresh_token")+ self.assertNotIn("user_access_token", row.sensitive_config)+ self.assertNotIn("user_refresh_token", row.sensitive_config)+ self.assertTrue(UserGitHubIntegration(row, source="test", priority=Priority.CRITICAL).needs_reauthorization)def test_get_usable_user_access_token_raises_when_refresh_token_expired(self):now = int(time.time())@@ -1275,6 +1337,34 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):self.assertEqual(integration.sensitive_config["user_refresh_token"], "ghr_refresh")self.assertEqual(integration.config["identity_verified_at"], 123)+ @parameterized.expand([("failure_before_reconnect", False), ("stale_failure_after_reconnect", True)])+ def test_a_reconnected_row_stays_usable(self, _name, fail_after_reconnect):+ row = _create_user_integration(self.user)+ stale = UserGitHubIntegration(row, source="test", priority=Priority.CRITICAL)+ if not fail_after_reconnect:+ stale._mark_needs_reauthorization("refresh rejected by GitHub: bad_refresh_token")++ integration = user_github_integration_from_installation(+ self.user,+ GitHubInstallationAccess(+ installation_id=row.integration_id,+ installation_info={"account": {"type": "User", "login": "octocat"}},+ access_token="ghs_install",+ token_expires_at="2099-01-01T00:00:00Z",+ repository_selection="selected",+ ),+ _authorization(),+ )+ if fail_after_reconnect:+ stale._mark_needs_reauthorization("refresh rejected by GitHub: bad_refresh_token")+ integration.refresh_from_db()++ self.assertFalse(+ UserGitHubIntegration(integration, source="test", priority=Priority.CRITICAL).needs_reauthorization+ )+ self.assertEqual(integration.sensitive_config["user_access_token"], "gho_access")+ self.assertTrue(user_has_personal_github_integration(self.user))+def test_different_installation_creates_second_integration(self):_create_user_integration(self.user)integration = user_github_integration_from_installation(diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex dbf38237e0e3..6d8cc6d6fa37 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -64,7 +64,12 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integrationfrom posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import User-from posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegration+from posthog.models.user_integration import (+ NEEDS_REAUTHORIZATION_Q,+ GitHubInstallRequest,+ UserGitHubIntegration,+ UserIntegration,+)from posthog.permissions import APIScopePermission, TimeSensitiveActionPermissionfrom posthog.rate_limit import CodexConnectUserThrottle, UserAuthenticationThrottlefrom posthog.user_permissions import UserPermissions@@ -356,6 +361,17 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):raise exceptions.NotFound()return user+ def _get_connected_github_integration(self, installation_id: str) -> UserIntegration:+ # A flagged row still holds the installation token, but its owner's GitHub authorization is gone.+ integration = (+ UserIntegration.objects.filter(user=self._get_user(), kind="github", integration_id=installation_id)+ .exclude(NEEDS_REAUTHORIZATION_Q)+ .first()+ )+ if integration is None:+ raise exceptions.NotFound("No GitHub integration found for this installation.")+ return integration+def _team_github_installation_ids(self, user: User) -> set[str]:"""Installation IDs for the current team's GitHub integrations (for ``uses_shared_installation``)."""team = user.current_team@@ -484,11 +500,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):query_serializer = GitHubReposQuerySerializer(data=request.query_params)query_serializer.is_valid(raise_exception=True)- integration = UserIntegration.objects.filter(- user=self._get_user(), kind="github", integration_id=installation_id- ).first()- if integration is None:- raise exceptions.NotFound("No GitHub integration found for this installation.")+ integration = self._get_connected_github_integration(installation_id)return Response(github_repos_page(@@ -505,11 +517,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):@action(methods=["POST"], detail=False, url_path=r"github/(?P<installation_id>\d+)/repos/refresh")def github_repos_refresh(self, request: Request, installation_id: str, **_kwargs) -> Response:"""Refresh repositories accessible to a specific GitHub installation."""- integration = UserIntegration.objects.filter(- user=self._get_user(), kind="github", integration_id=installation_id- ).first()- if integration is None:- raise exceptions.NotFound("No GitHub integration found for this installation.")+ integration = self._get_connected_github_integration(installation_id)github = UserGitHubIntegration(integration, source="user_integrations_api", priority=Priority.CRITICAL)try:@@ -548,11 +556,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):validate_github_repository_name(repo)- integration = UserIntegration.objects.filter(- user=self._get_user(), kind="github", integration_id=installation_id- ).first()- if integration is None:- raise exceptions.NotFound("No GitHub integration found for this installation.")+ integration = self._get_connected_github_integration(installation_id)github = UserGitHubIntegration(integration, source="github_branch_picker", priority=Priority.CRITICAL)branches, default_branch, has_more = github.list_cached_branches(@@ -944,7 +948,11 @@ def _has_unlinked_github_installations(user: User) -> bool | None:return Nonegithub_installation_ids = {str(installation["id"]) for installation in installations}- linked_ids = set(UserIntegration.objects.filter(user=user, kind="github").values_list("integration_id", flat=True))+ linked_ids = set(+ UserIntegration.objects.filter(user=user, kind="github")+ .exclude(NEEDS_REAUTHORIZATION_Q)+ .values_list("integration_id", flat=True)+ )return bool(github_installation_ids - linked_ids)@@ -975,7 +983,11 @@ def _attempt_app_oauth_fast_path(team_installation_id = _team_github_installation_id(team)if team_installation_id is None:return None- if UserIntegration.objects.filter(user=user, kind="github", integration_id=team_installation_id).exists():+ if (+ UserIntegration.objects.filter(user=user, kind="github", integration_id=team_installation_id)+ .exclude(NEEDS_REAUTHORIZATION_Q)+ .exists()+ ):return Nonegithub_callback_state.store_unified_authorize_state(GitHubAuthorizeState(diff --git a/posthog/models/integration/github_audit.py b/posthog/models/integration/github_audit.pyindex 2d354174257d..15240595a552 100644--- a/posthog/models/integration/github_audit.py+++ b/posthog/models/integration/github_audit.py@@ -60,9 +60,10 @@ class GitHubAuditPayload:"deleted": {"outcome"},"credential_created": {"reason"},"credential_replaced": {"reason"},- "credential_refreshed": {"reason"},+ "credential_refreshed": {"reason", "refresh_token_rotated"},"credential_deleted": {"reason"},- "credential_delete_failed": {"failure_type"},+ "credential_reauthorization_required": {"reason", "token_age_seconds"},+ "credential_mark_failed": {"failure_type"},"discovery_credential_selected": {"discovery_id", *PERSONAL_FIELDS},"discovery_github_response": {"discovery_id", "github_status", "github_request_id"},"discovery_candidates": {"discovery_id", "source"},diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex ae2cd80f54d5..9baecfdaa5e9 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Anyfrom uuid import UUID, uuid4from django.conf import settings-from django.db import models+from django.db import models, transactionfrom django.utils.functional import Promiseimport requests@@ -26,13 +26,17 @@ logger = structlog.get_logger(__name__)# GitHub rejects a refresh token with one of these error codes when it's no longer valid and the user can remediate this-# We then force the user to re-authorize through the install flow, by deleting the bad integration+# We then force the user to re-authorize through the install flow, by flagging the bad integration_GITHUB_UNRECOVERABLE_REFRESH_ERRORS = {"bad_refresh_token","refresh_token_expired","unauthorized_client",}+NEEDS_REAUTHORIZATION_AT_CONFIG_KEY = "needs_reauthorization_at"+# A flagged GitHub row keeps its installation token, so `.exclude(sensitive_config={})` does not filter it out.+NEEDS_REAUTHORIZATION_Q = models.Q(config__has_key=NEEDS_REAUTHORIZATION_AT_CONFIG_KEY)+def user_integration_kind_choices() -> list[tuple[str, str | Promise]]:return list(UserIntegration.IntegrationKind.choices)@@ -297,11 +301,16 @@ class UserGitHubIntegration(GitHubIntegrationBase):return Falsereturn time.time() > expires_at+ @property+ def needs_reauthorization(self) -> bool:+ """Whether the stored user tokens were stripped and the person has to reconnect."""+ return bool((self.integration.config or {}).get(NEEDS_REAUTHORIZATION_AT_CONFIG_KEY))+def refresh_user_access_token(self) -> None:"""Exchange the refresh token for a fresh user-to-server access token.- Deletes the integration row and raises :class:`ReauthorizationRequired`- when GitHub signals the refresh token can't produce a new access token.+ Strips the stored tokens and raises :class:`ReauthorizationRequired` when GitHub+ signals the refresh token can't produce a new access token."""client_id = settings.GITHUB_APP_CLIENT_IDclient_secret = settings.GITHUB_APP_CLIENT_SECRET@@ -309,7 +318,7 @@ class UserGitHubIntegration(GitHubIntegrationBase):if not client_id or not client_secret:raise Exception("GITHUB_APP_CLIENT_ID / GITHUB_APP_CLIENT_SECRET not configured, cannot refresh user token")if not refresh_token:- self._discard("no user refresh token stored")+ self._mark_needs_reauthorization("no user refresh token stored")raise ReauthorizationRequired("No refresh token stored for this GitHub integration.")response = requests.post(@@ -331,7 +340,7 @@ class UserGitHubIntegration(GitHubIntegrationBase):if not access_token:error = payload.get("error")if error in _GITHUB_UNRECOVERABLE_REFRESH_ERRORS:- self._discard(f"refresh rejected by GitHub: {error}")+ self._mark_needs_reauthorization(f"refresh rejected by GitHub: {error}")raise ReauthorizationRequired(f"GitHub refused the stored refresh token ({error}).")raise Exception(f"Unexpected refresh failure from GitHub: {error or response.status_code}")@@ -340,14 +349,14 @@ class UserGitHubIntegration(GitHubIntegrationBase):def get_usable_user_access_token(self) -> str:"""Return a non-expired user-to-server access token, refreshing on demand.- Raises :class:`ReauthorizationRequired` if the row lacks tokens, the- refresh token is expired, or GitHub rejects a refresh attempt.+ Raises :class:`ReauthorizationRequired` if the row lacks tokens, the refresh token is+ expired, or GitHub rejects a refresh attempt. The row is kept and flagged in those cases."""if not self.user_access_token:- self._discard("no user access token stored")+ self._mark_needs_reauthorization("no user access token stored")raise ReauthorizationRequired("No user access token stored for this GitHub integration.")if self.user_refresh_token_expired():- self._discard("user refresh token expired")+ self._mark_needs_reauthorization("user refresh token expired")raise ReauthorizationRequired("The stored GitHub user refresh token has expired.")if self.user_access_token_expired():self.refresh_user_access_token()@@ -522,7 +531,8 @@ class UserGitHubIntegration(GitHubIntegrationBase):"""Write a fresh user token pair + expirations onto the integration row."""now = int(time.time())access_token = payload.get("access_token")- refresh_token = payload.get("refresh_token") or self.user_refresh_token+ rotated_refresh_token = payload.get("refresh_token")+ refresh_token = rotated_refresh_token or self.user_refresh_tokenaccess_expires_in = payload.get("expires_in")refresh_expires_in = payload.get("refresh_token_expires_in")@@ -546,22 +556,75 @@ class UserGitHubIntegration(GitHubIntegrationBase):config.pop("user_refresh_token_expires_at", None)self.integration.config = configself.integration.save(update_fields=["sensitive_config", "config", "updated_at"])- GitHubAudit.personal(self.integration).record("credential_refreshed", after_commit=True, reason="oauth_refresh")+ GitHubAudit.personal(self.integration).record(+ "credential_refreshed",+ after_commit=True,+ reason="oauth_refresh",+ refresh_token_rotated=bool(rotated_refresh_token),+ )++ def _user_token_age_seconds(self) -> int | None:+ """Seconds since the stored user token pair was last written, or None when the row holds no+ refresh timestamp. It tells a token GitHub invalidated moments ago from one that sat stale+ for hours, which is the difference between a refresh race and a bad stored token.+ """+ refreshed_at = (self.integration.config or {}).get("user_token_refreshed_at")+ if not isinstance(refreshed_at, (int, float)):+ return None+ return int(time.time()) - int(refreshed_at)- def _discard(self, reason: str) -> None:- """Delete the integration when stored credentials are unusable.+ def _mark_needs_reauthorization(self, reason: str) -> None:+ """Strip the unusable tokens and flag the row for reconnection, keeping the row itself.- Deletion keeps the invariant that every integration row carries working tokens.- The user falls back to the Connect flow.+ Every caller raises :class:`ReauthorizationRequired` straight after. The kept row gives the+ person a connection to repair and records why it stopped working. A real disconnection is+ a different path: the views delete the row themselves."""- logger.info("UserGitHubIntegration: discarding integration", user_id=self.integration.user_id, reason=reason)+ token_age_seconds = self._user_token_age_seconds()+ failed_credential_version = (self.integration.config or {}).get("credential_version")+ logger.info(+ "UserGitHubIntegration: marking integration for reauthorization",+ user_id=self.integration.user_id,+ reason=reason,+ )audit = GitHubAudit.personal(self.integration)try:- self.integration.delete()- audit.record("credential_deleted", after_commit=True, reason=reason)+ with transaction.atomic():+ try:+ row = UserIntegration.objects.select_for_update().get(pk=self.integration.pk)+ except UserIntegration.DoesNotExist:+ # A disconnect deleted the row after this wrapper read it, so there is nothing to flag.+ return+ config = row.config or {}+ # Another writer changed the row after this wrapper read it. A new credential version+ # means a reconnect or a refresh stored working tokens, and an existing flag holds the+ # first failure's reason. Writing the stale copy would erase either one.+ if (+ config.get("credential_version") != failed_credential_version+ or NEEDS_REAUTHORIZATION_AT_CONFIG_KEY in config+ ):+ self.integration = row+ return+ sensitive_config = dict(row.sensitive_config or {})+ sensitive_config.pop("user_access_token", None)+ sensitive_config.pop("user_refresh_token", None)+ row.sensitive_config = sensitive_config+ row.config = {+ **config,+ "needs_reauthorization_reason": reason,+ NEEDS_REAUTHORIZATION_AT_CONFIG_KEY: int(time.time()),+ }+ row.save(update_fields=["sensitive_config", "config", "updated_at"])+ self.integration = row+ audit.record(+ "credential_reauthorization_required",+ after_commit=True,+ reason=reason,+ token_age_seconds=token_age_seconds,+ )except Exception as exc:- audit.record("credential_delete_failed", failure_type=type(exc).__name__)- logger.warning("UserGitHubIntegration: failed to delete unusable integration", exc_info=True)+ audit.record("credential_mark_failed", failure_type=type(exc).__name__)+ logger.warning("UserGitHubIntegration: failed to mark integration for reauthorization", exc_info=True)def user_github_integration_from_installation(diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex a614aa39d69e..c44ac95da15f 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -4,6 +4,10 @@ from django.test import SimpleTestCase, TestCase, override_settingsfrom parameterized import parameterized+from posthog.egress.limiter.policies import Priority+from posthog.models.user import User+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from products.mcp_store.backend.facade.contracts import ActiveInstallationfrom products.tasks.backend.constants import (DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,@@ -28,6 +32,7 @@ from products.tasks.backend.temporal.process_task.utils import (get_supported_reasoning_efforts,get_task_run_actor_user,get_task_run_credential_user,+ get_user_github_integration,get_user_mcp_server_configs,is_bot_authorship_fallback,is_caller_token_run,@@ -957,6 +962,33 @@ class TestSlackTaskRunActorUser(TestCase):assert get_task_run_credential_user(task, state) == creator+class TestGetUserGithubIntegration(TestCase):+ def test_a_flagged_install_is_skipped_for_a_healthy_one(self) -> None:+ user = User.objects.create(email="[email protected]")+ flagged = UserIntegration.objects.create(+ user=user,+ kind="github",+ integration_id="111",+ config={"installation_id": "111"},+ sensitive_config={"user_access_token": "gho_a", "user_refresh_token": "ghr_a"},+ )+ UserIntegration.objects.create(+ user=user,+ kind="github",+ integration_id="222",+ config={"installation_id": "222"},+ sensitive_config={"user_access_token": "gho_b", "user_refresh_token": "ghr_b"},+ )+ UserGitHubIntegration(flagged, source="test", priority=Priority.CRITICAL)._mark_needs_reauthorization(+ "refresh rejected by GitHub: bad_refresh_token"+ )++ resolved = get_user_github_integration(user)++ assert resolved is not None+ assert resolved.integration.integration_id == "222"++class TestGetSandboxGitHubToken(SimpleTestCase):@parameterized.expand([diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex ba35c823461d..9d3412b7d184 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -19,7 +19,12 @@ from posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_tfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.user import User-from posthog.models.user_integration import ReauthorizationRequired, UserGitHubIntegration, UserIntegration+from posthog.models.user_integration import (+ NEEDS_REAUTHORIZATION_Q,+ ReauthorizationRequired,+ UserGitHubIntegration,+ UserIntegration,+)from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, has_write_scopesfrom products.mcp_store.backend.facade.api import get_installations_for_sandbox@@ -1096,7 +1101,9 @@ def get_user_github_integration(return Nonenormalized_repository = _normalize_repository(repository)- integrations = UserIntegration.objects.filter(user=user, kind="github").order_by("created_at")+ integrations = (+ UserIntegration.objects.filter(user=user, kind="github").exclude(NEEDS_REAUTHORIZATION_Q).order_by("created_at")+ )if github_user_integration_id:integrations = integrations.filter(id=github_user_integration_id)@@ -1145,6 +1152,7 @@ def resolve_user_github_integration_for_task(kind="github",integration_id=team_installation_id,)+ .exclude(NEEDS_REAUTHORIZATION_Q).order_by("created_at").first())