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.

feat(integrations): bi-directional uninstall for github app (#61543)

Oliver Browne2d932f494c55
diff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.py
new file mode 100644
index 000000000000..46d85021956b
--- /dev/null
+++ b/posthog/api/github_callback/installation_events.py
@@ -0,0 +1,51 @@
+"""Inbound GitHub App ``installation`` webhook handling.
+
+This is the inbound side of bi-directional uninstall: when an account owner
+uninstalls the App on GitHub, GitHub sends an ``installation`` event with
+``action == "deleted"``. We then remove every PostHog row that referenced the
+installation so we don't keep dead tokens around.
+
+The handler never calls GitHub's DELETE endpoint — the App is already gone —
+which keeps the outbound/inbound pair loop-free.
+"""
+
+from django.http import HttpResponse
+
+import structlog
+
+from posthog.models.integration import Integration
+from posthog.models.user_integration import UserIntegration
+
+logger = structlog.get_logger(__name__)
+
+
+def handle_installation_event(payload: dict) -> HttpResponse:
+ """Process a pre-verified GitHub ``installation`` webhook event.
+
+ Called from ``posthog.urls.github_webhook`` after signature verification and
+ JSON parsing. Only ``action == "deleted"`` triggers cleanup; reversible
+ actions (suspend/unsuspend) and lifecycle noise (created, etc.) are ignored.
+ """
+ action = payload.get("action")
+ if action != "deleted":
+ logger.debug("github_installation_webhook_ignored_action", action=action)
+ return HttpResponse(status=200)
+
+ installation_id = (payload.get("installation") or {}).get("id")
+ if installation_id is None:
+ logger.warning("github_installation_webhook_missing_installation_id", action=action)
+ return HttpResponse(status=200)
+
+ installation_id = str(installation_id)
+
+ team_deleted, _ = Integration.objects.filter(kind="github", integration_id=installation_id).delete()
+ user_deleted, _ = UserIntegration.objects.filter(kind="github", integration_id=installation_id).delete()
+
+ logger.info(
+ "github_installation_webhook_uninstalled",
+ installation_id=installation_id,
+ team_integrations_deleted=team_deleted,
+ user_integrations_deleted=user_deleted,
+ )
+
+ return HttpResponse(status=200)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index d1d9f0acf6b9..2efaa9fe579a 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -64,6 +64,7 @@ from posthog.models.integration import (
TwilioIntegration,
defer_repository_cache_fields,
)
+from posthog.models.user_integration import UserIntegration
from posthog.permissions import (
AccessControlPermission,
APIScopePermission,
@@ -644,6 +645,27 @@ class IntegrationViewSet(
except Exception as e:
capture_exception(e)
+ if instance.kind == "github" and instance.integration_id:
+ # Team integrations own the installation; personal ones are subordinate. When the
+ # last team integration for an installation is removed, tear it down everywhere:
+ # uninstall the App on GitHub and delete the now-orphaned personal integrations.
+ # Other teams still sharing the same GitHub account keep it installed.
+ is_last_team_reference = (
+ not Integration.objects.filter(kind="github", integration_id=instance.integration_id)
+ .exclude(id=instance.id)
+ .exists()
+ )
+ if is_last_team_reference:
+ try:
+ GitHubIntegration.uninstall_app_installation(instance.integration_id)
+ except Exception as e:
+ capture_exception(e)
+ # Separate try so a DB error deleting personal rows isn't masked by the GitHub call.
+ try:
+ UserIntegration.objects.filter(kind="github", integration_id=instance.integration_id).delete()
+ except Exception as e:
+ capture_exception(e)
+
super().perform_destroy(instance)
@action(methods=["GET"], detail=False)
diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.py
new file mode 100644
index 000000000000..30214ea5abdb
--- /dev/null
+++ b/posthog/api/test/test_github_installation_webhook.py
@@ -0,0 +1,197 @@
+import hmac
+import json
+import hashlib
+
+from unittest.mock import MagicMock, patch
+
+from django.test import TestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework.test import APIClient
+
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+
+def _signature(payload: bytes, secret: str) -> str:
+ return "sha256=" + hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
+
+
+class TestGitHubInstallationReferenceHelpers(TestCase):
+ def setUp(self):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="helper-1")
+
+ def _team_integration(self, installation_id: str = "12345") -> Integration:
+ return Integration.objects.create(
+ team=self.team, kind="github", integration_id=installation_id, config={}, sensitive_config={}
+ )
+
+ def _user_integration(self, installation_id: str = "12345") -> UserIntegration:
+ return UserIntegration.objects.create(
+ user=self.user, kind="github", integration_id=installation_id, config={}, sensitive_config={}
+ )
+
+ def test_reference_count_zero_when_none(self):
+ self.assertEqual(GitHubIntegrationBase.installation_reference_count("12345"), 0)
+
+ def test_reference_count_team_only(self):
+ self._team_integration()
+ self.assertEqual(GitHubIntegrationBase.installation_reference_count("12345"), 1)
+
+ def test_reference_count_user_only(self):
+ self._user_integration()
+ self.assertEqual(GitHubIntegrationBase.installation_reference_count("12345"), 1)
+
+ def test_reference_count_across_both_tables(self):
+ self._team_integration()
+ self._user_integration()
+ self.assertEqual(GitHubIntegrationBase.installation_reference_count("12345"), 2)
+
+ def test_reference_count_respects_team_exclusion(self):
+ team_integration = self._team_integration()
+ self.assertEqual(
+ GitHubIntegrationBase.installation_reference_count(
+ "12345", exclude_team_integration_id=team_integration.id
+ ),
+ 0,
+ )
+
+ def test_reference_count_respects_user_exclusion(self):
+ user_integration = self._user_integration()
+ self.assertEqual(
+ GitHubIntegrationBase.installation_reference_count(
+ "12345", exclude_user_integration_id=user_integration.id
+ ),
+ 0,
+ )
+
+ @parameterized.expand(
+ [
+ ("removed_204", 204, True),
+ ("already_gone_404", 404, True),
+ ("unexpected_500", 500, False),
+ ]
+ )
+ @override_settings(GITHUB_APP_CLIENT_ID="cid", GITHUB_APP_PRIVATE_KEY="key")
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
+ def test_uninstall_app_installation_status_handling(self, _name, status_code, expected, mock_client_request):
+ mock_client_request.return_value = MagicMock(status_code=status_code)
+ self.assertEqual(GitHubIntegration.uninstall_app_installation("12345"), expected)
+ mock_client_request.assert_called_once_with("installations/12345", method="DELETE", timeout=10)
+
+ @override_settings(GITHUB_APP_CLIENT_ID="cid", GITHUB_APP_PRIVATE_KEY="key")
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
+ def test_uninstall_app_installation_false_when_request_raises(self, mock_client_request):
+ mock_client_request.side_effect = Exception("network error")
+ self.assertFalse(GitHubIntegration.uninstall_app_installation("12345"))
+
+ @override_settings(GITHUB_APP_CLIENT_ID="", GITHUB_APP_PRIVATE_KEY="")
+ def test_uninstall_app_installation_false_when_not_configured(self):
+ self.assertFalse(GitHubIntegration.uninstall_app_installation("12345"))
+
+ @patch("posthog.models.integration.GitHubIntegration.uninstall_app_installation")
+ def test_uninstall_if_last_reference_skips_when_references_remain(self, mock_uninstall):
+ self._team_integration()
+ self.assertFalse(GitHubIntegration.uninstall_if_last_reference("12345"))
+ mock_uninstall.assert_not_called()
+
+ @patch("posthog.models.integration.GitHubIntegration.uninstall_app_installation")
+ def test_uninstall_if_last_reference_uninstalls_when_none_remain(self, mock_uninstall):
+ mock_uninstall.return_value = True
+ self.assertTrue(GitHubIntegration.uninstall_if_last_reference("12345"))
+ mock_uninstall.assert_called_once_with("12345")
+
+
+class TestGitHubInstallationWebhook(TestCase):
+ def setUp(self):
+ self.client = APIClient()
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="webhook-1")
+ self.webhook_secret = "test-webhook-secret"
+
+ def _post(self, payload: dict, event_type: str = "installation"):
+ payload_bytes = json.dumps(payload).encode("utf-8")
+ return self.client.post(
+ "/webhooks/github/",
+ data=payload_bytes,
+ content_type="application/json",
+ headers={
+ "x-hub-signature-256": _signature(payload_bytes, self.webhook_secret),
+ "x-github-event": event_type,
+ },
+ )
+
+ def _team_integration(self, installation_id: str = "12345") -> Integration:
+ return Integration.objects.create(
+ team=self.team, kind="github", integration_id=installation_id, config={}, sensitive_config={}
+ )
+
+ def _user_integration(self, installation_id: str = "12345") -> UserIntegration:
+ return UserIntegration.objects.create(
+ user=self.user, kind="github", integration_id=installation_id, config={}, sensitive_config={}
+ )
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")
+ def test_deleted_removes_all_rows_and_does_not_call_github(self, mock_client_request, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ self._team_integration("12345")
+ self._user_integration("12345")
+
+ response = self._post({"action": "deleted", "installation": {"id": 12345}})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(Integration.objects.filter(kind="github", integration_id="12345").exists())
+ self.assertFalse(UserIntegration.objects.filter(kind="github", integration_id="12345").exists())
+ # Inbound side must never call out to GitHub (loop prevention).
+ mock_client_request.assert_not_called()
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_deleted_with_no_matching_rows_is_idempotent(self, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+
+ response = self._post({"action": "deleted", "installation": {"id": 99999}})
+
+ self.assertEqual(response.status_code, 200)
+
+ @parameterized.expand([("suspend",), ("unsuspend",)])
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_reversible_action_does_not_delete_rows(self, action, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ self._team_integration("12345")
+
+ response = self._post({"action": action, "installation": {"id": 12345}})
+
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_missing_installation_id_returns_200(self, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+
+ response = self._post({"action": "deleted"})
+
+ self.assertEqual(response.status_code, 200)
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ def test_invalid_signature_returns_403_and_keeps_rows(self, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ self._team_integration("12345")
+
+ payload_bytes = json.dumps({"action": "deleted", "installation": {"id": 12345}}).encode("utf-8")
+ response = self.client.post(
+ "/webhooks/github/",
+ data=payload_bytes,
+ content_type="application/json",
+ headers={"x-hub-signature-256": "sha256=wrong", "x-github-event": "installation"},
+ )
+
+ self.assertEqual(response.status_code, 403)
+ self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 66f4336f79ea..778394072fb9 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -36,6 +36,7 @@ from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
from posthog.models.utils import hash_key_value
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
@@ -3331,3 +3332,75 @@ class TestSlackPostHogCodeKindDeprecated:
serializer.is_valid()
assert "kind" not in serializer.errors
+
+
+class TestGitHubIntegrationUninstall:
+ @pytest.fixture(autouse=True)
+ def setup_integration(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ def _create_github_integration(self, installation_id: str = "12345") -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="github",
+ config={"installation_id": installation_id},
+ sensitive_config={"access_token": "ghs_token"},
+ integration_id=installation_id,
+ created_by=self.user,
+ )
+
+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation")
+ def test_destroy_github_uninstalls_and_cleans_up_personal_when_last_team_reference(
+ self, mock_uninstall, client: HttpClient
+ ):
+ mock_uninstall.return_value = True
+ integration = self._create_github_integration("12345")
+ personal = UserIntegration.objects.create(
+ user=self.user, kind="github", integration_id="12345", config={}, sensitive_config={}
+ )
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ mock_uninstall.assert_called_once_with("12345")
+ assert not Integration.objects.filter(id=integration.id).exists()
+ # Last team reference removed → the App is uninstalled, so personal integrations go too.
+ assert not UserIntegration.objects.filter(id=personal.id).exists()
+
+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation")
+ def test_destroy_github_skips_uninstall_when_other_team_reference_exists(self, mock_uninstall, client: HttpClient):
+ integration = self._create_github_integration("12345")
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ Integration.objects.create(
+ team=other_team, kind="github", integration_id="12345", config={}, sensitive_config={}
+ )
+ personal = UserIntegration.objects.create(
+ user=self.user, kind="github", integration_id="12345", config={}, sensitive_config={}
+ )
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ mock_uninstall.assert_not_called()
+ assert not Integration.objects.filter(id=integration.id).exists()
+ # Another team still uses the installation, so it stays installed and personal survives.
+ assert UserIntegration.objects.filter(id=personal.id).exists()
+
+ @patch(
+ "posthog.api.integration.GitHubIntegration.uninstall_app_installation",
+ side_effect=Exception("GitHub API error"),
+ )
+ def test_destroy_github_still_deletes_when_uninstall_fails(self, _mock_uninstall, client: HttpClient):
+ integration = self._create_github_integration("12345")
+
+ client.force_login(self.user)
+ response = client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not Integration.objects.filter(id=integration.id).exists()
diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.py
index 286de5c8af5d..51fc2aeb6572 100644
--- a/posthog/api/test/test_user_integration.py
+++ b/posthog/api/test/test_user_integration.py
@@ -132,6 +132,53 @@ class TestUserIntegrationEndpoints(APIBaseTest):
response = self.client.delete("/api/users/@me/integrations/github/99999/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation")
+ def test_delete_last_reference_calls_github_uninstall(self, mock_uninstall):
+ mock_uninstall.return_value = True
+ _create_user_integration(self.user, integration_id="12345")
+
+ response = self.client.delete("/api/users/@me/integrations/github/12345/")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ mock_uninstall.assert_called_once_with("12345")
+ self.assertFalse(UserIntegration.objects.filter(integration_id="12345").exists())
+
+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation")
+ def test_delete_skips_uninstall_when_team_reference_exists(self, mock_uninstall):
+ _create_user_integration(self.user, integration_id="12345")
+ Integration.objects.create(
+ team=self.team, kind="github", integration_id="12345", config={}, sensitive_config={}
+ )
+
+ response = self.client.delete("/api/users/@me/integrations/github/12345/")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ mock_uninstall.assert_not_called()
+ self.assertFalse(UserIntegration.objects.filter(user=self.user, integration_id="12345").exists())
+
+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation")
+ def test_delete_skips_uninstall_when_other_user_reference_exists(self, mock_uninstall):
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ _create_user_integration(self.user, integration_id="12345")
+ _create_user_integration(other_user, integration_id="12345")
+
+ response = self.client.delete("/api/users/@me/integrations/github/12345/")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ mock_uninstall.assert_not_called()
+
+ @patch(
+ "posthog.api.user_integration.UserGitHubIntegration.uninstall_if_last_reference",
+ side_effect=Exception("GitHub API error"),
+ )
+ def test_delete_still_returns_204_when_uninstall_fails(self, _mock_uninstall):
+ _create_user_integration(self.user, integration_id="12345")
+
+ response = self.client.delete("/api/users/@me/integrations/github/12345/")
+
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertFalse(UserIntegration.objects.filter(integration_id="12345").exists())
+
@override_settings(GITHUB_APP_CLIENT_ID="client_id")
@patch(
"posthog.api.github_callback.personal_state.get_instance_settings",
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 77310d970f5b..52511c8d354e 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -40,6 +40,7 @@ from posthog.api.integration import (
validate_github_repository_name,
)
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.exceptions_capture import capture_exception
from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integration
from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
@@ -192,6 +193,16 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
integration = UserIntegration.objects.filter(user=user, kind="github", integration_id=installation_id).first()
if integration is None:
raise exceptions.NotFound("No GitHub integration found for this installation.")
+
+ # Notify GitHub to uninstall the App, but only if no other PostHog team or user
+ # still relies on this installation (uninstalling breaks it for everyone sharing it).
+ try:
+ UserGitHubIntegration.uninstall_if_last_reference(
+ installation_id, exclude_user_integration_id=integration.id
+ )
+ except Exception as e:
+ capture_exception(e)
+
integration.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 4ca1356f30bc..495f8747be5d 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -6,6 +6,7 @@ operations that are shared between :class:`GitHubIntegration` (team-scoped) and
"""
import time
+import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
@@ -95,8 +96,13 @@ class GitHubIntegrationBase:
# --- App-level JWT authentication ---
@classmethod
- def client_request(cls, endpoint: str, method: str = "GET") -> requests.Response:
- """Make a request to the GitHub App API using a JWT."""
+ def client_request(cls, endpoint: str, method: str = "GET", timeout: float | None = 10) -> requests.Response:
+ """Make a request to the GitHub App API using a JWT.
+
+ ``timeout`` defaults to 10s so callers in web request and token-refresh paths
+ can't hang indefinitely on an unresponsive GitHub endpoint. Pass an explicit
+ value (or ``None`` to disable) when a different bound is needed.
+ """
from rest_framework.exceptions import ValidationError
github_app_client_id = settings.GITHUB_APP_CLIENT_ID
@@ -133,8 +139,103 @@ class GitHubIntegrationBase:
"Authorization": f"Bearer {jwt_token}",
"X-GitHub-Api-Version": "2022-11-28",
},
+ timeout=timeout,
)
+ # --- App installation lifecycle (uninstall) ---
+
+ @staticmethod
+ def installation_reference_count(
+ installation_id: str,
+ *,
+ exclude_team_integration_id: int | None = None,
+ exclude_user_integration_id: uuid.UUID | None = None,
+ ) -> int:
+ """Count PostHog rows that reference a GitHub App installation.
+
+ One installation can be shared by many team ``Integration`` rows and many
+ personal ``UserIntegration`` rows. Callers pass the id of the row currently
+ being deleted via the ``exclude_*`` params so it is not counted against itself.
+ """
+ # Local imports: both model modules import this module at load time.
+ from posthog.models.integration import Integration
+ from posthog.models.user_integration import UserIntegration
+
+ team_qs = Integration.objects.filter(kind="github", integration_id=installation_id)
+ if exclude_team_integration_id is not None:
+ team_qs = team_qs.exclude(id=exclude_team_integration_id)
+
+ user_qs = UserIntegration.objects.filter(kind="github", integration_id=installation_id)
+ if exclude_user_integration_id is not None:
+ user_qs = user_qs.exclude(id=exclude_user_integration_id)
+
+ return team_qs.count() + user_qs.count()
+
+ @classmethod
+ def uninstall_app_installation(cls, installation_id: str) -> bool:
+ """Tell GitHub to uninstall the App via ``DELETE /app/installations/{id}``.
+
+ Best-effort: never raises. Treats 204 (removed) and 404 (already gone) as
+ success. Returns ``False`` on any other outcome or when the App is not configured.
+ """
+ if not installation_id:
+ return False
+ if not settings.GITHUB_APP_CLIENT_ID or not settings.GITHUB_APP_PRIVATE_KEY:
+ logger.warning("GitHubIntegration: uninstall skipped, GitHub App not configured")
+ return False
+
+ try:
+ response = cls.client_request(f"installations/{installation_id}", method="DELETE", timeout=10)
+ except Exception:
+ logger.warning(
+ "GitHubIntegration: uninstall_app_installation request failed",
+ installation_id=installation_id,
+ exc_info=True,
+ )
+ return False
+
+ if response.status_code in (204, 404):
+ logger.info(
+ "GitHubIntegration: uninstalled App installation",
+ installation_id=installation_id,
+ status_code=response.status_code,
+ )
+ return True
+
+ logger.warning(
+ "GitHubIntegration: uninstall_app_installation unexpected status",
+ installation_id=installation_id,
+ status_code=response.status_code,
+ )
+ return False
+
+ @classmethod
+ def uninstall_if_last_reference(
+ cls,
+ installation_id: str,
+ *,
+ exclude_team_integration_id: int | None = None,
+ exclude_user_integration_id: uuid.UUID | None = None,
+ ) -> bool:
+ """Uninstall the App on GitHub only when no other PostHog row references it."""
+ if not installation_id:
+ return False
+
+ remaining = cls.installation_reference_count(
+ installation_id,
+ exclude_team_integration_id=exclude_team_integration_id,
+ exclude_user_integration_id=exclude_user_integration_id,
+ )
+ if remaining > 0:
+ logger.info(
+ "GitHubIntegration: skipping uninstall, other references remain",
+ installation_id=installation_id,
+ remaining=remaining,
+ )
+ return False
+
+ return cls.uninstall_app_installation(installation_id)
+
@staticmethod
def verify_user_installation_access(installation_id: str, user_access_token: str) -> bool:
"""Check that a GitHub user has access to the given App installation.
diff --git a/posthog/urls.py b/posthog/urls.py
index 68718ae0ac2b..3ed57e05cfed 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -135,6 +135,11 @@ def github_webhook(request: HttpRequest) -> HttpResponse:
return handle_pull_request_event(payload)
+ if event_type == "installation":
+ from posthog.api.github_callback.installation_events import handle_installation_event
+
+ return handle_installation_event(payload)
+
return HttpResponse(status=200)