Skip to content

: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.

fix(tasks): stop handing out stale tokens for dead github installations (#68891)

Alessandro Pogliaghi046d29c43fca
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 70242fbdfa9c..108ed077855f 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -45,6 +45,8 @@ GITHUB_REPOSITORY_CACHE_TTL_SECONDS = 60 * 60
GITHUB_BRANCH_CACHE_TTL_SECONDS = 60 * 10
GITHUB_BRANCH_CACHE_TIMEOUT_SECONDS = 60 * 60 * 24
+INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY = "installation_unavailable_since"
+
@dataclass(frozen=True)
class GitHubCommitAuthor:
@@ -338,11 +340,13 @@ class GitHubIntegrationBase:
except ValueError as e:
raise Exception(f"Invalid expires_at format from GitHub: {e}")
- self.integration.config = {
+ config = {
**self.integration.config,
"expires_in": expires_in,
"refreshed_at": int(time.time()),
}
+ config.pop(INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, None)
+ self.integration.config = config
self.integration.sensitive_config = {
**(self.integration.sensitive_config or {}),
"access_token": data["token"],
@@ -380,19 +384,32 @@ class GitHubIntegrationBase:
``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.
+ Also stamps ``installation_unavailable_since`` so callers can distinguish a dead installation's
+ stale stored token from a usable one (see :meth:`installation_unavailable`).
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.
+ refresh-retry mints successfully, re-persists the fields, and clears the marker. 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
+ changed = False
+ if "expires_in" in config or "refreshed_at" in config:
+ config.pop("expires_in", None)
+ config.pop("refreshed_at", None)
+ changed = True
+ if INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY not in config:
+ config[INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY] = int(time.time())
+ changed = True
+ if changed:
+ self.integration.config = config
+ return changed
+
+ def installation_unavailable(self) -> bool:
+ """Whether a failed mint marked this installation permanently gone (uninstalled or
+ suspended) and no mint has succeeded since. While True, the stored access token is
+ stale — it survives disarming but GitHub will reject it once it expires server-side."""
+ return bool(self.integration.config.get(INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY))
def _on_token_refresh_failed(self, response: requests.Response) -> None:
"""Called when the installation token refresh request fails.
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 1fdd3f07bf53..9238f8925527 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -1389,9 +1389,30 @@ class TestGitHubIntegrationModel(BaseTest):
assert "expires_in" not in integration.config
assert "refreshed_at" not in integration.config
assert GitHubIntegration(integration).access_token_expired() is False
+ assert integration.config["installation_unavailable_since"]
+ assert GitHubIntegration(integration).installation_unavailable() is True
else:
assert integration.config["expires_in"] == 3600
assert "refreshed_at" in integration.config
+ assert "installation_unavailable_since" not in integration.config
+ assert GitHubIntegration(integration).installation_unavailable() is False
+
+ @patch("posthog.models.integration.reload_integrations_on_workers")
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
+ def test_github_refresh_success_clears_installation_unavailable_marker(self, mock_client_request, _mock_reload):
+ mock_client_request.side_effect = self.mock_github_client_request(status_code=201)
+ integration = self.create_integration(
+ config={"installation_id": "INSTALL", "installation_unavailable_since": 1700000000},
+ sensitive_config={"access_token": "STALE_TOKEN"},
+ )
+
+ GitHubIntegration(integration).refresh_access_token()
+
+ integration.refresh_from_db()
+ assert "installation_unavailable_since" not in integration.config
+ assert GitHubIntegration(integration).installation_unavailable() is False
+ assert integration.sensitive_config["access_token"] == "ACCESS_TOKEN"
+ assert "expires_in" in integration.config
@patch("posthog.egress.transport.transport.requests.request")
@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index d583693b5c0e..ade3b3860aee 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -507,6 +507,26 @@ class TestGetGitIdentityEnvVars(TestCase):
assert result["GIT_AUTHOR_EMAIL"] == "[email protected]"
+class TestGetGithubToken(TestCase):
+ def test_raises_credential_unavailable_for_dead_installation_instead_of_stale_token(self):
+ from posthog.models import Integration, Organization, Team
+
+ from products.tasks.backend.exceptions import CredentialUnavailableError
+ from products.tasks.backend.temporal.process_task.utils import get_github_token
+
+ org = Organization.objects.create(name="o")
+ team = Team.objects.create(organization=org, name="t")
+ integration = Integration.objects.create(
+ team=team,
+ kind="github",
+ config={"installation_id": "INSTALL", "installation_unavailable_since": 1700000000},
+ sensitive_config={"access_token": "ghs_stale"},
+ )
+
+ with self.assertRaises(CredentialUnavailableError):
+ get_github_token(integration.id)
+
+
class TestGetSandboxGitHubToken(TestCase):
@parameterized.expand(
[
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 026ed6dec30f..c840c880fc90 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -24,6 +24,7 @@ from products.tasks.backend.constants import (
SnapshotKind,
filter_user_sandbox_env_vars,
)
+from products.tasks.backend.exceptions import CredentialUnavailableError
from products.tasks.backend.redis import get_tasks_cache
if TYPE_CHECKING:
@@ -510,6 +511,11 @@ def get_github_token(github_integration_id: int) -> Optional[str]:
integration = Integration.objects.get(id=github_integration_id)
github_integration = GitHubIntegration(integration)
+ if github_integration.installation_unavailable():
+ raise CredentialUnavailableError(
+ "GitHub App installation for this integration is uninstalled or suspended",
+ {"github_integration_id": github_integration_id},
+ )
if github_integration.access_token_expired():
github_integration.refresh_access_token()