: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): record github install requests and their approval (#84586)
Adam Bowker9197e33333e9
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex b76f61b3dd54..361db006721f 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -995,6 +995,7 @@ rules:(?x)(CommunitySkillVote|DashboardPrivilege+ |GitHubInstallRequest|PersonalAPIKey|ScoreDefinitionVersion|SignalUserAutonomyConfig@@ -1051,6 +1052,7 @@ rules:(?x)(CommunitySkillVote|DashboardPrivilege+ |GitHubInstallRequest|PersonalAPIKey|ScoreDefinitionVersion|SignalUserAutonomyConfigdiff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 1eff49bda79a..0dc96b266ea1 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4448,6 +4448,50 @@ export interface GitHubReposRefreshResponseApi {repositories: GitHubRepoApi[]}+/**+ * * `pending` - Pending+ * * `approved` - Approved+ * * `unidentified` - Unidentified+ */+export type GitHubInstallRequestItemStatusEnumApi =+ (typeof GitHubInstallRequestItemStatusEnumApi)[keyof typeof GitHubInstallRequestItemStatusEnumApi]++export const GitHubInstallRequestItemStatusEnumApi = {+ Pending: 'pending',+ Approved: 'approved',+ Unidentified: 'unidentified',+} as const++export interface GitHubInstallRequestItemApi {+ /** PostHog GitHubInstallRequest row id. */+ id: string+ /** GitHub login the install was requested under. Blank if it could not be resolved. */+ github_login: string+ /** `pending` while waiting on an org owner's approval, `approved` once the installation webhook confirms it, `unidentified` when the requesting GitHub account could not be resolved. Approval can't be detected for an unidentified request, so the user has to start the connect flow again.+ *+ * * `pending` - Pending+ * * `approved` - Approved+ * * `unidentified` - Unidentified */+ status: GitHubInstallRequestItemStatusEnumApi+ /**+ * GitHub App installation id, set once the request is approved.+ * @nullable+ */+ installation_id?: string | null+ /** When the install approval was requested. */+ requested_at: string+ /**+ * When an org owner approved the request.+ * @nullable+ */+ resolved_at?: string | null+}++export interface GitHubInstallRequestListResponseApi {+ /** The user's GitHub App install-approval requests, newest first. */+ results: GitHubInstallRequestItemApi[]+}+export interface UserGitHubPrepareCallbackRequestApi {/** GitHub App installation id being managed on github.com. */installation_id: stringdiff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex efe5cf3635cd..7079251d8f0c 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -26,6 +26,7 @@ import type {FileSystemShortcutListParams,FileSystemShortcutReorderApi,GitHubBranchesResponseApi,+ GitHubInstallRequestListResponseApi,GitHubReposRefreshResponseApi,GitHubReposResponseApi,IdentityProviderConfigApi,@@ -2619,6 +2620,28 @@ export const usersIntegrationsGithubReposRefreshCreate = async ()}+export const getUsersIntegrationsGithubInstallRequestsRetrieveUrl = (uuid: string) => {+ return `/api/users/${uuid}/integrations/github/install_requests/`+}++/**+ * Return the requesting user's GitHub App install-approval requests, newest first.+ *+ * This is the durable server-side "awaiting org owner approval" state (see+ * ``posthog.models.user_integration.GitHubInstallRequest``), distinct from the in-flight+ * connect spinner, which never touches this table.+ * @summary List the user's GitHub install-approval requests+ */+export const usersIntegrationsGithubInstallRequestsRetrieve = async (+ uuid: string,+ options?: RequestInit+): Promise<GitHubInstallRequestListResponseApi> => {+ return apiMutator<GitHubInstallRequestListResponseApi>(getUsersIntegrationsGithubInstallRequestsRetrieveUrl(uuid), {+ ...options,+ method: 'GET',+ })+}+export const getUsersIntegrationsGithubPrepareCallbackCreateUrl = (uuid: string) => {return `/api/users/${uuid}/integrations/github/prepare_callback/`}diff --git a/posthog/api/github_callback/install_requests.py b/posthog/api/github_callback/install_requests.pynew file mode 100644index 000000000000..787bb07b0c5e--- /dev/null+++ b/posthog/api/github_callback/install_requests.py@@ -0,0 +1,58 @@+"""Shared recording of a personal GitHub App install pending org-owner approval.++GitHub sends the user back with ``setup_action=request`` (no ``installation_id``) when the+account installing the App isn't an org owner. Both the personal-connect flow+(``personal_finish.finish_personal``) and the team-connect flow (``team_services.finish_team_setup``)+hit this branch, so the row-write lives here once. See ``posthog.models.user_integration.GitHubInstallRequest``+for why this needs to be durable server-side state rather than a client-held marker.+"""++import requests+import structlog++from posthog.models.integration import GitHubIntegration, GitHubUserAuthorization+from posthog.models.user import User+from posthog.models.user_integration import GitHubInstallRequest++logger = structlog.get_logger(__name__)+++def record_install_request(user: User, code: str | None, *, redirect_uri: str | None = None) -> None:+ """Upsert a ``GitHubInstallRequest`` for ``user``, resolving the requester from ``code``.++ The ``installation.created`` webhook identifies the requester by GitHub user id, so a request+ we cannot resolve an id for is recorded as ``unidentified`` instead of ``pending`` — nothing+ could ever flip it, and a client polling ``pending`` would wait forever. Never raises: the+ callback redirect must proceed either way.+ """+ authorization = _requester_from_code(user, code, redirect_uri)+ if authorization is None:+ GitHubInstallRequest.objects.get_or_create(+ user=user,+ github_user_id=None,+ status=GitHubInstallRequest.Status.UNIDENTIFIED,+ )+ return++ GitHubInstallRequest.objects.update_or_create(+ user=user,+ github_user_id=authorization.gh_id,+ status=GitHubInstallRequest.Status.PENDING,+ defaults={"github_login": authorization.gh_login},+ )+++def _requester_from_code(user: User, code: str | None, redirect_uri: str | None) -> GitHubUserAuthorization | None:+ if not code:+ logger.warning("github_install_request: no code to identify the requester with", user_id=user.id)+ return None++ try:+ authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=redirect_uri)+ except (requests.RequestException, ValueError):+ # ValueError: GitHub answered 200 with a non-JSON body (outage page, proxy+ # interstitial); the callback redirect must still proceed.+ authorization = None+ if authorization is None:+ logger.warning("github_install_request: code exchange could not identify the requester", user_id=user.id)+ return authorizationdiff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.pyindex fd47facaf382..543beaa5ac5c 100644--- a/posthog/api/github_callback/installation_events.py+++ b/posthog/api/github_callback/installation_events.py@@ -11,14 +11,20 @@ which keeps the outbound/inbound pair loop-free.Before the Integration rows are deleted, any Loop (products/tasks) referencing them isauto-paused and flagged for attention, so a disconnected integration never leaves a loopsilently pointed at a repository it can no longer reach.++``action == "created"`` is the other direction: an org owner approved a pending install+request (see ``posthog.api.github_callback.install_requests``). The payload's ``requester.id``+is who asked, so matching pending ``GitHubInstallRequest`` rows on ``github_user_id`` flip to+approved, which is how the desktop learns the wait is over without polling GitHub itself."""from django.http import HttpResponse+from django.utils import timezoneimport structlogfrom posthog.models.integration import Integration-from posthog.models.user_integration import UserIntegration+from posthog.models.user_integration import GitHubInstallRequest, UserIntegrationlogger = structlog.get_logger(__name__)@@ -27,10 +33,13 @@ 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.+ JSON parsing. ``action == "deleted"`` triggers integration cleanup; ``"created"``+ resolves matching pending install requests. Reversible actions (suspend/unsuspend)+ and other lifecycle noise are ignored."""action = payload.get("action")+ if action == "created":+ return _handle_installation_created(payload)if action != "deleted":logger.debug("github_installation_webhook_ignored_action", action=action)return HttpResponse(status=200)@@ -78,3 +87,33 @@ def _pause_loops_referencing_integrations(integrations: list[Integration], instareturnpause_loops_referencing_integrations(integrations, installation_id)+++def _handle_installation_created(payload: dict) -> HttpResponse:+ installation_id = (payload.get("installation") or {}).get("id")+ requester_id = (payload.get("requester") or {}).get("id")+ if installation_id is None or requester_id is None:+ # An owner installing for themselves has no requester, so this is the common case.+ logger.debug(+ "github_installation_webhook_created_no_requester",+ installation_id=installation_id,+ has_requester=requester_id is not None,+ )+ return HttpResponse(status=200)++ resolved_count = GitHubInstallRequest.objects.filter(+ github_user_id=requester_id, status=GitHubInstallRequest.Status.PENDING+ ).update(+ status=GitHubInstallRequest.Status.APPROVED,+ installation_id=str(installation_id),+ resolved_at=timezone.now(),+ )++ logger.info(+ "github_installation_webhook_created",+ installation_id=str(installation_id),+ requester_id=requester_id,+ resolved_count=resolved_count,+ )++ return HttpResponse(status=200)diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.pyindex 55049bac3cfd..b068e0ddad44 100644--- a/posthog/api/github_callback/personal_finish.py+++ b/posthog/api/github_callback/personal_finish.py@@ -9,6 +9,7 @@ import requestsimport structlogfrom posthog.api.github_callback import state+from posthog.api.github_callback.install_requests import record_install_requestfrom posthog.api.github_callback.types import (FinishResult,FlowKind,@@ -58,6 +59,15 @@ def finish_personal(request: HttpRequest) -> FinishResult:connect_from_value = authorize_state.connect_fromflow = authorize_state.flowinstallation_ids: list[str] = []+ redirect_uri = github_oauth_redirect_uri() if flow.is_oauth_redirect else None++ if request.GET.get("setup_action") == "request" and not request.GET.get("installation_id"):+ # Not an org owner: GitHub only requested approval instead of installing. It still+ # sends an OAuth `code` when the App asks for user authorization on install, so this+ # has to be checked before the code branches. Same code the team flow surfaces, so+ # the desktop treats both paths as one pending state.+ record_install_request(user, code, redirect_uri=redirect_uri)+ return _error("github_install_pending")if not code:# GitHub omits the OAuth `code` when the App is already installed on the@@ -107,7 +117,7 @@ def finish_personal(request: HttpRequest) -> FinishResult:installation_ids = [installation_id]if flow.is_oauth_redirect:- authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=github_oauth_redirect_uri())+ authorization = GitHubIntegration.github_user_from_code(code, redirect_uri=redirect_uri)else:authorization = GitHubIntegration.github_user_from_code(code)if authorization is None:diff --git a/posthog/api/github_callback/state.py b/posthog/api/github_callback/state.pyindex 07ca40eb5c53..10995f90f24a 100644--- a/posthog/api/github_callback/state.py+++ b/posthog/api/github_callback/state.py@@ -113,6 +113,25 @@ def resolve_github_setup_callback_context(return team_id, next_url+def callback_authorize_state(user_id: int, state_raw: str | None) -> GitHubAuthorizeState | None:+ """The authorize state a callback belongs to, or ``None`` when it carries none for this user.++ Resolves the token from the ``state`` query param first, then the user's pending record, the+ same way ``views._parse_callback`` routes a callback. Read-only, unlike+ ``consume_github_authorize_state``: callers further down the callback still need the state.++ Any logged-in user can be sent to the callback URL cross-site, so this is what separates a+ callback the user started from one an attacker handed them.+ """+ token, _ = parse_github_authorize_state_param(state_raw)+ if token is None:+ pending_token = cache.get(unified_authorize_pending_cache_key(user_id))+ token = str(pending_token) if pending_token is not None else None+ if not token:+ return None+ return load_authorize_state(token, user_id=user_id)++def has_pending_personal_setup_update(user: User, installation_id: str | None) -> bool:pending_token = cache.get(unified_authorize_pending_cache_key(user.id))if pending_token is None:diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.pyindex 032db0c25e99..460ec09de697 100644--- a/posthog/api/github_callback/team_services.py+++ b/posthog/api/github_callback/team_services.py@@ -17,6 +17,7 @@ from posthog.api.github_callback import (redirects,state as github_callback_state,)+from posthog.api.github_callback.install_requests import record_install_requestfrom posthog.api.github_callback.personal_state import (list_user_github_app_installations,personal_github_login,@@ -709,6 +710,7 @@ def finish_team_setup(http_request) -> FinishResult:user = cast(User, http_request.user)installation_id = http_request.GET.get("installation_id")setup_action = http_request.GET.get("setup_action") or ""+ code = http_request.GET.get("code")team_id, next_url = github_callback_state.resolve_github_setup_callback_context(user, state_raw)if github_error := http_request.GET.get("error"):@@ -728,6 +730,12 @@ def finish_team_setup(http_request) -> FinishResult:if not installation_id:_report_install_pending(user, team_id, setup_action)+ # An abandoned install lands here too, as does a bare cross-site `?setup_action=request`+ # link, since this is also where callbacks with no valid state fall through. No webhook can+ # ever resolve either, so a durable row needs both a real request and this user's own state.+ authorize_state = github_callback_state.callback_authorize_state(user.id, state_raw)+ if setup_action == "request" and authorize_state is not None:+ record_install_request(user, code)return FinishResult(redirect_kind="team_setup",next_url=next_url,diff --git a/posthog/api/github_callback/views.py b/posthog/api/github_callback/views.pyindex bcfab9bb220c..3c214e096e83 100644--- a/posthog/api/github_callback/views.py+++ b/posthog/api/github_callback/views.py@@ -1,6 +1,5 @@from typing import Literal, cast-from django.core.cache import cachefrom django.http import HttpRequest, HttpResponseRedirectfrom django.views.decorators.http import require_http_methods@@ -26,19 +25,10 @@ def _parse_callback(request: HttpRequest, entry: Literal["setup_url", "oauth_red)user = cast(User, request.user)- token: str | None = None- if state_raw:- token, _ = state.parse_github_authorize_state_param(state_raw)- if token is None:- pending_token = cache.get(state.unified_authorize_pending_cache_key(user.id))- if pending_token is not None:- token = str(pending_token)-- if token:- ctx.authorize_state = state.load_authorize_state(token, user_id=user.id)- if ctx.authorize_state is not None:- ctx.flow = ctx.authorize_state.flow- return ctx+ ctx.authorize_state = state.callback_authorize_state(user.id, state_raw)+ if ctx.authorize_state is not None:+ ctx.flow = ctx.authorize_state.flow+ return ctxif entry == "setup_url" and is_personal_github_setup_state(state_raw):ctx.flow = FlowKind.PERSONAL_INSTALLdiff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.pyindex 9ac506e4a7af..c36c079ffdef 100644--- a/posthog/api/test/test_github_installation_webhook.py+++ b/posthog/api/test/test_github_installation_webhook.py@@ -14,7 +14,7 @@ from posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from posthog.models.user_integration import UserIntegration+from posthog.models.user_integration import GitHubInstallRequest, UserIntegrationdef _signature(payload: bytes, secret: str) -> str:@@ -180,6 +180,60 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(response.status_code, 200)+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ def test_created_approves_the_requesters_pending_request_by_github_user_id(self, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ other_user = User.objects.create(email="[email protected]", distinct_id="other-requester-1")+ # Stale login on the row: a GitHub login can be renamed while the request waits, so+ # approval has to follow the immutable user id.+ matching = GitHubInstallRequest.objects.create(+ user=self.user,+ github_user_id=4242,+ github_login="octocat",+ status=GitHubInstallRequest.Status.PENDING,+ )+ someone_else = GitHubInstallRequest.objects.create(+ user=other_user,+ github_user_id=9999,+ github_login="someone-else",+ status=GitHubInstallRequest.Status.PENDING,+ )++ response = self._post(+ {+ "action": "created",+ "installation": {"id": 55555},+ "requester": {"id": 4242, "login": "octocat-renamed"},+ }+ )++ self.assertEqual(response.status_code, 200)+ matching.refresh_from_db()+ self.assertEqual(matching.status, GitHubInstallRequest.Status.APPROVED)+ self.assertEqual(matching.installation_id, "55555")+ self.assertIsNotNone(matching.resolved_at)++ someone_else.refresh_from_db()+ self.assertEqual(someone_else.status, GitHubInstallRequest.Status.PENDING)+ self.assertIsNone(someone_else.installation_id)++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ def test_created_without_a_requester_is_a_noop(self, mock_get_secret):+ # An owner installing for themselves sends no requester, and must not sweep up pending rows.+ mock_get_secret.return_value = self.webhook_secret+ pending = GitHubInstallRequest.objects.create(+ user=self.user,+ github_user_id=4242,+ github_login="octocat",+ status=GitHubInstallRequest.Status.PENDING,+ )++ response = self._post({"action": "created", "installation": {"id": 55555}})++ self.assertEqual(response.status_code, 200)+ pending.refresh_from_db()+ self.assertEqual(pending.status, GitHubInstallRequest.Status.PENDING)+@patch("products.tasks.backend.facade.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_secretdiff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex bf936ec33481..70345c03a249 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -55,7 +55,7 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import User-from posthog.models.user_integration import UserIntegration+from posthog.models.user_integration import GitHubInstallRequest, UserIntegrationfrom posthog.models.utils import hash_key_valuefrom posthog.rate_limit import GitHubRepositoryRefreshThrottle@@ -2724,19 +2724,77 @@ class TestGitHubTeamIntegrationComplete:assert response.status_code == status.HTTP_302_FOUNDassert "github_install_pending=1" in response["Location"]+ @patch("posthog.api.github_callback.install_requests.GitHubIntegration.github_user_from_code")+ def test_missing_installation_id_records_install_request(self, mock_from_code, client: HttpClient):+ # Team-flow counterpart of the personal flow's pending-approval recording+ # (test_user_integration.py): same durable GitHubInstallRequest row, reached from the+ # team-connect entry point instead of the personal one.+ client.force_login(self.user)+ mock_from_code.return_value = self._github_user_authorization()+ state_token = "pending-token-with-code"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state_token,+ flow=FlowKind.TEAM_INSTALL,+ user_id=self.user.id,+ team_id=self.team.pk,+ next_url=f"/project/{self.team.pk}/integrations/github",+ ),+ )++ response = client.get(+ "/integrations/github/callback/",+ {"setup_action": "request", "code": "gh-code", "state": urlencode({"token": state_token})},+ )++ assert response.status_code == status.HTTP_302_FOUND+ assert "github_install_pending=1" in response["Location"]+ install_request = GitHubInstallRequest.objects.get(user=self.user)+ assert install_request.github_user_id == 42+ assert install_request.github_login == "testuser"+ assert install_request.status == GitHubInstallRequest.Status.PENDING++ def test_abandoned_install_records_no_install_request(self, client: HttpClient):+ # Backing out of the install screen (no setup_action=request) reaches the same+ # missing-installation_id branch, but must not leave a durable pending row: nothing+ # would ever clear it, so the client would poll a wait that never started.+ client.force_login(self.user)+ state_token = "abandoned-token"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state_token,+ flow=FlowKind.TEAM_INSTALL,+ user_id=self.user.id,+ team_id=self.team.pk,+ next_url=f"/project/{self.team.pk}/integrations/github",+ ),+ )++ response = client.get(+ "/integrations/github/callback/",+ {"setup_action": "", "state": urlencode({"token": state_token})},+ )++ assert response.status_code == status.HTTP_302_FOUND+ assert not GitHubInstallRequest.objects.filter(user=self.user).exists()++ @patch("posthog.api.github_callback.install_requests.GitHubIntegration.github_user_from_code")@patch("posthog.api.github_callback.team_services.report_user_action")- def test_pending_without_callback_state_is_not_reported(self, mock_report):- # No stored authorize state: anyone logged in can hit this URL directly. It still redirects,- # but recording it would let a hand-typed URL inflate the approval-request metric, and would- # attribute it to whichever project the user happens to have open.+ def test_pending_without_callback_state_is_not_reported_or_recorded(self, mock_report, mock_from_code):+ # No stored authorize state: anyone logged in can be sent to this URL cross-site. It still+ # redirects, but recording it would let a hand-typed URL inflate the approval-request metric+ # and attribute it to whichever project the user happens to have open. A durable row is worse+ # still: with an attacker's OAuth code in the link it would be keyed to their GitHub account.+ mock_from_code.return_value = self._github_user_authorization()client = HttpClient()client.force_login(self.user)- response = client.get("/integrations/github/callback/", {"setup_action": "request"})+ response = client.get("/integrations/github/callback/", {"setup_action": "request", "code": "gh-code"})assert response.status_code == status.HTTP_302_FOUNDassert "github_install_pending=1" in response["Location"]assert mock_report.call_count == 0+ assert not GitHubInstallRequest.objects.filter(user=self.user).exists()@parameterized.expand([diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex 72163a71f8c7..3d67f9121167 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -19,6 +19,7 @@ from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeStatefrom posthog.models import OrganizationMembership, Userfrom posthog.models.integration import GitHubInstallationAccess, GitHubUserAuthorization, Integrationfrom posthog.models.user_integration import (+ GitHubInstallRequest,ReauthorizationRequired,UserGitHubIntegration,UserIntegration,@@ -127,6 +128,36 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(len(response.json()["results"]), 0)+ def test_github_install_requests_returns_only_own_rows_newest_first(self):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ GitHubInstallRequest.objects.create(+ user=self.user, github_user_id=4242, github_login="octocat", status=GitHubInstallRequest.Status.PENDING+ )+ approved = GitHubInstallRequest.objects.create(+ user=self.user,+ github_user_id=4242,+ github_login="octocat-org",+ status=GitHubInstallRequest.Status.APPROVED,+ installation_id="55555",+ )+ GitHubInstallRequest.objects.create(+ user=other_user,+ github_user_id=9999,+ github_login="someone-else",+ status=GitHubInstallRequest.Status.PENDING,+ )++ response = self.client.get("/api/users/@me/integrations/github/install_requests/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ results = response.json()["results"]+ self.assertEqual(len(results), 2)+ self.assertEqual(results[0]["id"], str(approved.id))+ self.assertEqual(results[0]["status"], "approved")+ self.assertEqual(results[0]["installation_id"], "55555")+ logins = {r["github_login"] for r in results}+ self.assertEqual(logins, {"octocat", "octocat-org"})+def test_delete_removes_specific_installation(self):_create_user_integration(self.user, integration_id="12345")_create_user_integration(self.user, integration_id="67890")@@ -662,6 +693,65 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(response.status_code, 302)self.assertIn("github_link_error=missing_params", response["Location"])+ @patch("posthog.api.github_callback.install_requests.GitHubIntegration.github_user_from_code")+ def test_github_link_personal_install_reports_pending_approval_when_org_owner_must_approve(self, mock_from_code):+ # Non-owner accounts come back with setup_action=request and no installation_id; the+ # OAuth code is still present because the App requests user authorization on install.+ # Recording the pending approval as a durable GitHubInstallRequest row (rather than just+ # redirecting) is what lets the desktop poll server-side state instead of holding a+ # client-side marker across app restarts.+ mock_from_code.return_value = _authorization(gh_id=4242, gh_login="octocat")+ state = "test_state_pending_approval"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state,+ flow=FlowKind.PERSONAL_INSTALL,+ user_id=self.user.id,+ connect_from="posthog_code",+ ),+ )++ response = self.client.get(+ "/complete/github-link/",+ {"state": state, "setup_action": "request", "code": "gh-code"},+ )++ self.assertEqual(response.status_code, 302)+ loc = response["Location"]+ self.assertIn("provider=github", loc)+ self.assertIn("error=github_install_pending", loc)+ install_request = GitHubInstallRequest.objects.get(user=self.user)+ self.assertEqual(install_request.github_user_id, 4242)+ self.assertEqual(install_request.github_login, "octocat")+ self.assertEqual(install_request.status, GitHubInstallRequest.Status.PENDING)++ @patch("posthog.api.github_callback.install_requests.GitHubIntegration.github_user_from_code")+ def test_github_link_personal_install_request_without_a_resolvable_requester_is_not_pending(self, mock_from_code):+ # The installation.created webhook identifies the requester by GitHub user id, so a request+ # recorded without one can never be approved. Marking it pending would leave the client+ # polling forever, so it lands as unidentified and the user restarts the flow instead.+ mock_from_code.return_value = None+ state = "test_state_pending_approval_no_identity"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state,+ flow=FlowKind.PERSONAL_INSTALL,+ user_id=self.user.id,+ connect_from="posthog_code",+ ),+ )++ response = self.client.get(+ "/complete/github-link/",+ {"state": state, "setup_action": "request", "code": "gh-code"},+ )++ self.assertEqual(response.status_code, 302)+ self.assertIn("error=github_install_pending", response["Location"])+ install_request = GitHubInstallRequest.objects.get(user=self.user)+ self.assertIsNone(install_request.github_user_id)+ self.assertEqual(install_request.status, GitHubInstallRequest.Status.UNIDENTIFIED)+@override_settings(GITHUB_APP_CLIENT_ID="client_id", SITE_URL="https://us.posthog.com")def test_github_link_personal_install_without_code_recovers_via_oauth_discover(self):# GitHub omits the OAuth code when the App is already installed, returning adiff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex 4fc9d1789a56..7ebfbe661e31 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -48,7 +48,7 @@ from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integrationfrom posthog.models.user import User-from posthog.models.user_integration import UserGitHubIntegration, UserIntegration+from posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegrationfrom posthog.permissions import APIScopePermissionfrom posthog.rate_limit import UserAuthenticationThrottlefrom posthog.user_permissions import UserPermissions@@ -130,6 +130,40 @@ class UserGitHubLinkStartResponseSerializer(serializers.Serializer):)+class GitHubInstallRequestItemSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="PostHog GitHubInstallRequest row id.")+ github_login = serializers.CharField(+ allow_blank=True,+ help_text="GitHub login the install was requested under. Blank if it could not be resolved.",+ )+ status = serializers.ChoiceField(+ choices=GitHubInstallRequest.Status.choices,+ help_text=(+ "`pending` while waiting on an org owner's approval, `approved` once the installation webhook "+ "confirms it, `unidentified` when the requesting GitHub account could not be resolved. Approval "+ "can't be detected for an unidentified request, so the user has to start the connect flow again."+ ),+ )+ installation_id = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="GitHub App installation id, set once the request is approved.",+ )+ requested_at = serializers.DateTimeField(help_text="When the install approval was requested.")+ resolved_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text="When an org owner approved the request.",+ )+++class GitHubInstallRequestListResponseSerializer(serializers.Serializer):+ results = GitHubInstallRequestItemSerializer(+ many=True,+ help_text="The user's GitHub App install-approval requests, newest first.",+ )++class UserSlackIntegrationItemSerializer(serializers.Serializer):id = serializers.UUIDField(help_text="PostHog UserIntegration row id.")kind = serializers.CharField(help_text="Integration kind; always `slack` for this API.")@@ -214,6 +248,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):"retrieve","github_repos","github_branches",+ "github_install_requests","slack_linkable",]scope_object_write_actions = [@@ -429,6 +464,33 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):return Response({"branches": branches, "default_branch": default_branch, "has_more": has_more})+ @extend_schema(+ summary="List the user's GitHub install-approval requests",+ responses={200: GitHubInstallRequestListResponseSerializer},+ )+ @action(methods=["GET"], detail=False, url_path="github/install_requests")+ def github_install_requests(self, request: Request, **_kwargs) -> Response:+ """Return the requesting user's GitHub App install-approval requests, newest first.++ This is the durable server-side "awaiting org owner approval" state (see+ ``posthog.models.user_integration.GitHubInstallRequest``), distinct from the in-flight+ connect spinner, which never touches this table.+ """+ user = self._get_user()+ install_requests = GitHubInstallRequest.objects.filter(user=user).order_by("-requested_at")+ results = [+ {+ "id": install_request.id,+ "github_login": install_request.github_login,+ "status": install_request.status,+ "installation_id": install_request.installation_id,+ "requested_at": install_request.requested_at,+ "resolved_at": install_request.resolved_at,+ }+ for install_request in install_requests+ ]+ return Response({"results": results})+@extend_schema(summary="Start GitHub personal integration linking",request=UserGitHubLinkStartRequestSerializer,diff --git a/posthog/migrations/1308_githubinstallrequest.py b/posthog/migrations/1308_githubinstallrequest.pynew file mode 100644index 000000000000..7caae612fabb--- /dev/null+++ b/posthog/migrations/1308_githubinstallrequest.py@@ -0,0 +1,68 @@+# Generated by Django 5.2.17 on 2026-08-18 15:25++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1307_remove_personlessdistinctid")]++ operations = [+ migrations.CreateModel(+ name="GitHubInstallRequest",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("github_user_id", models.BigIntegerField(blank=True, null=True)),+ ("github_login", models.CharField(blank=True, max_length=255)),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("approved", "Approved"),+ ("unidentified", "Unidentified"),+ ],+ default="pending",+ max_length=16,+ ),+ ),+ (+ "installation_id",+ models.CharField(blank=True, max_length=64, null=True),+ ),+ ("requested_at", models.DateTimeField(auto_now_add=True)),+ ("resolved_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="github_install_requests",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "posthog_github_install_request",+ "indexes": [+ models.Index(+ fields=["github_user_id", "status"],+ name="github_install_req_ghuser_idx",+ )+ ],+ },+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d3ccb35abd0a..af5a50124657 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1307_remove_personlessdistinctid+1308_githubinstallrequestdiff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex b9b2aee743ef..428e7ed78fea 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -70,7 +70,7 @@ from .global_rate_limit_threshold_config import GlobalRateLimitThresholdConfigfrom .uploaded_media import UploadedMediafrom .user import User, UserManagerfrom .user_group import UserGroup, UserGroupMembership-from .user_integration import UserIntegration+from .user_integration import GitHubInstallRequest, UserIntegrationfrom .user_push_token import UserPushTokenfrom .repo_routing_rule import RepoRoutingRulefrom .user_repo_preference import UserRepoPreference@@ -179,6 +179,7 @@ __all__ = ["UserManager","UserGroup","UserGroupMembership",+ "GitHubInstallRequest","UserIntegration","UserPushToken","DataWarehouseTable",diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex f2c4ff39a9cd..3bd880eae8bc 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -97,6 +97,51 @@ class UserIntegration(UUIDModel):]+class GitHubInstallRequest(UUIDModel):+ """Durable record of a personal GitHub App install that an org owner must approve.++ GitHub sends the user back with ``setup_action=request`` (no ``installation_id``) when the+ installing account isn't an org owner. That wait can take hours to days, so unlike the+ in-flight connect state machine it needs server-side state the desktop can poll instead of a+ client-held marker: a row here is the fact of "approval requested"; the+ ``installation.created`` webhook (see ``posthog.api.github_callback.installation_events``)+ flips it to ``approved`` once an owner acts. User-scoped like ``UserIntegration``, not+ team-scoped, because the request predates any team's Integration row.++ ``github_user_id`` is what the webhook matches on, because a pending row can outlive the login+ it was created under: GitHub logins are renameable and a freed one can be claimed by someone+ else. ``github_login`` is display data only. A request whose requester we could not resolve at+ all is ``unidentified`` rather than ``pending``, since no webhook can ever match it.+ """++ class Status(models.TextChoices):+ PENDING = "pending"+ APPROVED = "approved"+ UNIDENTIFIED = "unidentified"++ # db_constraint=False: posthog_user is a hot table, see safe-django-migrations.md.+ user = models.ForeignKey(+ "posthog.User",+ on_delete=models.CASCADE,+ db_constraint=False,+ related_name="github_install_requests",+ )+ github_user_id = models.BigIntegerField(null=True, blank=True)+ github_login = models.CharField(max_length=255, blank=True)+ status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)+ installation_id = models.CharField(max_length=64, null=True, blank=True)+ requested_at = models.DateTimeField(auto_now_add=True)+ resolved_at = models.DateTimeField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_github_install_request"+ indexes = [+ models.Index(fields=["github_user_id", "status"], name="github_install_req_ghuser_idx"),+ ]++class ReauthorizationRequired(Exception):"""The stored GitHub tokens cannot produce a usable access token; user must re-authorize."""diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yamlindex 3a580f2435e4..bc067ba58550 100644--- a/services/mcp/definitions/core.yaml+++ b/services/mcp/definitions/core.yaml@@ -524,6 +524,9 @@ tools:users-integrations-github-destroy:operation: users_integrations_github_destroyenabled: false+ users-integrations-github-install-requests-retrieve:+ operation: users_integrations_github_install_requests_retrieve+ enabled: falseusers-integrations-github-prepare-callback-create:operation: users_integrations_github_prepare_callback_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cc1a73fd7f07..2142a58ad2fe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38474,6 +38474,50 @@ export namespace Schemas {has_more: boolean;}+ /**+ * * `pending` - Pending+ * * `approved` - Approved+ * * `unidentified` - Unidentified+ */+ export type GitHubInstallRequestItemStatusEnum = typeof GitHubInstallRequestItemStatusEnum[keyof typeof GitHubInstallRequestItemStatusEnum];+++ export const GitHubInstallRequestItemStatusEnum = {+ Pending: 'pending',+ Approved: 'approved',+ Unidentified: 'unidentified',+ } as const;++ export interface GitHubInstallRequestItem {+ /** PostHog GitHubInstallRequest row id. */+ id: string;+ /** GitHub login the install was requested under. Blank if it could not be resolved. */+ github_login: string;+ /** `pending` while waiting on an org owner's approval, `approved` once the installation webhook confirms it, `unidentified` when the requesting GitHub account could not be resolved. Approval can't be detected for an unidentified request, so the user has to start the connect flow again.+ *+ * * `pending` - Pending+ * * `approved` - Approved+ * * `unidentified` - Unidentified */+ status: GitHubInstallRequestItemStatusEnum;+ /**+ * GitHub App installation id, set once the request is approved.+ * @nullable+ */+ installation_id?: string | null;+ /** When the install approval was requested. */+ requested_at: string;+ /**+ * When an org owner approved the request.+ * @nullable+ */+ resolved_at?: string | null;+ }++ export interface GitHubInstallRequestListResponse {+ /** The user's GitHub App install-approval requests, newest first. */+ results: GitHubInstallRequestItem[];+ }+export interface GitHubLinkExistingRequest {/*** Sibling team in the same organization whose GitHub installation should be reused.