: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): refresh github suggestions and preserve audit evidence (#104513)
Georgiy Tarasovb8f982910b6d
diff --git a/ee/api/agentic_provisioning/github_grants.py b/ee/api/agentic_provisioning/github_grants.pyindex 0117ca5e6f1f..0013324d23d3 100644--- a/ee/api/agentic_provisioning/github_grants.py+++ b/ee/api/agentic_provisioning/github_grants.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport jsonimport secrets+import dataclassesfrom dataclasses import dataclass, fieldfrom typing import Any@@ -65,9 +66,11 @@ class GitHubGrant:access_token_expires_in: int | Nonerefresh_token_expires_in: int | Nonecreated_at: str+ # None only for grants cached before the field existed.+ identity_verified_at: int | None = Nonedef to_authorization(self) -> GitHubUserAuthorization:- return GitHubUserAuthorization(+ authorization = GitHubUserAuthorization(gh_id=self.gh_id,gh_login=self.gh_login,access_token=self.access_token,@@ -75,6 +78,9 @@ class GitHubGrant:access_token_expires_in=self.access_token_expires_in,refresh_token_expires_in=self.refresh_token_expires_in,)+ if self.identity_verified_at is None:+ return authorization+ return dataclasses.replace(authorization, identity_verified_at=self.identity_verified_at)def cache_payload(self) -> dict[str, Any]:return {@@ -87,6 +93,7 @@ class GitHubGrant:"access_token_expires_in": self.access_token_expires_in,"refresh_token_expires_in": self.refresh_token_expires_in,"created_at": self.created_at,+ "identity_verified_at": self.identity_verified_at,}@classmethod@@ -102,6 +109,7 @@ class GitHubGrant:access_token_expires_in=payload.get("access_token_expires_in"),refresh_token_expires_in=payload.get("refresh_token_expires_in"),created_at=payload["created_at"],+ identity_verified_at=payload.get("identity_verified_at"),)@@ -117,6 +125,7 @@ def create_grant(partner: OAuthApplication, authorization: GitHubUserAuthorizatiaccess_token_expires_in=authorization.access_token_expires_in,refresh_token_expires_in=authorization.refresh_token_expires_in,created_at=timezone.now().isoformat(),+ identity_verified_at=authorization.identity_verified_at,)cache.set(f"{GITHUB_GRANT_CACHE_PREFIX}{grant.grant_id}",diff --git a/ee/api/agentic_provisioning/test/test_github_grants.py b/ee/api/agentic_provisioning/test/test_github_grants.pyindex b6e4cefe6c47..a80a9902aa41 100644--- a/ee/api/agentic_provisioning/test/test_github_grants.py+++ b/ee/api/agentic_provisioning/test/test_github_grants.py@@ -1,3 +1,5 @@+import dataclasses+from unittest.mock import MagicMock, patchfrom django.core.cache import cache@@ -90,7 +92,7 @@ class TestGitHubGrants(ProvisioningTestBase):with (patch("ee.api.agentic_provisioning.views.github_grants.GitHubIntegration.github_user_from_code",- return_value=AUTHORIZATION,+ return_value=dataclasses.replace(AUTHORIZATION, identity_verified_at=1_700_000_000),) as mock_exchange,patch("ee.api.agentic_provisioning.github_grants.github_request", return_value=EMAILS_RESPONSE),):@@ -114,6 +116,7 @@ class TestGitHubGrants(ProvisioningTestBase):assert grant is not Noneassert grant.access_token == ACCESS_TOKENassert grant.email == "[email protected]"+ assert grant.to_authorization().identity_verified_at == 1_700_000_000@parameterized.expand([diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 89994b0fa153..5fcaa4e49047 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1328,6 +1328,22 @@ snapshots:hash: v1.k794b7964.569cfd0e730a83543813b1eafb440926aa4609bb0152eb181dc59fee1ea5dfd3.45sa4VsBQ3Ff-WeTTpiTNY4rF2ENc8DS-adghxL68Bwcomponents-insighttooltip--math-tags-single-series--light:hash: v1.k794b7964.7b71a93bc37c46ac51efcb9f53cd989daade7490f30ebde795b0b918e59d25e2.Y0ThCO5-ePDvaf3o5da7LvN_1quQ_FXQEnTSm5TCvog+ components-integrations-github-suggestions--multiple--dark:+ hash: v1.k794b7964.fdd0edd3da576b292f0626930557bc4b395e257caafc9fa28111faf2e580979a.otTmyNsIxocnVyu5Vd5sZlxcYcGAgbzShAidGTDTzEk+ components-integrations-github-suggestions--multiple--light:+ hash: v1.k794b7964.d6c629b46cbb54eae46fbe57941e81ceebd61e004d7b10c99cb7dcef3c8d7de5.bV-SuN-48HsN6cx9NuUf-yg0Vlh3ZbrzmRe_D90D-JQ+ components-integrations-github-suggestions--narrow--dark:+ hash: v1.k794b7964.42879a3b4aaad2abb2d325dc06c820207384015ef8c84415965860e5b3f02e56.uy4rMiXR74BPJeUoyW0E93-bMP4MKbsHZ1Zd-t3cjlA+ components-integrations-github-suggestions--narrow--light:+ hash: v1.k794b7964.b4bef7501ef61f9e455b9f125f15510882a96799bd53a04e8b0a22ffaabadd9a.fYE1eJNI_PQw7cGfybxYS7AR4rXZMXOt3fCaq-gU5cs+ components-integrations-github-suggestions--personal-unavailable--dark:+ hash: v1.k794b7964.fe0bf2106dc915d46dd58774c57f73167084a622f444c82db7fda3487bbbfd14.7EZkCpDNSYXi1Sn5peWNbUw6P87pb_1ZoIdnDvRKDt4+ components-integrations-github-suggestions--personal-unavailable--light:+ hash: v1.k794b7964.e8ab4bc0f40d17c3c6b986e317b8583474ba9835e69a9fd69e895a9021ddedce.oTEKdkZmvyrdBDvN3yxfp1aJAUmSYoLcqincwrKuE7g+ components-integrations-github-suggestions--single--dark:+ hash: v1.k794b7964.bbc1214c9b3a2835f137dcb6951a408a9bfbb0bdb365713b6c73aa14322b402a.sQJuuLerKZpVLWOAzo52eVwc-A3wlgdvCstA-92E2TA+ components-integrations-github-suggestions--single--light:+ hash: v1.k794b7964.af98410b1acf3a20e61c3c7ac1d366cefd9ae7c5b2f930212a9cd2cda7c49310.40gZvIrwfFuoTOVOZacm1NnU4aXCMOGAraRvx7TYH5Ecomponents-integrations-githubreposummary--all-repositories--dark:hash: v1.k794b7964.ad87b61d12c16bbe594c68eede01d3e9e279a7dfd08bcce06c734ea7ade4c9cb.iOP_47ViGava56NrIa0Sn2daPDaCDikXL9e_fXtcKgocomponents-integrations-githubreposummary--all-repositories--light:@@ -9309,9 +9325,9 @@ snapshots:scenes-app-inbox-scene--self-driving-verdict-pending--light:hash: v1.k794b7964.96cdbec6c78e8daedb06be4a0134093efcd5838af69e6e7d1722a3892cf561b5.iJ2K0zNhOVgGAPY6JvduyhDBODMwk-CN7_mAdB8scOgscenes-app-inbox-scene--settings--dark:- hash: v1.k794b7964.45842d1bb16d1d971632b9097e17ec9cbac22946ee46508599f97685857af3fb.mOuqWtWVnLdPDLGecC3GxeNk6pnmMXr4UvaSjUIg8VI+ hash: v1.k794b7964.bc6182512f1a869ea994e7cef98731a96730d9bae156279e154ee73404674b1d.2RklYWoL5d3jqDKf1UHoQHO9dRxrTKeU8qZHAS7HE2Mscenes-app-inbox-scene--settings--light:- hash: v1.k794b7964.bd41ab17202dcbca6ddff01d47dad365c8cb22ac6ef8989a9afebdbf5b76080c.KAmw2VUnqagBz_eOS7fVwAAO0Cz-Gvl0Jzb8R6FkZ0k+ hash: v1.k794b7964.960cbf32355909e10651cc28d7e7f9f5ebc9095bd30f040a31e6c922399ba415.eDxCx3M_sNwJKuBuo5GBxSZH3iCojFsRRb9Hjcmlljsscenes-app-inbox-scene--triage--dark:hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eoscenes-app-inbox-scene--triage--light:diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.tsindex a5034014b474..7bff2ff2809e 100644--- a/frontend/src/lib/integrations/integrationsLogic.test.ts+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts@@ -1,16 +1,24 @@import { MOCK_TEAM_ID } from 'lib/api.mock'+import { waitFor } from '@testing-library/react'import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { LemonDialog, lemonToast } from '@posthog/lemon-ui'import apiReal, { ApiError } from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { IntegrationKind, IntegrationType } from '~/types'+import * as integrationsApi from 'products/integrations/frontend/generated/api'+import type {+ GitHubAvailableInstallationsResponseApi,+ IntegrationConfigApi,+} from 'products/integrations/frontend/generated/api.schemas'+import { integrationsLogic } from './integrationsLogic'const githubIntegration = (overrides: Partial<IntegrationType> = {}): IntegrationType =>@@ -39,6 +47,11 @@ describe('integrationsLogic', () => {// Handlers reset after every test, so register them per test.useMocks({get: {+ '/api/projects/:team_id/integrations/github/available_installations/': {+ installations: [],+ personal_github_connected: false,+ personal_discovery_status: 'not_connected',+ },'/api/projects/:team_id/integrations/': () => [200, { results: integrationsPayload }],'/api/projects/:team_id/integrations/:id/github_repos/': ({ params, request }) => {const offset = new URL(request.url).searchParams.get('offset') ?? '0'@@ -65,6 +78,140 @@ describe('integrationsLogic', () => {jest.restoreAllMocks()})+ describe('GitHub discovery freshness', () => {+ const discovery = (id: string): GitHubAvailableInstallationsResponseApi => ({+ discovery_id: id,+ discovered_at: new Date().toISOString(),+ personal_github_connected: true,+ personal_github_login: 'synthetic-reader',+ personal_discovery_status: 'ok',+ installations: [+ {+ installation_id: id,+ account_name: 'synthetic-owner',+ account_type: 'Organization',+ source_team_id: null,+ source_team_name: null,+ },+ ],+ })++ it.each(['invalidate', 'newer response', 'project switch'])(+ 'rejects a delayed response after %s',+ async (change) => {+ let resolve!: (response: GitHubAvailableInstallationsResponseApi) => void+ const pending = new Promise<GitHubAvailableInstallationsResponseApi>((done) => {+ resolve = done+ })+ const request = jest+ .spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')+ .mockReturnValueOnce(pending)+ logic.actions.loadGithubAvailableInstallations()+ if (change === 'invalidate') {+ logic.actions.invalidateGithubSuggestions()+ } else if (change === 'newer response') {+ request.mockResolvedValueOnce(discovery('new'))+ logic.actions.loadGithubAvailableInstallations()+ await waitFor(() =>+ expect(logic.values.githubAvailableInstallations?.[0].installation_id).toBe('new')+ )+ } else {+ teamLogic.actions.loadCurrentTeamSuccess({+ ...teamLogic.values.currentTeam!,+ id: 999,+ project_id: 999,+ })+ }+ resolve(discovery('old'))+ await pending+ await new Promise<void>((done) => queueMicrotask(done))+ expect(logic.values.githubAvailableInstallations?.[0]?.installation_id ?? null).toBe(+ change === 'newer response' ? 'new' : null+ )+ }+ )++ it('hides invalidated suggestions and exposes refresh failure for retry', async () => {+ const request = jest+ .spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')+ .mockResolvedValueOnce(discovery('old'))+ logic.actions.loadGithubAvailableInstallations()+ await waitFor(() => expect(logic.values.githubAvailableInstallations).toHaveLength(1))+ request.mockRejectedValueOnce(new Error('synthetic failure'))+ logic.actions.loadGithubAvailableInstallations()+ expect(logic.values.githubAvailableInstallations).toBeNull()+ await waitFor(() => expect(logic.values.githubDiscoveryFailed).toBe(true))+ expect(logic.values.githubAvailableInstallationsResponseLoading).toBe(false)+ })++ it('refreshes suggestions when polling sees changed GitHub connections', async () => {+ const request = jest+ .spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')+ .mockResolvedValue(discovery('fresh'))+ logic.actions.subscribeGithubSuggestions()+ integrationsPayload = [githubIntegration()]+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([+ 'loadIntegrationsSuccess',+ 'loadGithubAvailableInstallations',+ ])+ expect(request).toHaveBeenCalled()+ logic.actions.unsubscribeGithubSuggestions()+ })++ it('discovers once when switching projects with a mounted GitHub surface', async () => {+ const request = jest+ .spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')+ .mockResolvedValue(discovery('fresh'))+ logic.actions.subscribeGithubSuggestions()+ await expectLogic(logic).toFinishAllListeners()+ request.mockClear()+ integrationsPayload = [githubIntegration()]++ await expectLogic(logic, () =>+ teamLogic.actions.loadCurrentTeamSuccess({ ...teamLogic.values.currentTeam!, id: 999, project_id: 999 })+ ).toFinishAllListeners()++ expect(request).toHaveBeenCalledTimes(1)+ expect(request).toHaveBeenCalledWith('999')+ logic.actions.unsubscribeGithubSuggestions()+ })++ it('keeps loaded integrations when the same project refreshes', async () => {+ integrationsPayload = [githubIntegration()]+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toFinishAllListeners()++ teamLogic.actions.loadCurrentTeamSuccess({ ...teamLogic.values.currentTeam! })++ expect(logic.values.integrations).toHaveLength(1)+ })++ it.each([false, true])(+ 'discards a delayed link completion after switching projects, failure=%s',+ async (fails) => {+ let finish!: () => void+ const pending = new Promise<IntegrationConfigApi>((resolve, reject) => {+ finish = () =>+ fails ? reject(new Error('synthetic failure')) : resolve({ id: 42 } as IntegrationConfigApi)+ })+ jest.spyOn(integrationsApi, 'integrationsGithubLinkExistingCreate').mockReturnValue(pending)+ const toast = jest.spyOn(lemonToast, 'success')+ const reload = jest.spyOn(logic.actions, 'loadIntegrations')+ logic.actions.linkExistingGithubInstallation('12345')+ teamLogic.actions.loadCurrentTeamSuccess({ ...teamLogic.values.currentTeam!, id: 999, project_id: 999 })+ await expectLogic(logic).toDispatchActions(['loadIntegrationsSuccess'])+ reload.mockClear()++ finish()+ await expectLogic(logic).toFinishAllListeners()++ expect(toast).not.toHaveBeenCalled()+ expect(reload).not.toHaveBeenCalled()+ expect(logic.values.linkedGithubInstallation).toBeNull()+ expect(logic.values.linkedGithubInstallationLoading).toBe(false)+ }+ )+ })+describe('GitHub repositories', () => {it.each([['all', 1],@@ -138,6 +285,39 @@ describe('integrationsLogic', () => {expect(dialogProps.description).toBe(description)})+ it.each([false, true])('refreshes suggestions after disconnect with failure=%s', async (fails) => {+ integrationsPayload = [githubIntegration()]+ await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([+ 'loadIntegrationsSuccess',+ ])+ const discoveryRequest = jest+ .spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')+ .mockResolvedValue({+ installations: [],+ personal_github_connected: false,+ personal_discovery_status: 'not_connected',+ personal_github_login: null,+ discovery_id: 'fresh',+ discovered_at: new Date().toISOString(),+ })+ let finish!: () => void+ const deletion = new Promise<IntegrationType>((resolve, reject) => {+ finish = () => (fails ? reject(new ApiError('synthetic failure', 500)) : resolve(githubIntegration()))+ })+ jest.spyOn(apiReal.integrations, 'delete').mockReturnValue(deletion)+ jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast')+ logic.actions.deleteIntegration(42)+ const click = dialogProps.primaryButton.onClick()+ expect(logic.values.githubAvailableInstallations).toBeNull()+ expect(logic.values.githubAvailableInstallationsResponseLoading).toBe(true)+ logic.actions.loadGithubAvailableInstallations()+ expect(discoveryRequest).not.toHaveBeenCalled()+ finish()+ await click+ await waitFor(() => expect(discoveryRequest).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(logic.values.githubAvailableInstallationsResponseLoading).toBe(false))+ })+it('treats a 404 on delete as already disconnected and reloads', async () => {integrationsPayload = [githubIntegration()]await expectLogic(logic, () => logic.actions.loadIntegrations()).toDispatchActions([@@ -160,6 +340,7 @@ describe('integrationsLogic', () => {describe('polling', () => {it('polls integrations only while at least one surface is subscribed', async () => {jest.useFakeTimers()+ const discoveryRequest = jest.spyOn(integrationsApi, 'integrationsGithubAvailableInstallationsRetrieve')logic.actions.startPolling()logic.actions.startPolling()@@ -173,6 +354,7 @@ describe('integrationsLogic', () => {expect(logic.cache.disposables.registry.has('poll')).toBe(true)logic.actions.stopPolling()expect(logic.cache.disposables.registry.has('poll')).toBe(false)+ expect(discoveryRequest).not.toHaveBeenCalled()})})diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 25839d087965..7e746f1beeaf 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -26,6 +26,7 @@ import { EmailIntegrationDomainGroupedType, IntegrationKind, IntegrationType } fimport {integrationsGithubAvailableInstallationsRetrieve,integrationsGithubReposRetrieve,+ integrationsGithubLinkExistingCreate,integrationsList,integrationsRequestAccessCreate,} from 'products/integrations/frontend/generated/api'@@ -34,6 +35,7 @@ import type {GitHubAvailableInstallationsResponseApi,GitHubRepoApi,InstallationStatusEnumApi,+ IntegrationConfigApi,IntegrationKindEnumApi,} from 'products/integrations/frontend/generated/api.schemas'import { ChannelType } from 'products/workflows/frontend/Channels/MessageChannels'@@ -126,15 +128,20 @@ export interface integrationsLogicValues {githubAvailableInstallations: GitHubAvailableInstallationApi[] | nullgithubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | nullgithubAvailableInstallationsResponseLoading: boolean+ githubDisconnecting: boolean+ githubDiscoveryFailed: boolean+ githubDiscoveryGeneration: number+ githubDiscoveryProjectId: number | string | nullgithubIntegrations: IntegrationType[]githubPersonalConnected: boolean | nullgithubRepositories: Record<number, GitHubRepoApi[]>githubRepositoriesLoading: booleangithubRepositoriesTotal: Record<number, number>+ githubSuggestionSubscribers: numberintegrations: IntegrationType[] | nullintegrationsLoading: booleanlinearIntegrations: IntegrationType[]- linkedGithubInstallation: IntegrationType | null+ linkedGithubInstallation: IntegrationConfigApi | nulllinkedGithubInstallationLoading: booleannewIntegrationModalId: string | nullnewIntegrationModalKind: IntegrationKind | null@@ -159,6 +166,16 @@ export interface integrationsLogicActions {markTaskAsCompleted: (taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]) => {taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]} // globalSetupLogic+ loadCurrentTeamSuccess: (+ currentTeam: null | import('~/types').TeamPublicType,+ payload?: any+ ) => {+ currentTeam: null | import('~/types').TeamPublicType+ payload?: any+ } // teamLogic+ clearIntegrations: () => {+ value: true+ }closeNewIntegrationModal: () => {value: true}@@ -219,7 +236,10 @@ export interface integrationsLogicActions {| 'youtube-analytics'searchParams: any}- linkExistingGithubInstallation: (installationId?: string) => string+ invalidateGithubSuggestions: () => {+ value: true+ }+ linkExistingGithubInstallation: (installationId: string | undefined) => string | undefinedlinkExistingGithubInstallationFailure: (error: string,errorObject?: any@@ -228,11 +248,11 @@ export interface integrationsLogicActions {errorObject?: any}linkExistingGithubInstallationSuccess: (- linkedGithubInstallation: IntegrationType,- payload?: string+ linkedGithubInstallation: IntegrationConfigApi | null,+ payload?: string | undefined) => {- linkedGithubInstallation: IntegrationType- payload?: string+ linkedGithubInstallation: IntegrationConfigApi | null+ payload?: string | undefined}loadGitHubRepositories: (integrationId: number) => {integrationId: number@@ -258,22 +278,10 @@ export interface integrationsLogicActions {repositories: GitHubRepoApi[]total: number | null}- loadGithubAvailableInstallations: () => any- loadGithubAvailableInstallationsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadGithubAvailableInstallationsSuccess: (- githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi,- payload?: any- ) => {- githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi- payload?: any+ loadGithubAvailableInstallations: () => {+ value: true}- loadIntegrations: () => any+ loadIntegrations: (_?: any) => anyloadIntegrationsFailure: (error: string,errorObject?: any@@ -601,12 +609,30 @@ export interface integrationsLogicActions {setAccessRequestReason: (reason: string) => {reason: string}+ setGithubDisconnecting: (disconnecting: boolean) => {+ disconnecting: boolean+ }+ setGithubDiscovery: (+ response: GitHubAvailableInstallationsResponseApi | null,+ projectId: number | string,+ failed: boolean+ ) => {+ failed: boolean+ projectId: number | string+ response: GitHubAvailableInstallationsResponseApi | null+ }startPolling: () => {value: true}stopPolling: () => {value: true}+ subscribeGithubSuggestions: () => {+ value: true+ }+ unsubscribeGithubSuggestions: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -616,7 +642,9 @@ export interface integrationsLogicMeta {githubIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]linearIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]githubAvailableInstallations: (- githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null,+ githubDiscoveryProjectId: number | string | null,+ currentProjectId: number | string) => GitHubAvailableInstallationApi[] | nullgithubPersonalConnected: (githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null@@ -696,7 +724,14 @@ export const integrationsLogic = kea<integrationsLogicType>([path(['lib', 'integrations', 'integrationsLogic']),connect(() => ({values: [preflightLogic, ['siteUrlMisconfigured', 'preflight'], teamLogic, ['currentProjectId']],- actions: [globalSetupLogic, ['markTaskAsCompleted'], eventUsageLogic, ['reportIntegrationConnectRejected']],+ actions: [+ globalSetupLogic,+ ['markTaskAsCompleted'],+ eventUsageLogic,+ ['reportIntegrationConnectRejected'],+ teamLogic,+ ['loadCurrentTeamSuccess'],+ ],})),actions({@@ -707,6 +742,14 @@ export const integrationsLogic = kea<integrationsLogicType>([callback,}),deleteIntegration: (id: number) => ({ id }),+ invalidateGithubSuggestions: true,+ setGithubDisconnecting: (disconnecting: boolean) => ({ disconnecting }),+ loadGithubAvailableInstallations: true,+ setGithubDiscovery: (+ response: GitHubAvailableInstallationsResponseApi | null,+ projectId: number | string,+ failed: boolean+ ) => ({ response, projectId, failed }),openNewIntegrationModal: (kind: IntegrationKind, id: string) => ({ kind, id }),closeNewIntegrationModal: true,openSetupModal: (integration?: IntegrationType, channelType?: ChannelType) => ({ integration, channelType }),@@ -728,8 +771,48 @@ export const integrationsLogic = kea<integrationsLogicType>([setAccessRequestReason: (reason: string) => ({ reason }),startPolling: true,stopPolling: true,+ subscribeGithubSuggestions: true,+ unsubscribeGithubSuggestions: true,+ clearIntegrations: true,}),reducers({+ integrations: [null as IntegrationType[] | null, { clearIntegrations: () => null }],+ githubDisconnecting: [false, { setGithubDisconnecting: (_, { disconnecting }) => disconnecting }],+ githubDiscoveryGeneration: [+ 0,+ {+ invalidateGithubSuggestions: (state) => state + 1,+ loadGithubAvailableInstallations: (state) => state + 1,+ },+ ],+ githubDiscoveryProjectId: [+ null as number | string | null,+ { setGithubDiscovery: (_, { projectId }) => projectId },+ ],+ githubAvailableInstallationsResponse: [+ null as GitHubAvailableInstallationsResponseApi | null,+ {+ invalidateGithubSuggestions: () => null,+ loadGithubAvailableInstallations: () => null,+ setGithubDiscovery: (_, { response }) => response,+ },+ ],+ githubAvailableInstallationsResponseLoading: [+ false,+ {+ invalidateGithubSuggestions: () => true,+ loadGithubAvailableInstallations: () => true,+ setGithubDiscovery: () => false,+ },+ ],+ githubDiscoveryFailed: [+ false,+ {+ loadGithubAvailableInstallations: () => false,+ invalidateGithubSuggestions: () => false,+ setGithubDiscovery: (_, { failed }) => failed,+ },+ ],newIntegrationModalId: [null as string | null,{@@ -812,6 +895,13 @@ export const integrationsLogic = kea<integrationsLogicType>([stopPolling: (state) => Math.max(0, state - 1),},],+ githubSuggestionSubscribers: [+ 0,+ {+ subscribeGithubSuggestions: (state) => state + 1,+ unsubscribeGithubSuggestions: (state) => Math.max(0, state - 1),+ },+ ],requestedAccessKinds: [[] as IntegrationKind[],{@@ -827,16 +917,18 @@ export const integrationsLogic = kea<integrationsLogicType>([},],}),- loaders(({ actions, values }) => ({+ loaders(({ actions, values, cache }) => ({integrations: [null as IntegrationType[] | null,{- loadIntegrations: async () => {+ loadIntegrations: async (_ = undefined, breakpoint) => {+ const projectId = values.currentProjectIdconst integrations: IntegrationType[] = []let offset = 0let hasNext = truewhile (hasNext) {- const res = await integrationsList(String(values.currentProjectId), { limit: 100, offset })+ const res = await integrationsList(String(projectId), { limit: 100, offset })+ await breakpoint()for (const integration of res.results) {// The API serves kinds this union does not name yet, and consumers such as// PosthogConnect read them, so every result is kept and only the icon is optional.@@ -901,35 +993,53 @@ export const integrationsLogic = kea<integrationsLogicType>([},],linkedGithubInstallation: [- null as IntegrationType | null,+ null as IntegrationConfigApi | null,{// Reuse a GitHub App installation already connected to another project in the same// org. A GitHub App installs once per org, so a second project can't reinstall; this// links the existing install without the fragile GitHub setup redirect roundtrip.// When the org has more than one installation the caller passes the chosen// installationId, since the backend can't auto-resolve between them.- linkExistingGithubInstallation: async (installationId?: string) => {+ linkExistingGithubInstallation: async (installationId: string | undefined, breakpoint) => {// The global kea-loaders failure handler shows the API detail. Do not add a// local toast here because the rejected loader would then show both messages.- const integration = await api.integrations.githubLinkExisting(- installationId ? { installation_id: installationId } : {}- )+ const projectGeneration = cache.githubProjectGeneration+ const discoveryId = values.githubAvailableInstallationsResponse?.discovery_id+ const projectId = values.currentProjectId+ actions.invalidateGithubSuggestions()+ let integration+ try {+ integration = await integrationsGithubLinkExistingCreate(String(projectId), {+ installation_id: installationId,+ discovery_id: discoveryId,+ })+ } catch (error) {+ await breakpoint()+ if (+ values.currentProjectId !== projectId ||+ cache.githubProjectGeneration !== projectGeneration+ ) {+ return values.linkedGithubInstallation+ }+ throw error+ } finally {+ if (+ values.currentProjectId === projectId &&+ cache.githubProjectGeneration === projectGeneration+ ) {+ actions.loadGithubAvailableInstallations()+ }+ }+ await breakpoint()+ if (values.currentProjectId !== projectId || cache.githubProjectGeneration !== projectGeneration) {+ return values.linkedGithubInstallation+ }lemonToast.success('Linked the existing GitHub installation to this project.')actions.loadIntegrations()return integration},},],- githubAvailableInstallationsResponse: [- null as GitHubAvailableInstallationsResponseApi | null,- {- // The org's other GitHub installations, so the UI can offer a picker when there's- // more than one, rather than failing the auto-resolve link as ambiguous.- loadGithubAvailableInstallations: async () => {- return await integrationsGithubAvailableInstallationsRetrieve(String(values.currentProjectId))- },- },- ],accessRequest: [null as IntegrationKind | null,{@@ -950,6 +1060,54 @@ export const integrationsLogic = kea<integrationsLogicType>([],})),listeners(({ actions, values, cache }) => ({+ loadCurrentTeamSuccess: () => {+ if (cache.githubProjectId === values.currentProjectId) {+ return+ }+ cache.githubProjectId = values.currentProjectId+ cache.githubProjectGeneration = (cache.githubProjectGeneration ?? 0) + 1+ actions.linkExistingGithubInstallationSuccess(null)+ cache.githubConnectionFingerprint = undefined+ // Clear only on a project switch: same-project team refreshes keep the connected integrations.+ actions.clearIntegrations()+ actions.invalidateGithubSuggestions()+ actions.loadIntegrations()+ if (values.githubSuggestionSubscribers > 0) {+ actions.loadGithubAvailableInstallations()+ }+ },+ loadGithubAvailableInstallations: async () => {+ if (values.githubDisconnecting) {+ return+ }+ const projectId = values.currentProjectId+ const generation = values.githubDiscoveryGeneration+ try {+ const response = await integrationsGithubAvailableInstallationsRetrieve(String(projectId))+ if (projectId === values.currentProjectId && generation === values.githubDiscoveryGeneration) {+ actions.setGithubDiscovery(response, projectId, false)+ }+ } catch {+ if (projectId === values.currentProjectId && generation === values.githubDiscoveryGeneration) {+ actions.setGithubDiscovery(null, projectId, true)+ }+ }+ },+ loadIntegrationsSuccess: ({ integrations }) => {+ const fingerprint = JSON.stringify(+ integrations+ ?.filter((row) => row.kind === 'github')+ .map((row) => [row.id, row.config?.installation_id, row.config?.account, row.installation_status])+ )+ if (+ cache.githubConnectionFingerprint !== undefined &&+ cache.githubConnectionFingerprint !== fingerprint &&+ values.githubSuggestionSubscribers > 0+ ) {+ actions.loadGithubAvailableInstallations()+ }+ cache.githubConnectionFingerprint = fingerprint+ },loadGitHubRepositories: ({ integrationId }) => {actions.loadGitHubRepositoriesPage(integrationId, 0)},@@ -989,7 +1147,12 @@ export const integrationsLogic = kea<integrationsLogicType>([}, 'poll')cache.disposables.add(() => {- const onFocus = (): void => actions.loadIntegrations()+ const onFocus = (): void => {+ actions.loadIntegrations()+ if (values.githubSuggestionSubscribers > 0) {+ actions.loadGithubAvailableInstallations()+ }+ }window.addEventListener('focus', onFocus)return () => window.removeEventListener('focus', onFocus)},@@ -997,6 +1160,11 @@ export const integrationsLogic = kea<integrationsLogicType>([{ pauseOnPageHidden: false })},+ subscribeGithubSuggestions: () => {+ if (values.githubSuggestionSubscribers === 1) {+ actions.loadGithubAvailableInstallations()+ }+ },stopPolling: () => {if (values.pollingSubscribers > 0) {return@@ -1119,6 +1287,10 @@ export const integrationsLogic = kea<integrationsLogicType>([children: 'Disconnect',status: 'danger',onClick: async () => {+ if (integration.kind === 'github') {+ actions.setGithubDisconnecting(true)+ actions.invalidateGithubSuggestions()+ }try {await api.integrations.delete(id)actions.loadIntegrations()@@ -1129,6 +1301,11 @@ export const integrationsLogic = kea<integrationsLogicType>([} else {toastApiError(e)}+ } finally {+ if (integration.kind === 'github') {+ actions.setGithubDisconnecting(false)+ actions.loadGithubAvailableInstallations()+ }}},},@@ -1138,7 +1315,8 @@ export const integrationsLogic = kea<integrationsLogicType>([})},})),- afterMount(({ actions }) => {+ afterMount(({ actions, values, cache }) => {+ cache.githubProjectId = values.currentProjectIdactions.loadIntegrations()const params = new URLSearchParams(window.location.search)@@ -1176,9 +1354,13 @@ export const integrationsLogic = kea<integrationsLogicType>([},],githubAvailableInstallations: [- (s) => [s.githubAvailableInstallationsResponse],- (response: GitHubAvailableInstallationsResponseApi | null): GitHubAvailableInstallationApi[] | null => {- return response?.installations ?? null+ (s) => [s.githubAvailableInstallationsResponse, s.githubDiscoveryProjectId, s.currentProjectId],+ (+ response: GitHubAvailableInstallationsResponseApi | null,+ projectId: number | string | null,+ currentProjectId: number | string+ ): GitHubAvailableInstallationApi[] | null => {+ return projectId === currentProjectId ? (response?.installations ?? null) : null},],githubPersonalConnected: [diff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.tsindex 147699e96954..a096b0127e37 100644--- a/frontend/src/lib/integrations/utils.ts+++ b/frontend/src/lib/integrations/utils.ts@@ -44,6 +44,21 @@ import IconTwilio from 'public/services/twilio.png'import IconVercel from 'public/services/vercel.png'import IconYouTubeAnalytics from 'public/services/youtube_analytics.png'+/**+ * What a "link an existing installation" banner offered, reported as counts on+ * `integration_link_existing_offered`. `unnamed` counts entries shown by installation id because+ * their account name is missing, which is the case a reader cannot recognize.+ */+export interface IntegrationLinkExistingCounts {+ discoveryId?: string+ installationIds?: string[]+ responseAgeMs?: number+ total: number+ sibling: number+ orphan: number+ unnamed: number+}+/*** Where a user started an integration connect flow. Reported as the `surface` property on* `integration_connect_clicked`, so these strings are frozen — renaming one silently splits adiff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex d38308883c00..ea3bde0b4e3f 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -4,7 +4,7 @@ import posthog from 'posthog-js'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import type { Dayjs } from 'lib/dayjs'import { now } from 'lib/dayjs'-import type { IntegrationConnectSurface } from 'lib/integrations/utils'+import type { IntegrationConnectSurface, IntegrationLinkExistingCounts } from 'lib/integrations/utils'import { TimeToSeeDataPayload } from 'lib/internalMetrics'import { preflightLogic } from 'lib/logic/preflightLogic'import { objectClean } from 'lib/utils/objects'@@ -1849,6 +1849,17 @@ export interface eventUsageLogicActions {reportFunnelStepReordered: () => {value: true}+ reportGithubInstallationSelected: (+ surface: string,+ discoveryId?: string,+ installationId?: string,+ responseAgeMs?: number+ ) => {+ discoveryId: string | undefined+ installationId: string | undefined+ responseAgeMs: number | undefined+ surface: string+ }reportGroupProfileViewed: (delay?: number) => {delay: number | undefined}@@ -2019,6 +2030,15 @@ export interface eventUsageLogicActions {error: stringkind: string}+ reportIntegrationLinkExistingOffered: (+ kind: string,+ surface: IntegrationConnectSurface,+ counts: IntegrationLinkExistingCounts+ ) => {+ counts: IntegrationLinkExistingCounts+ kind: string+ surface: IntegrationConnectSurface+ }reportInviteMembersButtonClicked: () => {value: true}@@ -2603,6 +2623,17 @@ export const eventUsageLogic = kea<eventUsageLogicType>([surface,selfDriving,}),+ reportIntegrationLinkExistingOffered: (+ kind: string,+ surface: IntegrationConnectSurface,+ counts: IntegrationLinkExistingCounts+ ) => ({ kind, surface, counts }),+ reportGithubInstallationSelected: (+ surface: string,+ discoveryId?: string,+ installationId?: string,+ responseAgeMs?: number+ ) => ({ surface, discoveryId, installationId, responseAgeMs }),reportIntegrationConnectRejected: (kind: string, error: string) => ({ kind, error }),reportPersonalIntegrationConnectClicked: (kind: string) => ({ kind }),reportGroupPropertyUpdated: (@@ -3557,6 +3588,31 @@ export const eventUsageLogic = kea<eventUsageLogicType>([self_driving: selfDriving,})},+ // The banner offering an existing installation is where an unfamiliar account name is read,+ // so it reports what it offered: without this, neither the label nor its source is recorded+ // anywhere, and a confusing entry only shows up as a support ticket.+ reportGithubInstallationSelected: ({ surface, discoveryId, installationId, responseAgeMs }) => {+ posthog.capture('integration_link_existing_selected', {+ integration_kind: 'github',+ surface,+ discovery_id: discoveryId,+ installation_id: installationId,+ response_age_ms: responseAgeMs,+ })+ },+ reportIntegrationLinkExistingOffered: ({ kind, surface, counts }) => {+ posthog.capture('integration_link_existing_offered', {+ integration_kind: kind,+ surface,+ discovery_id: counts.discoveryId,+ displayed_installation_ids: counts.installationIds,+ response_age_ms: counts.responseAgeMs,+ installation_count: counts.total,+ sibling_installation_count: counts.sibling,+ orphan_installation_count: counts.orphan,+ unnamed_installation_count: counts.unnamed,+ })+ },// Counts connect attempts the provider sent back without a code. `integration_connect_clicked`// only says the user started, so without this the drop-off is invisible outside session// recordings — and `access_denied` in particular hides a workspace waiting on an admin.diff --git a/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.ts b/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.tsindex 6f742a2992df..5c043f9db424 100644--- a/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.ts+++ b/frontend/src/scenes/StripeConfirmInstall/stripeConfirmInstallLogic.ts@@ -31,7 +31,7 @@ export interface stripeConfirmInstallLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface stripeConfirmInstallLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogiccancelInstall: () => {value: true}diff --git a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.tsindex a06320f3a5b6..1ea152e9d666 100644--- a/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts+++ b/frontend/src/scenes/integrations/aws-s3/awsS3SetupModalLogic.ts@@ -58,7 +58,7 @@ export interface awsS3SetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface awsS3SetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetAwsS3Integration: (values?: {awsAccessKeyId: stringawsRoleArn: stringdiff --git a/frontend/src/scenes/integrations/azure-blob/azureBlobSetupModalLogic.ts b/frontend/src/scenes/integrations/azure-blob/azureBlobSetupModalLogic.tsindex 8c55eb406373..457b84305e3c 100644--- a/frontend/src/scenes/integrations/azure-blob/azureBlobSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/azure-blob/azureBlobSetupModalLogic.ts@@ -44,7 +44,7 @@ export interface azureBlobSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface azureBlobSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetAzureBlobIntegration: (values?: { connectionString: string }) => {values?: {connectionString: stringdiff --git a/frontend/src/scenes/integrations/components/GithubIntegration.stories.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.stories.tsxnew file mode 100644index 000000000000..888fc504a15c--- /dev/null+++ b/frontend/src/scenes/integrations/components/GithubIntegration.stories.tsx@@ -0,0 +1,65 @@+import type { Meta, StoryObj } from '@storybook/react'++import { useStorybookMocks } from '~/mocks/browser'++import { GithubIntegration } from './GithubIntegration'++interface StoryArgs {+ multiple: boolean+ width: number+ unavailable: boolean+}++const meta: Meta<StoryArgs> = {+ title: 'Components/Integrations/GitHub suggestions',+ args: { multiple: false, width: 960, unavailable: false },+ render: ({ multiple, width, unavailable }): JSX.Element => {+ useStorybookMocks({+ get: {+ '/api/projects/:id/integrations': { results: [] },+ '/api/projects/:id/integrations/github/available_installations/': {+ discovery_id: '11111111-1111-4111-8111-111111111111',+ discovered_at: new Date().toISOString(),+ personal_github_connected: true,+ personal_github_login: 'synthetic-reader',+ personal_discovery_status: unavailable ? 'unavailable' : 'ok',+ installations: [+ {+ installation_id: '9001',+ account_name: 'synthetic-owner',+ account_type: 'Organization',+ source_team_id: unavailable ? 7 : null,+ source_team_name: unavailable ? 'Synthetic website' : null,+ },+ ...(multiple+ ? [+ {+ installation_id: '9002',+ account_name: null,+ account_type: null,+ source_team_id: 7,+ source_team_name: 'Synthetic website',+ },+ ]+ : []),+ ],+ },+ '/api/users/@me/integrations/github/install_requests/': {+ results: [],+ install_url: 'https://example.com/install',+ },+ },+ })+ return (+ <div className={width === 520 ? 'w-[520px]' : 'w-[960px]'}>+ <GithubIntegration connectSurface="settings" />+ </div>+ )+ },+}+export default meta++export const Single: StoryObj<StoryArgs> = {}+export const Multiple: StoryObj<StoryArgs> = { args: { multiple: true } }+export const Narrow: StoryObj<StoryArgs> = { args: { width: 520, multiple: true } }+export const PersonalUnavailable: StoryObj<StoryArgs> = { args: { unavailable: true, width: 520 } }diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsxindex 25ed72391f0c..e9d9b55c9620 100644--- a/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx+++ b/frontend/src/scenes/integrations/components/GithubIntegration.test.tsx@@ -25,7 +25,14 @@ describe('GithubIntegration', () => {'/api/projects/:team_id/integrations': { results: [] },'/api/projects/:team_id/integrations/github/available_installations/': () => [200,- { installations: availableInstallations, personal_github_connected: false },+ {+ installations: availableInstallations,+ personal_github_connected: false,+ personal_discovery_status: 'ok',+ personal_github_login: 'synthetic-user',+ discovery_id: '11111111-1111-4111-8111-111111111111',+ discovered_at: new Date().toISOString(),+ },],'/api/users/@me/integrations/github/install_requests/': () => [200,@@ -97,6 +104,111 @@ describe('GithubIntegration', () => {})+ it.each([+ [+ 'a sibling project',+ {+ installation_id: '55555',+ account_name: 'acme',+ account_type: null,+ source_team_id: 7,+ source_team_name: 'Website',+ },+ 'and connected to',+ ],+ [+ 'the personal GitHub connection',+ {+ installation_id: '55555',+ account_name: 'acme',+ account_type: null,+ source_team_id: null,+ source_team_name: null,+ },+ 'Found through your GitHub connection as synthetic-user',+ ],+ ])('says an installation offered from %s is from there', async (_source, installation, expectedSource) => {+ availableInstallations = [installation]++ render(+ <Provider>+ <GithubIntegration connectSurface="settings" />+ </Provider>+ )++ expect(await screen.findByText(expectedSource, { exact: false })).toBeInTheDocument()+ })++ // The label used to fall back to the login of whoever connected the install, which reads as a+ // stranger's account. An install with no account name must say so instead of naming a person.+ it('falls back to the installation id when the account name is missing', async () => {+ availableInstallations = [+ {+ installation_id: '55555',+ account_name: null,+ account_type: null,+ source_team_id: 7,+ source_team_name: 'Website',+ },+ ]++ render(+ <Provider>+ <GithubIntegration connectSurface="settings" />+ </Provider>+ )++ expect(await screen.findByText('installation 55555')).toBeInTheDocument()+ })++ it('reports what the link-existing banner offered', async () => {+ availableInstallations = [+ {+ installation_id: '55555',+ account_name: 'acme',+ account_type: null,+ source_team_id: 7,+ source_team_name: 'Website',+ },+ {+ installation_id: '66666',+ account_name: null,+ account_type: null,+ source_team_id: null,+ source_team_name: null,+ },+ ]++ render(+ <Provider>+ <GithubIntegration connectSurface="settings" />+ </Provider>+ )++ await screen.findByText('Choose an account')+ expect(captureSpy.mock.calls.filter((call) => call[0] === 'integration_link_existing_offered')).toHaveLength(0)+ await userEvent.click(screen.getByText('Choose an account'))+ await waitFor(() =>+ expect(+ captureSpy.mock.calls+ .filter((call) => call[0] === 'integration_link_existing_offered')+ .map((call) => call[1])+ ).toEqual([+ {+ discovery_id: '11111111-1111-4111-8111-111111111111',+ displayed_installation_ids: ['55555', '66666'],+ response_age_ms: expect.any(Number),+ integration_kind: 'github',+ surface: 'settings',+ installation_count: 2,+ sibling_installation_count: 1,+ orphan_installation_count: 1,+ unnamed_installation_count: 1,+ },+ ])+ )+ })+it.each([['pending', 'GitHub sent your request', 'Copy message for your org owner'],['approved', 'An organization owner approved the PostHog app for', 'Finish connecting'],diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.tsxindex 039474a30f67..555bf279697d 100644--- a/frontend/src/scenes/integrations/components/GithubIntegration.tsx+++ b/frontend/src/scenes/integrations/components/GithubIntegration.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'import { IconChevronDown, IconGithub } from '@posthog/icons'import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'@@ -8,7 +9,7 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { GitHubInstallRequestsBanner } from 'lib/integrations/GitHubInstallRequestsBanner'import { githubInstallRequestsLogic } from 'lib/integrations/githubInstallRequestsLogic'import { integrationsLogic } from 'lib/integrations/integrationsLogic'-import type { IntegrationConnectSurface } from 'lib/integrations/utils'+import type { IntegrationConnectSurface, IntegrationLinkExistingCounts } from 'lib/integrations/utils'import { LemonMenu } from 'lib/lemon-ui/LemonMenu'import { cn } from 'lib/utils/css-classes'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'@@ -39,12 +40,26 @@ export function GithubIntegration({*/connectSurface?: IntegrationConnectSurface}): JSX.Element {+ const [visibleDiscoveryId, setVisibleDiscoveryId] = useState<string | null>(null)const { currentTeam } = useValues(teamLogic)- const { linkedGithubInstallationLoading, githubAvailableInstallations, githubPersonalConnected } =- useValues(integrationsLogic)- const { linkExistingGithubInstallation, loadGithubAvailableInstallations, startPolling, stopPolling } =- useActions(integrationsLogic)- const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)+ const {+ linkedGithubInstallationLoading,+ githubAvailableInstallations,+ githubPersonalConnected,+ githubAvailableInstallationsResponse,+ githubAvailableInstallationsResponseLoading,+ githubDiscoveryFailed,+ } = useValues(integrationsLogic)+ const {+ linkExistingGithubInstallation,+ loadGithubAvailableInstallations,+ startPolling,+ stopPolling,+ subscribeGithubSuggestions,+ unsubscribeGithubSuggestions,+ } = useActions(integrationsLogic)+ const { reportIntegrationConnectClicked, reportIntegrationLinkExistingOffered, reportGithubInstallationSelected } =+ useActions(eventUsageLogic)const { hasPendingInstallRequests } = useValues(githubInstallRequestsLogic)const githubIntegrations = useIntegrations('github')@@ -52,9 +67,12 @@ export function GithubIntegration({// hangs off the GitHub setup UI instead of the shared integrations load. Polling is likewise// scoped to the settings surface: an uninstall on GitHub should show up while someone is looking.useOnMountEffect(() => {- loadGithubAvailableInstallations()startPolling()- return () => stopPolling()+ subscribeGithubSuggestions()+ return () => {+ unsubscribeGithubSuggestions()+ stopPolling()+ }})const settingsPath = next ?? urls.settings('environment-integrations')@@ -65,10 +83,31 @@ export function GithubIntegration({const installations = githubAvailableInstallations ?? []const isConnected = githubIntegrations.length > 0- const canLinkExisting = !isConnected && installations.length > 0+ const canLinkExisting = !isConnected && !githubAvailableInstallationsResponseLoading && installations.length > 0const multipleInstallations = installations.length > 1+ const pickerOpen =+ visibleDiscoveryId !== null && visibleDiscoveryId === githubAvailableInstallationsResponse?.discovery_idconst installRequestInProgress = hasPendingInstallRequests+ // A discovery response is reported only after its suggestions render.+ const offeredInstallationIds =+ canLinkExisting && (!multipleInstallations || pickerOpen)+ ? installations.map((installation) => installation.installation_id).join(',')+ : ''+ useEffect(() => {+ if (offeredInstallationIds) {+ reportIntegrationLinkExistingOffered('github', connectSurface ?? 'integration_landing_page', {+ ...countInstallations(installations),+ discoveryId: githubAvailableInstallationsResponse?.discovery_id,+ installationIds: installations.map((installation) => installation.installation_id),+ responseAgeMs: Math.max(+ 0,+ Date.now() - Date.parse(githubAvailableInstallationsResponse?.discovered_at ?? '')+ ),+ })+ }+ }, [offeredInstallationIds, connectSurface, githubAvailableInstallationsResponse?.discovery_id]) // oxlint-disable-line react-hooks/exhaustive-deps+// Silent without `connectSurface`, because the only card rendered without one sits on the OAuth// landing page, which already reports every kind's connect click for itself.const reportConnect = (variant?: IntegrationConnectSurface): void => {@@ -92,18 +131,47 @@ export function GithubIntegration({below. */}{canLinkExisting && (<LemonBanner type="info" hideIcon>- <div className="flex items-center gap-3">+ {/* Wraps because the centered cards (onboarding, the integration landing page)+ are narrow enough that the sentence and the button can't share a row. */}+ <div className="flex flex-wrap items-center gap-3"><span className="min-w-0 text-sm font-normal">{multipleInstallations ? (- <>Already installed on more than one of your GitHub accounts.</>+ <>PostHog is already installed on more than one GitHub account.</>) : (<>- Already installed on your GitHub account{' '}- <code>{accountLabel(installations[0])}</code>.+ {installations[0].source_team_id !== null ? (+ <span>+ PostHog is installed on{' '}+ <strong>{accountLabel(installations[0])}</strong> and connected to{' '}+ <strong>+ {installations[0].source_team_name ??+ `project ${installations[0].source_team_id}`}+ </strong>+ .+ </span>+ ) : (+ <span>+ PostHog is installed on the GitHub account{' '}+ <strong>{accountLabel(installations[0])}</strong>.{' '}+ <span>+ {sourceLabel(+ installations[0],+ githubAvailableInstallationsResponse?.personal_github_login+ )}+ .+ </span>+ </span>+ )}</>)}</span><GitHubInstallationLink+ onVisibilityChange={(visible) =>+ setVisibleDiscoveryId(+ visible ? (githubAvailableInstallationsResponse?.discovery_id ?? null) : null+ )+ }+ personalGithubLogin={githubAvailableInstallationsResponse?.personal_github_login}installations={installations}loading={linkedGithubInstallationLoading}emphasizeInstallation={emphasizeConnect}@@ -114,13 +182,44 @@ export function GithubIntegration({// every other button here, instead of a fixed literal, so the// surface still says where the click happened.reportConnect(connectSurface === 'settings' ? 'settings_link_existing' : undefined)+ reportGithubInstallationSelected(+ connectSurface ?? 'integration_landing_page',+ githubAvailableInstallationsResponse?.discovery_id,+ installationId,+ Math.max(+ 0,+ Date.now() -+ Date.parse(githubAvailableInstallationsResponse?.discovered_at ?? '')+ )+ )linkExistingGithubInstallation(installationId)}}projectName={currentTeam?.name}/></div>+ {installations.some((installation) => installation.source_team_id === null) && (+ <p className="mb-0 mt-2 text-sm font-normal">+ GitHub can include accounts whose repositories you can access.+ </p>+ )}</LemonBanner>)}+ {!isConnected && githubAvailableInstallationsResponseLoading && (+ <p className="text-secondary mb-0">Looking for existing GitHub installations…</p>+ )}+ {!isConnected &&+ !githubAvailableInstallationsResponseLoading &&+ (githubDiscoveryFailed ||+ githubAvailableInstallationsResponse?.personal_discovery_status === 'unavailable') && (+ <LemonBanner type="warning">+ <div className="flex flex-wrap items-center gap-2">+ <span>Couldn't check your personal GitHub connection.</span>+ <LemonButton size="small" onClick={loadGithubAvailableInstallations}>+ Retry+ </LemonButton>+ </div>+ </LemonBanner>+ )}{installRequestInProgress ? null : emphasizeConnect && !isConnected ? (<div className="flex w-full flex-col items-center gap-4"><div className="flex flex-wrap justify-center gap-2">@@ -178,7 +277,24 @@ export function GithubIntegration({// The GitHub account name is what a person recognizes, so it carries the label wherever we have// it. The id is a fallback for an installation whose account metadata never arrived.function accountLabel(installation: GitHubAvailableInstallationApi): string {- return installation.account_name ?? `installation ${installation.installation_id}`+ return installation.account_name || `installation ${installation.installation_id}`+}++function countInstallations(installations: GitHubAvailableInstallationApi[]): IntegrationLinkExistingCounts {+ return {+ total: installations.length,+ sibling: installations.filter((installation) => installation.source_team_id !== null).length,+ orphan: installations.filter((installation) => installation.source_team_id === null).length,+ unnamed: installations.filter((installation) => !installation.account_name).length,+ }+}++// Where an entry came from decides whether an unfamiliar account reads as a teammate's work or as a+// stranger in your settings, so every entry says its source.+function sourceLabel(installation: GitHubAvailableInstallationApi, personalGithubLogin?: string | null): string {+ return installation.source_team_id !== null+ ? `Connected to ${installation.source_team_name ?? `project ${installation.source_team_id}`}`+ : `Found through your GitHub connection${personalGithubLogin ? ` as ${personalGithubLogin}` : ''}`}export function GitHubInstallationLink({@@ -187,8 +303,12 @@ export function GitHubInstallationLink({onLink,projectName,emphasizeInstallation = false,+ personalGithubLogin,+ onVisibilityChange,}: {installations: GitHubAvailableInstallationApi[]+ personalGithubLogin?: string | null+ onVisibilityChange?: (visible: boolean) => voidloading: booleanonLink: (installationId?: string) => void/** Named on the button, so it's clear which project the install lands in. */@@ -218,9 +338,15 @@ export function GitHubInstallationLink({return (<LemonMenu+ onVisibilityChange={onVisibilityChange}items={installations.map((installation) => ({key: installation.installation_id,- label: accountLabel(installation),+ label: (+ <span className="flex flex-col items-start">+ <span>{accountLabel(installation)}</span>+ <span className="text-xs text-secondary">{sourceLabel(installation, personalGithubLogin)}</span>+ </span>+ ),disabledReason: loading ? 'Connecting an account' : undefined,onClick: () => onLink(installation.installation_id),}))}diff --git a/frontend/src/scenes/integrations/components/Integrations.test.tsx b/frontend/src/scenes/integrations/components/Integrations.test.tsxindex 33e76f06da4a..777b8513a2fe 100644--- a/frontend/src/scenes/integrations/components/Integrations.test.tsx+++ b/frontend/src/scenes/integrations/components/Integrations.test.tsx@@ -17,12 +17,14 @@ describe('GitHubInstallationLink', () => {account_name: 'PostHog',account_type: 'Organization',source_team_id: 1,+ source_team_name: 'Website',},{installation_id: '202',account_name: 'Hedgebox',account_type: 'Organization',source_team_id: 2,+ source_team_name: 'Hedgebox app',},]@@ -49,6 +51,7 @@ describe('GitHubInstallationLink', () => {account_name: 'PostHog',account_type: 'Organization',source_team_id: null,+ source_team_name: null,},]diff --git a/frontend/src/scenes/integrations/databricks/databricksSetupModalLogic.ts b/frontend/src/scenes/integrations/databricks/databricksSetupModalLogic.tsindex e688bb09ceba..79a3399a6aae 100644--- a/frontend/src/scenes/integrations/databricks/databricksSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/databricks/databricksSetupModalLogic.ts@@ -50,7 +50,7 @@ export interface databricksSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface databricksSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetDatabricksIntegration: (values?: { clientId: string; clientSecret: string; serverHostname: string }) => {values?: {clientId: stringdiff --git a/frontend/src/scenes/integrations/gitlab/gitlabSetupModalLogic.ts b/frontend/src/scenes/integrations/gitlab/gitlabSetupModalLogic.tsindex b3b97db065cd..6a137588d42c 100644--- a/frontend/src/scenes/integrations/gitlab/gitlabSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/gitlab/gitlabSetupModalLogic.ts@@ -47,7 +47,7 @@ export interface gitlabSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface gitlabSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetGitlabIntegration: (values?: { hostname: string; projectAccessToken: string; projectId: string }) => {values?: {hostname: stringdiff --git a/frontend/src/scenes/integrations/google-cloud-service-account/googleCloudServiceAccountSetupModalLogic.ts b/frontend/src/scenes/integrations/google-cloud-service-account/googleCloudServiceAccountSetupModalLogic.tsindex a55dc9a3431d..1e95fa470738 100644--- a/frontend/src/scenes/integrations/google-cloud-service-account/googleCloudServiceAccountSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/google-cloud-service-account/googleCloudServiceAccountSetupModalLogic.ts@@ -62,7 +62,7 @@ export interface googleCloudServiceAccountSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface googleCloudServiceAccountSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetGoogleCloudServiceAccountIntegration: (values?: {jsonKeyFile: nullprivateKey: string | nulldiff --git a/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts b/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.tsindex a4f81f1b3176..5f044a2fc60a 100644--- a/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/postgresql/postgreSQLSetupModalLogic.ts@@ -65,7 +65,7 @@ export interface postgreSQLSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface postgreSQLSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetPostgreSQLIntegration: (values?: {host: string | nullname: stringdiff --git a/frontend/src/scenes/integrations/redshift/redshiftSetupModalLogic.ts b/frontend/src/scenes/integrations/redshift/redshiftSetupModalLogic.tsindex 01a022c73d33..4ca7b7b322cc 100644--- a/frontend/src/scenes/integrations/redshift/redshiftSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/redshift/redshiftSetupModalLogic.ts@@ -96,7 +96,7 @@ export interface redshiftSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface redshiftSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetRedshiftIntegration: (values?: {autoCreate: booleanawsAccessKeyId: stringdiff --git a/frontend/src/scenes/integrations/s3-compatible/s3CompatibleSetupModalLogic.ts b/frontend/src/scenes/integrations/s3-compatible/s3CompatibleSetupModalLogic.tsindex b631e1acd783..dfc472e902be 100644--- a/frontend/src/scenes/integrations/s3-compatible/s3CompatibleSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/s3-compatible/s3CompatibleSetupModalLogic.ts@@ -53,7 +53,7 @@ export interface s3CompatibleSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface s3CompatibleSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetS3CompatibleIntegration: (values?: {awsAccessKeyId: stringawsSecretAccessKey: stringdiff --git a/frontend/src/scenes/integrations/snowflake/snowflakeSetupModalLogic.ts b/frontend/src/scenes/integrations/snowflake/snowflakeSetupModalLogic.tsindex 3df8ba4456b7..c8db770d2050 100644--- a/frontend/src/scenes/integrations/snowflake/snowflakeSetupModalLogic.ts+++ b/frontend/src/scenes/integrations/snowflake/snowflakeSetupModalLogic.ts@@ -65,7 +65,7 @@ export interface snowflakeSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface snowflakeSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetSnowflakeIntegration: (values?: {account: stringauthentication_type: stringdiff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.tsindex 4e98d86e5b26..5232476f1330 100644--- a/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/wizardCloudRunLogic.ts@@ -63,7 +63,7 @@ export interface wizardCloudRunLogicActions {startedAt: stringtaskId: string} // activeCloudRunLogic- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicreportOnboardingCloudRunQueued: (props: { repository: string; runId: string; taskId: string }) => {repository: stringrunId: stringdiff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.tsindex b33f6d04ebe2..c4a96c7b0b9e 100644--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts@@ -113,7 +113,7 @@ export interface personalIntegrationsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface personalIntegrationsLogicActions {- loadProjectIntegrations: () => any // integrationsLogic+ loadProjectIntegrations: (_?: any) => any // integrationsLogicprojectIntegrationsLoaded: (integrations: import('../../../types').IntegrationType[],payload?: anydiff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.pyindex 942d65cb7151..5f3ca6b01e3e 100644--- a/posthog/api/github_callback/installation_events.py+++ b/posthog/api/github_callback/installation_events.py@@ -30,6 +30,7 @@ from django.utils import timezoneimport structlogfrom posthog.models.integration import Integration, invalidate_github_repository_caches_for_installation+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user_integration import GitHubInstallRequest, UserIntegrationlogger = structlog.get_logger(__name__)@@ -60,8 +61,29 @@ def handle_installation_event(payload: dict) -> HttpResponse:integrations = list(Integration.objects.filter(kind="github", integration_id=installation_id))_pause_loops_referencing_integrations(integrations, 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()+ project_audits = [GitHubAudit.project(row) for row in integrations]+ personal_rows = list(UserIntegration.objects.filter(kind="github", integration_id=installation_id))+ personal_audits = [GitHubAudit.personal(row) for row in personal_rows]+ try:+ # nosemgrep: idor-lookup-without-team (a verified installation webhook removes this installation across projects)+ team_deleted, _ = Integration.objects.filter(+ kind="github", integration_id=installation_id, pk__in=[row.pk for row in integrations]+ ).delete()+ except Exception as exc:+ for audit in project_audits:+ audit.record("webhook_cleanup_failed", stage="project_deletion", failure_type=type(exc).__name__)+ raise+ for audit in project_audits:+ audit.record("deleted", after_commit=True, customer_visible=True, outcome="disconnected")+ audit.record("webhook_cleanup", after_commit=True, outcome="already_absent", completed_deletion=True)+ try:+ user_deleted, _ = UserIntegration.objects.filter(pk__in=[row.pk for row in personal_rows]).delete()+ except Exception as exc:+ for audit in personal_audits:+ audit.record("webhook_cleanup_failed", stage="personal_deletion", failure_type=type(exc).__name__)+ raise+ for audit in personal_audits:+ audit.record("credential_deleted", after_commit=True, reason="installation_deleted_webhook")logger.info("github_installation_webhook_uninstalled",diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.pyindex b068e0ddad44..76c9ccac5105 100644--- a/posthog/api/github_callback/personal_finish.py+++ b/posthog/api/github_callback/personal_finish.py@@ -81,6 +81,8 @@ def finish_personal(request: HttpRequest) -> FinishResult:GitHubAuthorizeState(token=discover_token,flow=FlowKind.OAUTH_DISCOVER,+ originating_organization_id=authorize_state.originating_organization_id,+ flow_id=authorize_state.flow_id,user_id=user.id,connect_from=connect_from_value,),@@ -152,6 +154,8 @@ def finish_personal(request: HttpRequest) -> FinishResult:GitHubAuthorizeState(token=token,flow=FlowKind.PERSONAL_INSTALL,+ originating_organization_id=authorize_state.originating_organization_id,+ flow_id=authorize_state.flow_id,user_id=user.id,connect_from=connect_from_value,),@@ -195,7 +199,12 @@ def finish_personal(request: HttpRequest) -> FinishResult:logger.warning("github_link: failed to fetch installation info", exc_info=True)return _error(exc.code)- user_github_integration_from_installation(user, installation_access, authorization)+ user_github_integration_from_installation(+ user,+ installation_access,+ authorization,+ originating_organization_id=authorize_state.originating_organization_id,+ )if flow.creates_team_integration and authorize_state.team_id is not None:installation_id = str(installation_ids[0])diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.pyindex e48b31012020..9693d9a95b53 100644--- a/posthog/api/github_callback/personal_state.py+++ b/posthog/api/github_callback/personal_state.py@@ -6,17 +6,34 @@ team. Shared by the personal "unlinked installations" check, the org installatioorphan-installation adoption."""+from dataclasses import fieldfrom typing import Anyimport requests+from posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import Userfrom posthog.models.user_integration import UserGitHubIntegration, UserIntegration_OBSERVABILITY_SOURCE = "integration"+@frozen+class PersonalGitHubCredential:+ token: str = field(repr=False)+ integration: UserIntegration = field(repr=False)+++@frozen(frozen=False)+class PersonalGitHubDiscovery:+ audit: GitHubAudit+ discovery_id: str+ login: str | None = None+ status: str = "not_connected"++def _newest_personal_github_integration(user: User) -> UserIntegration | None:return (UserIntegration.objects.filter(user=user, kind="github")@@ -39,7 +56,7 @@ def personal_github_login(user: User) -> str | None:return UserGitHubIntegration(integration).github_login-def usable_personal_github_token(user: User) -> str | None:+def usable_personal_github_credential(user: User) -> PersonalGitHubCredential | None:"""Return a usable user-to-server GitHub token for ``user``, refreshing it if needed.Tries every personal GitHub link newest-first, since the newest row can hold stale credentials@@ -56,11 +73,18 @@ def usable_personal_github_token(user: User) -> str | None:except Exception:continueif token:- return token+ return PersonalGitHubCredential(token=token, integration=integration)return None-def list_user_github_app_installations(user: User) -> list[dict[str, Any]] | None:+def usable_personal_github_token(user: User) -> str | None:+ credential = usable_personal_github_credential(user)+ return credential.token if credential else None+++def list_user_github_app_installations(+ user: User, discovery: PersonalGitHubDiscovery | None = None+) -> list[dict[str, Any]] | None:"""List the GitHub App installations visible to ``user``'s personal OAuth token.Returns installation dicts as GitHub reports them from ``GET /user/installations`` (``id``,@@ -68,9 +92,20 @@ def list_user_github_app_installations(user: User) -> list[dict[str, Any]] | Nonpersonal GitHub link, a token refresh failure, a network error, or a non-200 response. Callersmust treat None as "unknown" and degrade gracefully rather than fail the request."""- token = usable_personal_github_token(user)- if token is None:+ credential = usable_personal_github_credential(user)+ connected = user_has_personal_github_integration(user)+ if discovery:+ discovery.status = "unavailable" if connected else "not_connected"+ if credential is None:return None+ token = credential.token+ if discovery:+ discovery.login = UserGitHubIntegration(credential.integration).github_login+ discovery.audit.record(+ "discovery_credential_selected",+ discovery_id=discovery.discovery_id,+ **(GitHubAudit.personal(credential.integration).personal_metadata or {}),+ )try:# Identity-blind: user OAuth token, metered against the user's budget, not an installation's.@@ -83,8 +118,19 @@ def list_user_github_app_installations(user: User) -> list[dict[str, Any]] | Nontimeout=10,)except (requests.RequestException, GitHubEgressBudgetExhausted):+ if discovery:+ discovery.audit.record(+ "discovery_failed", discovery_id=discovery.discovery_id, reason="github_request_failed"+ )return None+ if discovery:+ discovery.audit.record(+ "discovery_github_response",+ discovery_id=discovery.discovery_id,+ github_status=response.status_code,+ github_request_id=response.headers.get("X-GitHub-Request-Id"),+ )if response.status_code != 200:return None@@ -96,6 +142,23 @@ def list_user_github_app_installations(user: User) -> list[dict[str, Any]] | Nonif not isinstance(installations, list):return None+ if discovery:+ discovery.status = "ok"+ discovery.audit.record(+ "discovery_candidates",+ discovery_id=discovery.discovery_id,+ source="personal",+ candidates=[+ {+ "installation_id": str(item["id"]),+ "account_name": (item.get("account") or {}).get("login"),+ "account_type": (item.get("account") or {}).get("type"),+ }+ for item in installations+ if isinstance(item, dict) and item.get("id") is not None+ ],+ )+return [installationfor installation in installationsdiff --git a/posthog/api/github_callback/state.py b/posthog/api/github_callback/state.pyindex 10995f90f24a..149642229f8c 100644--- a/posthog/api/github_callback/state.py+++ b/posthog/api/github_callback/state.py@@ -44,6 +44,19 @@ def authenticated_user_id(request: Request) -> int:def store_unified_authorize_state(state: GitHubAuthorizeState, *, ttl: int | None = None) -> None:+ if state.originating_organization_id is None:+ user = User.objects.filter(pk=state.user_id).first()+ if user:+ organization_id = (+ user.teams.filter(id=state.team_id).values_list("organization_id", flat=True).first()+ if state.team_id+ else user.current_organization_id+ )+ if (+ organization_id+ and OrganizationMembership.objects.filter(user=user, organization_id=organization_id).exists()+ ):+ state = state.model_copy(update={"originating_organization_id": organization_id})timeout = ttl or GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDScache.set(unified_authorize_cache_key(state.token), state.cache_payload(), timeout=timeout)cache.set(unified_authorize_pending_cache_key(state.user_id), state.token, timeout=timeout)diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.pyindex 460ec09de697..22aaf4cab476 100644--- a/posthog/api/github_callback/team_services.py+++ b/posthog/api/github_callback/team_services.py@@ -19,8 +19,9 @@ from posthog.api.github_callback import ()from posthog.api.github_callback.install_requests import record_install_requestfrom posthog.api.github_callback.personal_state import (+ PersonalGitHubDiscovery,list_user_github_app_installations,- personal_github_login,+ usable_personal_github_credential,usable_personal_github_token,)from posthog.api.github_callback.types import (@@ -31,6 +32,7 @@ from posthog.api.github_callback.types import (is_valid_github_installation_id,)from posthog.auth import SessionAuthentication+from posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubEgressBudgetExhaustedfrom posthog.event_usage import report_user_actionfrom posthog.models import Team@@ -43,9 +45,10 @@ from posthog.models.integration import (defer_repository_cache_fields,invalidate_github_repository_caches_for_installation,)+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.organization import Organizationfrom posthog.models.user import User-from posthog.models.user_integration import user_github_integration_from_installation+from posthog.models.user_integration import UserGitHubIntegration, user_github_integration_from_installationfrom posthog.utils import is_relative_urllogger = structlog.get_logger(__name__)@@ -129,6 +132,13 @@ def link_github_installation_for_user("""if not is_valid_github_installation_id(installation_id):raise ValidationError("Invalid installation_id")+ audit = GitHubAudit(+ organization_id=Team.objects.get(pk=team_id).organization_id,+ team_id=team_id,+ user=user,+ installation_id=installation_id,+ )+ audit.record("link_started", path="oauth")try:has_access = GitHubIntegration.verify_user_installation_access(installation_id, authorization.access_token)except (requests.RequestException, GitHubEgressBudgetExhausted):@@ -138,6 +148,7 @@ def link_github_installation_for_user(user_id=user.id,exc_info=True,)+ audit.record("link_rejected", path="oauth", rejection_reason="installation_verify_failed")raise ValidationError("Failed to verify installation access", code="installation_verify_failed")if not has_access:logger.warning(@@ -145,6 +156,7 @@ def link_github_installation_for_user(installation_id=installation_id,user_id=user.id,)+ audit.record("link_rejected", path="oauth", rejection_reason="installation_access_denied")raise ValidationError("You do not have access to this GitHub installation", code="installation_access_denied")instance = GitHubIntegration.integration_from_installation_id(installation_id, team_id, user)@@ -165,8 +177,10 @@ def link_github_installation_for_user(),authorization,create_only=True,+ originating_organization_id=instance.team.organization_id,)+ audit.record("link_completed", path="oauth", linked_integration_id=instance.pk, after_commit=True)return instance@@ -214,7 +228,9 @@ GITHUB_ADOPTION_ADMIN_REQUIRED_MESSAGE = ()-def adopt_orphan_installation(*, user: User, team: Team, installation_id: str) -> Integration:+def adopt_orphan_installation(+ *, user: User, team: Team, installation_id: str, discovery_id: str | None = None+) -> Integration:"""Create the team's first ``Integration`` row for a GitHub App installation that exists onGitHub but was never linked to any PostHog team — e.g. a non-admin clicked "Connectorganization", GitHub created an install *request*, and a GitHub org admin approved it@@ -228,19 +244,22 @@ def adopt_orphan_installation(*, user: User, team: Team, installation_id: str) -GitHub org admin reaches the callback with a valid installation_id); adoption has no suchgate, so neither check here can be dropped."""+ GitHubAudit(+ organization_id=team.organization_id, team_id=team.id, user=user, installation_id=installation_id+ ).record("link_path", path="adoption", discovery_id=discovery_id)if not github_callback_state.has_team_management_access(user, team):raise ValidationError(GITHUB_ADOPTION_ADMIN_REQUIRED_MESSAGE,code="github_adoption_admin_required",)- token = usable_personal_github_token(user)- if token is None:+ credential = usable_personal_github_credential(user)+ if credential is None:raise ValidationError(PERSONAL_GITHUB_REQUIRED_MESSAGE,code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,)try:- has_access = GitHubIntegration.verify_user_installation_access(installation_id, token)+ has_access = GitHubIntegration.verify_user_installation_access(installation_id, credential.token)except (requests.RequestException, GitHubEgressBudgetExhausted):raise ValidationError("Failed to verify installation access")if not has_access:@@ -248,7 +267,7 @@ def adopt_orphan_installation(*, user: User, team: Team, installation_id: str) -instance = GitHubIntegration.integration_from_installation_id(installation_id, team.id, user)- login = personal_github_login(user)+ login = UserGitHubIntegration(credential.integration).github_loginif login:instance.config["connecting_user_github_login"] = logininstance.save(update_fields=["config"])@@ -489,6 +508,7 @@ def link_existing_team_github_integration(team_id: int,source_team_id: Any | None,installation_id_param: Any | None,+ discovery_id: str | None = None,) -> Integration:if installation_id_param and not is_valid_github_installation_id(installation_id_param):raise ValidationError("Invalid installation_id")@@ -542,7 +562,9 @@ def link_existing_team_github_integration(target_team = organization.teams.filter(id=team_id).first()if target_team is None:raise ValidationError("Target team not found in your organization")- return adopt_orphan_installation(user=user, team=target_team, installation_id=installation_id_str)+ return adopt_orphan_installation(+ user=user, team=target_team, installation_id=installation_id_str, discovery_id=discovery_id+ )source = existingelse:# No source specified: auto-resolve the org's existing GitHub installation. This backs the@@ -583,6 +605,9 @@ def link_existing_team_github_integration(target_team = organization.teams.filter(id=team_id).first()if target_team is None:raise ValidationError("Target team not found in your organization")+ GitHubAudit(+ organization_id=organization.id, team_id=team_id, user=user, installation_id=str(installation_id)+ ).record("link_path", path="sibling", source_team_id=source.team_id, discovery_id=discovery_id)authorize_link_existing_installation(user=user, team=target_team, source_installation_id=str(installation_id))instance = GitHubIntegration.integration_from_installation_id(str(installation_id), team_id, user)@@ -595,11 +620,34 @@ def link_existing_team_github_integration(return instance+@frozen+class _InstallationAccount:+ name: str | None+ type: str | None+++def _sibling_installation_account(integration: Integration) -> _InstallationAccount:+ """Account to show for an installation a project in the organization already has.++ The name must be the GitHub account the app is installed on, never the login of the person who+ connected it: a reader who sees a colleague's handle where an account belongs reads it as a+ stranger's account in their settings. Missing names use the installation ID fallback so discovery+ does not wait for a GitHub metadata request for each sibling installation.+ """+ github_integration = GitHubIntegration(integration)+ account = (integration.config or {}).get("account") or {}+ name = account.get("name")+ if not name or str(name) == str(github_integration.github_installation_id):+ return _InstallationAccount(name=None, type=account.get("type"))+ return _InstallationAccount(name=str(name), type=account.get("type"))++def list_org_github_installations(*,user: User,organization: Organization,exclude_team_id: int | None = None,+ discovery: PersonalGitHubDiscovery | None = None,) -> list[dict[str, Any]]:"""List the distinct GitHub App installations ``user`` can link to a project in ``organization``.@@ -621,13 +669,14 @@ def list_org_github_installations("""accessible_team_ids = _accessible_org_team_ids(user, organization)org_github = defer_repository_cache_fields(- Integration.objects.filter(team__organization_id=organization.id, kind="github")+ Integration.objects.filter(team__organization_id=organization.id, kind="github").select_related("team")).order_by("id")# One pass over the org's rows yields both the sibling entries and the org-wide linked set the# adoption merge below excludes against, instead of two near-identical queries.installations: dict[str, dict[str, Any]] = {}org_linked_installation_ids: set[str] = set()+ filtered: list[dict[str, str]] = []for integration in org_github:config = integration.config or {}raw_installation_id = config.get("installation_id")@@ -636,24 +685,40 @@ def list_org_github_installations(installation_id = str(raw_installation_id)org_linked_installation_ids.add(installation_id)if integration.team_id not in accessible_team_ids or integration.team_id == exclude_team_id:+ filtered.append(+ {+ "installation_id": installation_id,+ "source": "sibling",+ "reason": "current_project" if integration.team_id == exclude_team_id else "inaccessible_project",+ }+ )continueif installation_id in installations:+ filtered.append(+ {"installation_id": installation_id, "source": "sibling", "reason": "duplicate_installation"}+ )continue- account = config.get("account") or {}+ sibling_account = _sibling_installation_account(integration)installations[installation_id] = {"installation_id": installation_id,- "account_name": account.get("name") or config.get("connecting_user_github_login"),- "account_type": account.get("type"),+ "account_name": sibling_account.name,+ "account_type": sibling_account.type,"source_team_id": integration.team_id,+ "source_team_name": integration.team.name,}- personal_installations = list_user_github_app_installations(user)+ personal_installations = (+ list_user_github_app_installations(user, discovery) if discovery else list_user_github_app_installations(user)+ )for raw_installation in personal_installations or []:installation_id = str(raw_installation.get("id"))# Skip anything already linked in the org, even to a project this user can't access — those# aren't orphans, and offering them here would advertise an adoption that link_existing then# has to refuse.if installation_id in installations or installation_id in org_linked_installation_ids:+ filtered.append(+ {"installation_id": installation_id, "source": "personal", "reason": "already_linked_in_organization"}+ )continueaccount = raw_installation.get("account") or {}installations[installation_id] = {@@ -661,8 +726,12 @@ def list_org_github_installations("account_name": account.get("login"),"account_type": account.get("type"),"source_team_id": None,+ "source_team_name": None,}+ # One record per request keeps repeated discovery refreshes from writing a row per filtered installation.+ if discovery and filtered:+ discovery.audit.record("discovery_candidates_filtered", discovery_id=discovery.discovery_id, filtered=filtered)return list(installations.values())diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.pyindex 04394881668d..1a581dc0811f 100644--- a/posthog/api/github_callback/types.py+++ b/posthog/api/github_callback/types.py@@ -4,6 +4,7 @@ import refrom enum import StrEnumfrom typing import Any, Literal, Selffrom urllib.parse import parse_qsl, urlencode, urlparse+from uuid import UUID, uuid4from django.conf import settings@@ -90,6 +91,8 @@ class GitHubAuthorizeState(BaseModel):model_config = ConfigDict(frozen=True, extra="ignore")token: str+ flow_id: UUID = Field(default_factory=uuid4)+ originating_organization_id: UUID | None = Noneflow: FlowKinduser_id: intteam_id: int | None = Nonediff --git a/posthog/api/github_callback/views.py b/posthog/api/github_callback/views.pyindex 3c214e096e83..c31b88583a69 100644--- a/posthog/api/github_callback/views.py+++ b/posthog/api/github_callback/views.py@@ -1,12 +1,16 @@from typing import Literal, cast+from uuid import uuid4from django.http import HttpRequest, HttpResponseRedirectfrom django.views.decorators.http import require_http_methods+from rest_framework.exceptions import ValidationError+from posthog.api.github_callback import personal_finish, redirects, state, team_servicesfrom posthog.api.github_callback.types import CallbackContext, FinishResult, FlowKind, is_personal_github_setup_statefrom posthog.auth import session_auth_requiredfrom posthog.models import User+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user_integration import UserIntegrationfrom posthog.views import login_required@@ -116,12 +120,44 @@ def _finish(http_request: HttpRequest, ctx: CallbackContext) -> FinishResult:return team_services.finish_team_setup(http_request)+def _audit_finish_failure(request: HttpRequest, ctx: CallbackContext, result: FinishResult) -> None:+ if not result.error:+ return+ origin = ctx.authorize_state+ GitHubAudit(+ organization_id=origin.originating_organization_id if origin else None, user=cast(User, request.user)+ ).record(+ "setup_failed",+ flow_id=str(origin.flow_id if origin else uuid4()),+ callback_type=ctx.entry,+ failure_category=result.error,+ )+++def _finish_with_audit(request: HttpRequest, ctx: CallbackContext) -> FinishResult:+ try:+ result = _finish(request, ctx)+ except ValidationError as exc:+ origin = ctx.authorize_state+ GitHubAudit(+ organization_id=origin.originating_organization_id if origin else None, user=cast(User, request.user)+ ).record(+ "setup_failed",+ flow_id=str(origin.flow_id if origin else uuid4()),+ callback_type=ctx.entry,+ failure_category=exc.get_codes(),+ )+ raise+ _audit_finish_failure(request, ctx, result)+ return result++@require_http_methods(["GET"])@login_requireddef github_setup_callback(request: HttpRequest) -> HttpResponseRedirect:"""GitHub App Setup URL — team finish or personal install."""ctx = _parse_callback(request, "setup_url")- result = _finish(request, ctx)+ result = _finish_with_audit(request, ctx)return redirects.redirect_from_finish_result(result)@@ -130,5 +166,5 @@ def github_setup_callback(request: HttpRequest) -> HttpResponseRedirect:def github_oauth_callback(request: HttpRequest) -> HttpResponseRedirect:"""GitHub User OAuth redirect_uri — personal and team-oauth recovery flows."""ctx = _parse_callback(request, "oauth_redirect")- result = _finish(request, ctx)+ result = _finish_with_audit(request, ctx)return redirects.redirect_from_finish_result(result)diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex 97ddf17a91ad..94974ce85e7f 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -5,10 +5,11 @@ import timefrom collections.abc import Iterablefrom typing import Any, NoReturn, Protocol, castfrom urllib.parse import urlencode+from uuid import uuid4from django.conf import settingsfrom django.core.cache import cache, caches-from django.db import transaction+from django.db import models, transactionfrom django.db.models import Q, QuerySetfrom django.http import HttpResponsefrom django.shortcuts import redirect@@ -31,7 +32,7 @@ from rest_framework.views import APIViewfrom slack_sdk.errors import SlackApiErrorfrom posthog.api.github_callback import state as github_callback_state-from posthog.api.github_callback.personal_state import user_has_personal_github_integration+from posthog.api.github_callback.personal_state import PersonalGitHubDiscovery, user_has_personal_github_integrationfrom posthog.api.github_callback.team_services import (build_team_oauth_authorize_url,create_team_github_integration_from_oauth_code,@@ -102,6 +103,7 @@ from posthog.models.integration import (defer_repository_cache_fields,resolve_aliased_oauth_kind,)+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user_integration import UserIntegrationfrom posthog.permissions import (AccessControlPermission,@@ -1144,6 +1146,9 @@ class GitHubPrepareCallbackRequestSerializer(serializers.Serializer):class GitHubLinkExistingRequestSerializer(serializers.Serializer):+ discovery_id = serializers.UUIDField(+ required=False, allow_null=True, help_text="Discovery response ID for diagnostics only; grants no authority."+ )source_team_id = serializers.IntegerField(required=False,allow_null=True,@@ -1152,6 +1157,7 @@ class GitHubLinkExistingRequestSerializer(serializers.Serializer):installation_id = serializers.CharField(required=False,allow_blank=True,+ allow_null=True,help_text="GitHub installation ID to link; resolved within the organization when source_team_id is omitted.",)@@ -1174,9 +1180,29 @@ class GitHubAvailableInstallationSerializer(serializers.Serializer):"Null when the installation isn't linked to any project yet — it was found via the user's ""personal GitHub link and can be adopted by linking it here.",)+ source_team_name = serializers.CharField(+ allow_null=True,+ help_text="Name of the project in source_team_id, so the picker can say where the "+ "installation comes from. Null for an installation no project has linked yet.",+ )+++class GitHubPersonalDiscoveryStatus(models.TextChoices):+ OK = "ok"+ NOT_CONNECTED = "not_connected"+ UNAVAILABLE = "unavailable"class GitHubAvailableInstallationsResponseSerializer(serializers.Serializer):+ discovery_id = serializers.UUIDField(help_text="Correlation ID for this discovery response.")+ discovered_at = serializers.DateTimeField(help_text="Time this discovery completed.")+ personal_github_login = serializers.CharField(+ allow_null=True, help_text="GitHub identity of the credential used for personal discovery."+ )+ personal_discovery_status = serializers.ChoiceField(+ choices=GitHubPersonalDiscoveryStatus.choices,+ help_text="Whether personal discovery succeeded, has no connection, or is unavailable.",+ )installations = GitHubAvailableInstallationSerializer(many=True,help_text="GitHub installations available to link to this project: the organization's "@@ -1403,6 +1429,9 @@ class IntegrationViewSet(pass # kind not configured on this instanceexcept Exception as e:capture_exception(e)+ github_audit = (+ GitHubAudit.project(instance, cast(User, self.request.user)) if instance.kind == "github" else None+ )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:@@ -1413,18 +1442,42 @@ class IntegrationViewSet(.exclude(id=instance.id).exists())+ assert github_audit is not None+ github_audit.record("disconnect_started", last_reference=is_last_team_reference)+ if not is_last_team_reference:+ github_audit.record("uninstall_completed", outcome="skipped", reason="other_project_references")if is_last_team_reference:try:- GitHubIntegration.uninstall_app_installation(instance.integration_id)+ outcome = GitHubIntegration.uninstall_app_installation_status(instance.integration_id)+ github_audit.record("uninstall_completed", outcome=outcome)except Exception as e:capture_exception(e)+ github_audit.record("uninstall_completed", outcome="failed", failure_type=type(e).__name__)# 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()+ personal_rows = list(+ UserIntegration.objects.filter(kind="github", integration_id=instance.integration_id)+ )+ personal_audits = [+ GitHubAudit.personal(row, cast(User, self.request.user)) for row in personal_rows+ ]+ UserIntegration.objects.filter(pk__in=[row.pk for row in personal_rows]).delete()+ for personal_audit in personal_audits:+ personal_audit.record(+ "credential_deleted", after_commit=True, reason="last_project_disconnected"+ )except Exception as e:capture_exception(e)+ github_audit.record("personal_cleanup_failed", failure_type=type(e).__name__)- super().perform_destroy(instance)+ try:+ super().perform_destroy(instance)+ except Exception as exc:+ if github_audit:+ github_audit.record("disconnect_failed", stage="project_deletion", failure_type=type(exc).__name__)+ raise+ if github_audit:+ github_audit.record("deleted", after_commit=True, customer_visible=True, outcome="disconnected")@action(methods=["GET"], detail=False)def authorize(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:@@ -2110,17 +2163,26 @@ class IntegrationViewSet(PostHog's callback, which ``github/link_existing`` can adopt."""user = cast(User, request.user)+ discovery = PersonalGitHubDiscovery(+ audit=GitHubAudit(organization_id=self.organization.id, team_id=self.team_id, user=user),+ discovery_id=str(uuid4()),+ )installations = list_org_github_installations(user=user,organization=self.organization,exclude_team_id=self.team_id,+ discovery=discovery,)- return Response(- {- "installations": GitHubAvailableInstallationSerializer(installations, many=True).data,- "personal_github_connected": user_has_personal_github_integration(user),- }- )+ payload = {+ "installations": GitHubAvailableInstallationSerializer(installations, many=True).data,+ "personal_github_connected": user_has_personal_github_integration(user),+ "personal_github_login": discovery.login,+ "personal_discovery_status": discovery.status,+ "discovery_id": discovery.discovery_id,+ "discovered_at": timezone.now().isoformat(),+ }+ discovery.audit.record("discovery_completed", discovery_id=discovery.discovery_id, response=payload)+ return Response(payload, headers={"Cache-Control": "private, no-store"})@extend_schema(request=GitHubLinkExistingRequestSerializer,@@ -2129,12 +2191,41 @@ class IntegrationViewSet(@action(methods=["POST"], detail=False, url_path="github/link_existing")def github_link_existing(self, request: Request, *args: Any, **kwargs: Any) -> Response:"""Reuse a GitHub installation already linked to a sibling team in the same organization."""- instance = link_existing_team_github_integration(- user=cast(User, request.user),- organization=self.organization,- team_id=self.team_id,- source_team_id=request.data.get("source_team_id"),- installation_id_param=request.data.get("installation_id"),+ serializer = GitHubLinkExistingRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ discovery_id = str(serializer.validated_data.get("discovery_id") or "")+ audit = GitHubAudit(organization_id=self.organization.id, team_id=self.team_id, user=cast(User, request.user))+ selected_id = serializer.validated_data.get("installation_id")+ selected_id = selected_id if is_valid_github_installation_id(selected_id) else None+ audit.record("link_started", discovery_id=discovery_id, installation_id=selected_id)+ try:+ instance = link_existing_team_github_integration(+ user=cast(User, request.user),+ organization=self.organization,+ team_id=self.team_id,+ source_team_id=serializer.validated_data.get("source_team_id"),+ installation_id_param=serializer.validated_data.get("installation_id"),+ discovery_id=discovery_id,+ )+ except ValidationError as exc:+ audit.record(+ "link_rejected",+ discovery_id=discovery_id,+ installation_id=selected_id,+ rejection_reason=exc.get_codes(),+ )+ raise+ except Exception as exc:+ audit.record(+ "link_failed", discovery_id=discovery_id, installation_id=selected_id, failure_type=type(exc).__name__+ )+ raise+ audit.record(+ "link_completed",+ discovery_id=discovery_id,+ installation_id=instance.integration_id,+ linked_integration_id=instance.pk,+ after_commit=True,)return Response(self.get_serializer(instance).data)diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.pyindex 5a55a3597976..c196c47a26fb 100644--- a/posthog/api/test/test_github_installation_webhook.py+++ b/posthog/api/test/test_github_installation_webhook.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.test import APIClient+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.organization import Organization@@ -74,27 +75,32 @@ class TestGitHubInstallationReferenceHelpers(TestCase):@parameterized.expand([- ("removed_204", 204, True),- ("already_gone_404", 404, True),- ("unexpected_500", 500, False),+ ("removed_204", 204, True, "uninstalled"),+ ("already_gone_404", 404, True, "already_absent"),+ ("unexpected_500", 500, False, "failed"),])@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):+ def test_uninstall_app_installation_status_handling(+ self, _name, status_code, expected, expected_status, 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)+ self.assertEqual(GitHubIntegration.uninstall_app_installation_status("12345"), expected_status)@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"))+ self.assertEqual(GitHubIntegration.uninstall_app_installation_status("12345"), "failed")@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"))+ self.assertEqual(GitHubIntegration.uninstall_app_installation_status("12345"), "skipped")@patch("posthog.models.integration.github.GitHubIntegration.uninstall_app_installation")def test_uninstall_if_last_reference_skips_when_references_remain(self, mock_uninstall):@@ -143,10 +149,16 @@ class TestGitHubInstallationWebhook(TestCase):@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")+ integration = self._team_integration("12345")+ integration_id = str(integration.pk)self._user_integration("12345")- response = self._post({"action": "deleted", "installation": {"id": 12345}})+ with self.captureOnCommitCallbacks(execute=True):+ response = self._post({"action": "deleted", "installation": {"id": 12345}})+ log = ActivityLog.objects.get(item_id=integration_id, activity="deleted")+ self.assertEqual(log.team_id, self.team.id)+ assert log.detail is not None+ self.assertEqual(log.detail["trigger"]["payload"]["outcome"], "disconnected")self.assertEqual(response.status_code, 202)self.assertFalse(Integration.objects.filter(kind="github", integration_id="12345").exists())diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 8aa6beb10f03..c61267b198c3 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -7,6 +7,7 @@ from typing import Any, castfrom urllib.parse import quote, urlencodeimport pytest+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import ANY, MagicMock, patch@@ -41,6 +42,7 @@ from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeStatefrom posthog.api.integration import IntegrationSerializer, IntegrationViewSetfrom posthog.constants import AvailableFeaturefrom posthog.egress.github.transport import GitHubEgressBudgetExhausted+from posthog.models.activity_logging.activity_log import ActivityLog, apply_activity_visibility_restrictionsfrom posthog.models.integration import (ERROR_TOKEN_REFRESH_FAILED,GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,@@ -57,12 +59,18 @@ from posthog.models.integration import (StripeIntegration,github_account_type,)+from posthog.models.integration.github_audit import GitHubAudit, GitHubAuditPayloadfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom 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 GitHubInstallRequest, UserIntegration+from posthog.models.user_integration import (+ GitHubInstallRequest,+ ReauthorizationRequired,+ UserGitHubIntegration,+ UserIntegration,+)from posthog.models.utils import hash_key_valuefrom posthog.rate_limit import GitHubRepositoryRefreshThrottlefrom posthog.team_notifications.slack import is_shared_channel@@ -4344,6 +4352,34 @@ class TestGitHubTeamIntegrationComplete:assert installations[0]["account_name"] == "acme"assert installations[0]["account_type"] == "Organization"assert installations[0]["source_team_id"] == first.pk+ assert installations[0]["source_team_name"] == "Org Project"++ @parameterized.expand([("missing", None), ("placeholder", "111")])+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_list_org_github_installations_uses_id_fallback_without_fetching_names(+ self, _name, account_name, mock_client_request+ ):+ sibling = Team.objects.create(organization=self.organization, name="Org Project")+ Integration.objects.create(+ team=sibling,+ kind="github",+ integration_id="111",+ config={+ "installation_id": "111",+ "account": {"name": account_name, "type": "Organization"},+ "connecting_user_github_login": "synthetic-connector",+ },+ sensitive_config={"access_token": "synthetic-installation-token"},+ )++ installations = list_org_github_installations(+ user=self.user, organization=self.organization, exclude_team_id=self.team.pk+ )++ assert installations[0]["account_name"] is None+ assert installations[0]["account_type"] == "Organization"+ assert installations[0]["source_team_name"] == "Org Project"+ mock_client_request.assert_not_called()def _org_member_with_access_control(self) -> User:self.organization.available_product_features = [@@ -4707,6 +4743,7 @@ class TestGitHubTeamIntegrationComplete:assert set(by_id.keys()) == {"111", "222"}assert by_id["111"]["source_team_id"] == sibling.team_idassert by_id["222"]["source_team_id"] is None+ assert by_id["222"]["source_team_name"] is Noneassert by_id["222"]["account_name"] == "coderabbitai"assert by_id["222"]["account_type"] == "Organization"@@ -6458,11 +6495,11 @@ class TestGitHubIntegrationUninstall:created_by=self.user,)- @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation")+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation_status")def test_destroy_github_uninstalls_and_cleans_up_personal_when_last_team_reference(self, mock_uninstall, client: HttpClient):- mock_uninstall.return_value = True+ mock_uninstall.return_value = "uninstalled"integration = self._create_github_integration("12345")personal = UserIntegration.objects.create(user=self.user, kind="github", integration_id="12345", config={}, sensitive_config={}@@ -6477,7 +6514,7 @@ class TestGitHubIntegrationUninstall:# 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")+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation_status")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")@@ -6498,7 +6535,7 @@ class TestGitHubIntegrationUninstall:assert UserIntegration.objects.filter(id=personal.id).exists()@patch(- "posthog.api.integration.GitHubIntegration.uninstall_app_installation",+ "posthog.api.integration.GitHubIntegration.uninstall_app_installation_status",side_effect=Exception("GitHub API error"),)def test_destroy_github_still_deletes_when_uninstall_fails(self, _mock_uninstall, client: HttpClient):@@ -6510,12 +6547,13 @@ class TestGitHubIntegrationUninstall:assert response.status_code == status.HTTP_204_NO_CONTENTassert not Integration.objects.filter(id=integration.id).exists()- @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation")+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation_status")@patch("posthog.api.integration.count_in_progress_runs_for_github_integration")def test_destroy_github_blocked_while_background_agent_runs_in_progress(self, mock_count, _mock_uninstall, client: HttpClient):integration = self._create_github_integration("12345")+ _mock_uninstall.return_value = "uninstalled"mock_count.return_value = 2client.force_login(self.user)@@ -7273,3 +7311,204 @@ class TestIntegrationSerializerFilesWriteRequestable(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["files_write_requestable"] is expected+++@time_machine.travel("2026-01-15T12:00:00Z", tick=False)+class TestGitHubDiscoveryAudit(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization.memberships.filter(user=self.user).update(level=OrganizationMembership.Level.ADMIN)++ @patch("posthog.api.github_callback.personal_state.github_request")+ def test_discovery_records_the_usable_credential_and_keeps_siblings_on_failure(+ self, github_request_mock: MagicMock+ ) -> None:+ older = UserIntegration.objects.create(+ user=self.user,+ kind="github",+ integration_id="9001",+ config={"github_user": {"login": "synthetic-reader", "id": 101}, "credential_version": "version-a"},+ sensitive_config={"user_access_token": "synthetic-private-token"},+ )+ UserIntegration.objects.create(+ user=self.user,+ kind="github",+ integration_id="9002",+ config={},+ sensitive_config={"access_token": "synthetic-unusable-token"},+ )+ sibling = Team.objects.create(organization=self.organization, name="Synthetic project")+ Integration.objects.create(+ team=sibling,+ kind="github",+ integration_id="9003",+ config={"installation_id": "9003", "account": {"name": "synthetic-owner"}},+ )+ github_request_mock.return_value = MagicMock(+ status_code=200,+ headers={"X-GitHub-Request-Id": "synthetic-request"},+ json=lambda: {+ "installations": [{"id": 9004, "account": {"login": "synthetic-external", "type": "Organization"}}]+ },+ )+ with capture_logs() as captured:+ response = self.client.get(f"/api/projects/{self.team.id}/integrations/github/available_installations/")+ assert response.status_code == 200+ assert response["Cache-Control"] == "private, no-store"+ assert response.json()["personal_github_login"] == "synthetic-reader"+ assert response.json()["personal_discovery_status"] == "ok"+ assert not ActivityLog.objects.filter(activity="github_diagnostic").exists()+ selected = next(entry for entry in captured if entry["event"] == "discovery_credential_selected")+ assert selected["personal_integration_id"] == str(older.pk)+ assert "synthetic-private-token" not in json.dumps(captured, default=str)+ completed = next(entry for entry in captured if entry["event"] == "discovery_completed")+ assert completed["response"] == {+ **response.json(),+ "installation_count": len(response.json()["installations"]),+ }+ github_request_mock.return_value.status_code = 503+ response = self.client.get(f"/api/projects/{self.team.id}/integrations/github/available_installations/")+ assert response.json()["personal_discovery_status"] == "unavailable"+ assert [row["installation_id"] for row in response.json()["installations"]] == ["9003"]+ older.config["user_refresh_token_expires_at"] = 1+ older.save(update_fields=["config"])+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.get(f"/api/projects/{self.team.id}/integrations/github/available_installations/")+ assert response.json()["personal_github_connected"] is False+ assert response.json()["personal_discovery_status"] == "not_connected"+ assert [row["installation_id"] for row in response.json()["installations"]] == ["9003"]++ @parameterized.expand([("uninstalled",), ("already_absent",), ("skipped",), ("failed",)])+ @patch("posthog.api.integration.GitHubIntegration.uninstall_app_installation_status")+ @patch("posthog.models.integration.github.GitHubIntegration.fetch_installation_access")+ def test_connection_history_survives_disconnect_without_exposing_diagnostics(+ self, outcome: str, fetch: MagicMock, uninstall: MagicMock+ ) -> None:+ fetch.return_value = GitHubInstallationAccess(+ installation_id="9005",+ installation_info={"account": {"login": "synthetic-owner", "type": "Organization"}},+ access_token="synthetic-installation-secret",+ token_expires_at=(timezone.now() + timedelta(hours=1)).isoformat(),+ repository_selection="selected",+ )+ uninstall.return_value = outcome+ with self.captureOnCommitCallbacks(execute=True):+ integration = GitHubIntegration.integration_from_installation_id("9005", self.team.id, self.user)+ integration_id = integration.pk+ target = Team.objects.create(organization=self.organization, name="Synthetic target")+ discovered = self.client.get(f"/api/projects/{target.id}/integrations/github/available_installations/")+ assert [item["installation_id"] for item in discovered.json()["installations"]] == ["9005"]+ with self.captureOnCommitCallbacks(execute=True), capture_logs() as diagnostic_logs:+ response = self.client.delete(f"/api/projects/{self.team.id}/integrations/{integration_id}/")+ assert response.status_code == 204+ assert not Integration.objects.filter(pk=integration_id).exists()+ logs = ActivityLog.objects.filter(scope="Integration", item_id=str(integration_id))+ assert set(logs.values_list("activity", flat=True)) == {"created", "deleted", "github_diagnostic"}+ uninstall_log = next(+ log for log in logs if log.detail and log.detail["trigger"]["payload"]["event"] == "uninstall_completed"+ )+ assert uninstall_log.detail is not None+ assert uninstall_log.detail["trigger"]["payload"]["outcome"] == outcome+ assert "synthetic-installation-secret" not in json.dumps([log.detail for log in logs])+ assert "synthetic-installation-secret" not in json.dumps(diagnostic_logs, default=str)+ self.user.is_staff = False+ assert set(apply_activity_visibility_restrictions(logs, self.user).values_list("activity", flat=True)) == {+ "created",+ "deleted",+ }+ self.user.is_staff = True+ assert apply_activity_visibility_restrictions(logs, self.user).count() == logs.count()+ refreshed = self.client.get(f"/api/projects/{target.id}/integrations/github/available_installations/")+ assert refreshed.json()["installations"] == []++ @patch("posthog.cdp.internal_events.produce_internal_event")+ def test_invalid_credential_discard_is_private_and_retained(self, produce: MagicMock) -> None:+ integration = UserIntegration.objects.create(+ user=self.user,+ kind="github",+ integration_id="9006",+ config={+ "originating_organization_id": str(self.organization.id),+ "github_user": {"id": 101, "login": "synthetic-reader"},+ "user_refresh_token_expires_at": 1,+ },+ sensitive_config={"user_access_token": "synthetic-private-secret"},+ )+ integration_id = str(integration.pk)+ with self.captureOnCommitCallbacks(execute=True):+ with self.assertRaises(ReauthorizationRequired):+ UserGitHubIntegration(integration).get_usable_user_access_token()+ log = ActivityLog.objects.get(item_id=integration_id, activity="github_diagnostic")+ assert log.team_id is None+ assert log.organization_id == self.organization.id+ assert log.detail is not None+ assert log.detail["trigger"]["payload"]["event"] == "credential_deleted"+ assert not UserIntegration.objects.filter(pk=integration_id).exists()+ assert "synthetic-private-secret" not in json.dumps(log.detail)+ produce.assert_not_called()++ 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:+ GitHubAudit(organization_id=self.organization.id, team_id=self.team.id).record(+ "discovery_completed",+ discovery_id="synthetic-discovery",+ token="synthetic-secret",+ response={+ "discovery_id": "synthetic-discovery",+ "installations": [candidate],+ "headers": {"authorization": "synthetic-secret"},+ "config": {"token": "synthetic-secret"},+ },+ )+ completed = next(entry for entry in captured if entry["event"] == "discovery_completed")+ assert completed["response"]["installations"] == [+ {"installation_id": "9007", "account_name": "synthetic-owner"}+ ]+ assert "synthetic-secret" not in json.dumps(captured, default=str)++ @parameterized.expand([("discovery_completed",), ("discovery_candidates_filtered",)])+ def test_github_audit_caps_recorded_installations(self, event: str) -> None:+ entries = [+ {"installation_id": str(9100 + index), "source": "sibling"}+ for index in range(GitHubAuditPayload.MAX_RECORDED_INSTALLATIONS + 5)+ ]+ evidence = {"response": {"installations": entries}} if event == "discovery_completed" else {"filtered": entries}+ with capture_logs() as captured:+ GitHubAudit(organization_id=self.organization.id, team_id=self.team.id).record(+ event, discovery_id="synthetic-discovery", **evidence+ )+ payload = next(entry for entry in captured if entry["event"] == event)+ if event == "discovery_completed":+ count, recorded = payload["response"]["installation_count"], payload["response"]["installations"]+ expected = [{"installation_id": entry["installation_id"]} for entry in entries]+ else:+ count, recorded = payload["filtered_count"], payload["filtered"]+ expected = entries+ assert count == len(entries)+ assert recorded == expected[: GitHubAuditPayload.MAX_RECORDED_INSTALLATIONS]++ def test_discovery_logs_filtered_installations_once(self) -> None:+ for installation_id in ("9201", "9202", "9203"):+ Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id=installation_id,+ config={"installation_id": installation_id, "account": {"name": "synthetic-owner"}},+ )+ with capture_logs() as captured:+ response = self.client.get(f"/api/projects/{self.team.id}/integrations/github/available_installations/")+ assert response.status_code == 200+ filtered_logs = [entry for entry in captured if entry["event"] == "discovery_candidates_filtered"]+ assert len(filtered_logs) == 1+ payload = filtered_logs[0]+ assert payload["filtered_count"] == 3+ assert {entry["reason"] for entry in payload["filtered"]} == {"current_project"}++ @parameterized.expand([({},), ({"installation_id": None},)])+ @patch("posthog.api.integration.link_existing_team_github_integration")+ def test_link_accepts_omitted_or_null_installation_id(self, payload: dict, link: MagicMock) -> None:+ link.return_value = Integration.objects.create(team=self.team, kind="github", integration_id="9008")+ response = self.client.post(f"/api/projects/{self.team.id}/integrations/github/link_existing/", payload)+ assert response.status_code == 200+ assert link.call_args.kwargs["installation_id_param"] is Nonediff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex 5138dda4c2d2..df55d11054fd 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -16,7 +16,7 @@ from posthog.api.github_callback.state import (store_unified_authorize_state,)from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState-from posthog.models import OrganizationMembership, Team, User+from posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.models.integration import (GitHubInstallationAccess,GitHubIntegrationError,@@ -36,6 +36,7 @@ def _authorization(gh_id: int = 99, gh_login: str = "octocat") -> GitHubUserAuthreturn GitHubUserAuthorization(gh_id=gh_id,gh_login=gh_login,+ identity_verified_at=123,access_token="gho_access",refresh_token="ghr_refresh",access_token_expires_in=28800,@@ -296,9 +297,9 @@ 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")+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation_status")def test_delete_last_reference_calls_github_uninstall(self, mock_uninstall):- mock_uninstall.return_value = True+ mock_uninstall.return_value = "uninstalled"_create_user_integration(self.user, integration_id="12345")response = self.client.delete("/api/users/@me/integrations/github/12345/")@@ -307,7 +308,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):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")+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation_status")def test_delete_skips_uninstall_when_team_reference_exists(self, mock_uninstall):_create_user_integration(self.user, integration_id="12345")Integration.objects.create(@@ -320,7 +321,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):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")+ @patch("posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation_status")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")@@ -332,16 +333,17 @@ class TestUserIntegrationEndpoints(APIBaseTest):mock_uninstall.assert_not_called()@patch(- "posthog.api.user_integration.UserGitHubIntegration.uninstall_if_last_reference",+ "posthog.api.user_integration.UserGitHubIntegration.uninstall_app_installation_status",side_effect=Exception("GitHub API error"),)- def test_delete_still_returns_204_when_uninstall_fails(self, _mock_uninstall):+ 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())+ mock_uninstall.assert_called_once_with("12345")@override_settings(GITHUB_APP_CLIENT_ID="client_id")@patch(@@ -451,6 +453,33 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(data.get("connect_flow"), "app_install")self.assertIn("github.com/apps/posthog-dev/installations/new", data["install_url"])+ @parameterized.expand([("oauth_discover", "posthog_code"), ("app_install", None)])+ @override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")+ @patch("posthog.api.user_integration._has_unlinked_github_installations", return_value=None)+ @patch(+ "posthog.api.github_callback.types.get_instance_settings",+ return_value={"GITHUB_APP_SLUG": "posthog-dev"},+ )+ def test_github_start_records_the_selected_project_organization(+ self, expected_flow, connect_from, _mock_settings, _mock_unlinked+ ):+ other_org = Organization.objects.create(name="Synthetic other organization")+ OrganizationMembership.objects.create(organization=other_org, user=self.user)+ self.user.current_organization = other_org+ self.user.save(update_fields=["current_organization"])++ body = {"team_id": self.team.id, **({"connect_from": connect_from} if connect_from else {})}+ response = self.client.post("/api/users/@me/integrations/github/start/", body, content_type="application/json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["connect_flow"], expected_flow)+ state = parse_qs(urlparse(response.json()["install_url"]).query)["state"][0]+ token, _ = parse_github_authorize_state_param(state)+ assert token is not None+ stored = load_authorize_state(token, user_id=self.user.id)+ assert stored is not None+ assert stored.originating_organization_id == self.organization.id+@override_settings(GITHUB_APP_CLIENT_ID="gh_client_123")@patch("posthog.api.user_integration._has_unlinked_github_installations", return_value=False)@patch(@@ -669,14 +698,17 @@ class TestUserIntegrationEndpoints(APIBaseTest):)state = "tok_oauth_discover_empty"- store_unified_authorize_state(- GitHubAuthorizeState(- token=state,- flow=FlowKind.OAUTH_DISCOVER,- user_id=self.user.id,- connect_from="posthog_code",- ),- )+ origin = GitHubAuthorizeState(+ token=state,+ flow=FlowKind.OAUTH_DISCOVER,+ user_id=self.user.id,+ connect_from="posthog_code",+ )+ store_unified_authorize_state(origin)+ other_org = Organization.objects.create(name="Synthetic other organization")+ OrganizationMembership.objects.create(organization=other_org, user=self.user)+ self.user.current_organization = other_org+ self.user.save(update_fields=["current_organization"])response = self.client.get("/complete/github-link/",@@ -686,6 +718,14 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertEqual(response.status_code, 302)self.assertIn("github.com/apps/posthog-dev/installations/new", response["Location"])+ next_state = parse_qs(urlparse(response["Location"]).query)["state"][0]+ next_token, _ = parse_github_authorize_state_param(next_state)+ assert next_token is not None+ resumed = load_authorize_state(next_token, user_id=self.user.id)+ assert resumed is not None+ assert resumed.originating_organization_id == self.organization.id+ assert resumed.flow_id == origin.flow_id+@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.github.GitHubIntegration.client_request")@@ -1078,10 +1118,12 @@ class TestUserGitHubIntegration(APIBaseTest):}mock_post.return_value = mock_response- gh = self._make_integration()+ gh = self._make_integration(credential_version="synthetic-old-version", identity_verified_at=123)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")@@ -1196,6 +1238,7 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):self.assertEqual(integration.sensitive_config["access_token"], "ghs_install")self.assertEqual(integration.sensitive_config["user_access_token"], "gho_access")self.assertEqual(integration.sensitive_config["user_refresh_token"], "ghr_refresh")+ self.assertEqual(integration.config["identity_verified_at"], 123)def test_different_installation_creates_second_integration(self):_create_user_integration(self.user)@@ -1222,8 +1265,17 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):self.assertEqual(integration.integration_id, "67890")self.assertEqual(integration.sensitive_config["user_access_token"], "gho_new")- def test_same_installation_updates_existing_integration(self):- _create_user_integration(self.user, integration_id="12345")+ @parameterized.expand(+ [+ ("relink_without_organization_keeps_stored", False, "stored"),+ ("relink_with_organization_replaces_stored", True, "new"),+ ]+ )+ def test_same_installation_updates_existing_integration(self, _name, relink_with_organization, expected):+ stored_organization = Organization.objects.create(name="Synthetic stored organization")+ existing = _create_user_integration(self.user, integration_id="12345")+ existing.config["originating_organization_id"] = str(stored_organization.id)+ existing.save(update_fields=["config"])integration = user_github_integration_from_installation(self.user,GitHubInstallationAccess(@@ -1241,11 +1293,14 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):access_token_expires_in=28800,refresh_token_expires_in=15897600,),+ originating_organization_id=self.organization.id if relink_with_organization else None,)self.assertEqual(UserIntegration.objects.filter(user=self.user, kind="github").count(), 1)self.assertEqual(integration.integration_id, "12345")self.assertEqual(integration.sensitive_config["user_access_token"], "gho_refreshed")+ expected_organization = stored_organization if expected == "stored" else self.organization+ self.assertEqual(integration.config["originating_organization_id"], str(expected_organization.id))@parameterized.expand([diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex a29ef90c1757..13db33a4c522 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -49,6 +49,7 @@ from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthenticfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integration+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import Userfrom posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegrationfrom posthog.permissions import APIScopePermission, TimeSensitiveActionPermission@@ -425,16 +426,27 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):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).+ audit = GitHubAudit.personal(integration, user)+ remaining = UserGitHubIntegration.installation_reference_count(+ installation_id, exclude_user_integration_id=integration.id+ )+ audit.record("disconnect_started", last_reference=remaining == 0)try:- UserGitHubIntegration.uninstall_if_last_reference(- installation_id, exclude_user_integration_id=integration.id+ outcome = (+ UserGitHubIntegration.uninstall_app_installation_status(installation_id)+ if remaining == 0+ else "skipped")+ audit.record("uninstall_completed", outcome=outcome)except Exception as e:capture_exception(e)-- integration.delete()+ audit.record("uninstall_completed", outcome="failed", failure_type=type(e).__name__)+ try:+ integration.delete()+ except Exception as exc:+ audit.record("disconnect_failed", stage="personal_deletion", failure_type=type(exc).__name__)+ raise+ audit.record("credential_deleted", after_commit=True, reason="personal_disconnect")return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(@@ -629,6 +641,7 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):flow=FlowKind.OAUTH_DISCOVER,user_id=user.id,connect_from=connect_from,+ originating_organization_id=team.organization_id if team else None,),)return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_discover"})@@ -648,6 +661,8 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):flow=FlowKind.PERSONAL_INSTALL,user_id=user.id,connect_from=str(connect_from) if connect_from else None,+ # The resolved team can be a Desktop-selected project outside the current organization.+ originating_organization_id=team.organization_id if team else None,),)return Response(@@ -899,6 +914,7 @@ def _attempt_app_oauth_fast_path(user_id=user.id,installation_id=team_installation_id,connect_from=connect_from,+ originating_organization_id=team.organization_id,),)return Response({"install_url": github_oauth_authorize_url(state), "connect_flow": "oauth_authorize"})diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex d39eee6f3c34..dd546e315004 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -511,6 +511,7 @@ signal_exclusions: dict[ActivityScope, list[str]] = {# Activity visibility restrictions - controls which users can see certain activity logs# Used to hide sensitive activities (e.g., impersonated logins, user account changes) from non-staff usersactivity_visibility_restrictions: list[dict[str, Any]] = [+ {"scope": "Integration", "activities": ["github_diagnostic"], "allow_staff": True},{"scope": "User","activities": ["logged_in", "logged_out"],diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 43c128dc4297..f0031869821d 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -359,16 +359,22 @@ class GitHubIntegrationBase:@classmethoddef uninstall_app_installation(cls, installation_id: str) -> bool:+ return cls.uninstall_app_installation_status(installation_id) in ("uninstalled", "already_absent")++ @classmethod+ def uninstall_app_installation_status(+ cls, installation_id: str+ ) -> Literal["uninstalled", "already_absent", "skipped", "failed"]:"""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.+ success. The result distinguishes removal, absence, skipped requests, and failures."""if not installation_id:- return False+ return "skipped"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+ return "skipped"try:response = cls.client_request(f"installations/{installation_id}", method="DELETE", timeout=10)@@ -378,7 +384,7 @@ class GitHubIntegrationBase:installation_id=installation_id,exc_info=True,)- return False+ return "failed"if response.status_code in (204, 404):logger.info(@@ -386,14 +392,14 @@ class GitHubIntegrationBase:installation_id=installation_id,status_code=response.status_code,)- return True+ return "uninstalled" if response.status_code == 204 else "already_absent"logger.warning("GitHubIntegration: uninstall_app_installation unexpected status",installation_id=installation_id,status_code=response.status_code,)- return False+ return "failed"@classmethoddef uninstall_if_last_reference(diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex 28535e68d8e4..7865ae1e922a 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -21,6 +21,7 @@ from posthog.models.github_integration_base import (GitHubIntegrationError,_is_safe_github_repo_path,)+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.user import Userfrom posthog.plugins.plugin_server_api import reload_integrations_on_workersfrom posthog.sync import database_sync_to_async@@ -77,6 +78,7 @@ class GitHubUserAuthorization:refresh_token: str | None = field(repr=False)access_token_expires_in: int | Nonerefresh_token_expires_in: int | None+ identity_verified_at: int = field(default_factory=lambda: int(time.time()))@dataclass(frozen=True)@@ -195,6 +197,11 @@ class GitHubIntegration(GitHubIntegrationBase):},)+ if created:+ GitHubAudit.project(integration, created_by).record(+ "created", customer_visible=True, after_commit=True, outcome="connected"+ )+if integration.errors:integration.errors = ""integration.save()diff --git a/posthog/models/integration/github_audit.py b/posthog/models/integration/github_audit.pynew file mode 100644index 000000000000..2d354174257d--- /dev/null+++ b/posthog/models/integration/github_audit.py@@ -0,0 +1,236 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any+from uuid import UUID++from django.db import transaction++import structlog++from posthog.dataclasses import frozen+from posthog.models.activity_logging.utils import activity_storage++if TYPE_CHECKING:+ from posthog.models.integration import Integration+ from posthog.models.user import User+ from posthog.models.user_integration import UserIntegration++logger = structlog.get_logger("posthog.github_diagnostics")+++class GitHubAuditPayload:+ PERSONAL_FIELDS = frozenset(+ {+ "personal_integration_id",+ "owning_user_id",+ "github_user_id",+ "github_login",+ "credential_version",+ "identity_verified_at",+ }+ )+ CANDIDATE_FIELDS = frozenset(+ {"installation_id", "account_name", "account_type", "source_team_id", "source_team_name"}+ )+ FILTERED_FIELDS = frozenset({"installation_id", "source", "reason"})+ RESPONSE_FIELDS = frozenset(+ {+ "discovery_id",+ "discovered_at",+ "personal_github_connected",+ "personal_github_login",+ "personal_discovery_status",+ }+ )+ # Organizations with many GitHub projects would otherwise grow each discovery record without bound.+ MAX_RECORDED_INSTALLATIONS = 50+ # Discovery runs on every suggestions load and window focus, so it goes to logs only, not the activity log.+ LOG_ONLY_EVENTS = frozenset(+ {+ "discovery_credential_selected",+ "discovery_github_response",+ "discovery_candidates",+ "discovery_candidates_filtered",+ "discovery_completed",+ "discovery_failed",+ }+ )+ EVENT_FIELDS = {+ "created": {"outcome"},+ "deleted": {"outcome"},+ "credential_created": {"reason"},+ "credential_replaced": {"reason"},+ "credential_refreshed": {"reason"},+ "credential_deleted": {"reason"},+ "credential_delete_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"},+ "discovery_candidates_filtered": {"discovery_id"},+ "discovery_completed": {"discovery_id"},+ "discovery_failed": {"discovery_id", "reason"},+ "link_started": {"discovery_id", "installation_id", "path"},+ "link_path": {"discovery_id", "path", "source_team_id"},+ "link_completed": {"discovery_id", "installation_id", "path", "linked_integration_id"},+ "link_rejected": {"discovery_id", "installation_id", "path"},+ "link_failed": {"discovery_id", "installation_id", "failure_type"},+ "disconnect_started": {"last_reference"},+ "disconnect_failed": {"stage", "failure_type"},+ "uninstall_completed": {"outcome", "reason", "failure_type"},+ "personal_cleanup_failed": {"failure_type"},+ "webhook_cleanup": {"outcome", "completed_deletion"},+ "webhook_cleanup_failed": {"stage", "failure_type"},+ "setup_failed": {"flow_id", "callback_type"},+ }++ @staticmethod+ def fields(value: object, allowed: set[str] | frozenset[str]) -> dict[str, Any]:+ if not isinstance(value, dict):+ return {}+ return {+ key: item+ for key, item in value.items()+ if key in allowed and (item is None or isinstance(item, (str, int, float, bool)))+ }++ @classmethod+ def candidates(cls, value: object, allowed: frozenset[str] | None = None) -> list[dict[str, Any]]:+ allowed = allowed or cls.CANDIDATE_FIELDS+ return [cls.fields(item, allowed) for item in value] if isinstance(value, list) else []++ @classmethod+ def capped(cls, entries: list[dict[str, Any]]) -> tuple[int, list[dict[str, Any]]]:+ return len(entries), entries[: cls.MAX_RECORDED_INSTALLATIONS]++ @classmethod+ def error_codes(cls, value: object) -> list[str]:+ if isinstance(value, str):+ return [value]+ if isinstance(value, dict):+ value = list(value.values())+ if isinstance(value, list):+ return [code for item in value for code in cls.error_codes(item)]+ return []++ @classmethod+ def evidence(cls, event: str, value: dict[str, Any]) -> dict[str, Any]:+ result = cls.fields(value, cls.EVENT_FIELDS.get(event, set()))+ if event == "discovery_candidates":+ result["candidates"] = cls.candidates(value.get("candidates"))+ elif event == "discovery_candidates_filtered":+ result["filtered_count"], result["filtered"] = cls.capped(+ cls.candidates(value.get("filtered"), cls.FILTERED_FIELDS)+ )+ elif event == "discovery_completed":+ response = value.get("response")+ result["response"] = cls.fields(response, cls.RESPONSE_FIELDS)+ if isinstance(response, dict):+ result["response"]["installation_count"], result["response"]["installations"] = cls.capped(+ cls.candidates(response.get("installations"))+ )+ elif event in {"link_rejected", "setup_failed"}:+ field = "rejection_reason" if event == "link_rejected" else "failure_category"+ result[field] = cls.error_codes(value.get(field))+ return result+++@frozen+class GitHubAudit:+ organization_id: UUID | None = None+ team_id: int | None = None+ integration_id: str | None = None+ installation_id: str | None = None+ owner: str | None = None+ user: User | None = None+ personal_metadata: dict[str, Any] | None = None++ @classmethod+ def project(cls, integration: Integration, user: User | None = None) -> GitHubAudit:+ return cls(+ organization_id=integration.team.organization_id,+ team_id=integration.team_id,+ integration_id=str(integration.pk),+ installation_id=integration.integration_id,+ owner=(integration.config.get("account") or {}).get("name"),+ user=user,+ )++ @classmethod+ def personal(cls, integration: UserIntegration, user: User | None = None) -> GitHubAudit:+ config = integration.config or {}+ identity = config.get("github_user") or {}+ try:+ organization_id = (+ UUID(str(config["originating_organization_id"])) if config.get("originating_organization_id") else None+ )+ except (ValueError, TypeError):+ organization_id = None+ return cls(+ organization_id=organization_id,+ integration_id=str(integration.pk),+ installation_id=integration.integration_id,+ user=user,+ personal_metadata={+ "personal_integration_id": str(integration.pk),+ "owning_user_id": integration.user_id,+ "github_user_id": identity.get("id"),+ "github_login": identity.get("login"),+ "credential_version": config.get("credential_version"),+ "identity_verified_at": config.get("identity_verified_at"),+ },+ )++ def record(+ self, event: str, *, after_commit: bool = False, customer_visible: bool = False, **evidence: Any+ ) -> None:+ was_impersonated = bool(self.user and activity_storage.get_was_impersonated())+ payload = {+ "integration_id": self.integration_id,+ "installation_id": self.installation_id,+ "installation_owner": self.owner,+ **GitHubAuditPayload.fields(self.personal_metadata, GitHubAuditPayload.PERSONAL_FIELDS),+ **GitHubAuditPayload.evidence(event, evidence),+ }++ def write() -> None:+ logger.info(+ event,+ organization_id=str(self.organization_id) if self.organization_id else None,+ team_id=self.team_id,+ actor_id=self.user.pk if self.user else None,+ **payload,+ )+ if self.organization_id is None or event in GitHubAuditPayload.LOG_ONLY_EVENTS:+ return+ try:+ from posthog.models.activity_logging.activity_log import ( # noqa: PLC0415 -- avoids the integration model import cycle+ Detail,+ Trigger,+ log_activity,+ )++ with transaction.atomic():+ log_activity(+ organization_id=self.organization_id,+ team_id=self.team_id,+ user=self.user,+ item_id=self.integration_id or self.installation_id,+ scope="Integration",+ activity=event if customer_visible else "github_diagnostic",+ detail=Detail(+ name=self.owner or self.installation_id or "GitHub",+ trigger=Trigger(+ job_type="github",+ job_id=str(payload.get("discovery_id") or ""),+ payload={"event": event, **payload},+ ),+ ),+ was_impersonated=was_impersonated,+ )+ except Exception:+ logger.warning("github_audit_write_failed", event_name=event, team_id=self.team_id)++ if after_commit:+ transaction.on_commit(write, robust=True)+ else:+ write()diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex 97c395200980..d050cb909f3b 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -1,6 +1,7 @@import timefrom datetime import datetimefrom typing import TYPE_CHECKING, Any+from uuid import UUID, uuid4from django.conf import settingsfrom django.db import models@@ -13,6 +14,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import github_account_type, invalidate_github_repository_caches_for_installation+from posthog.models.integration.github_audit import GitHubAuditfrom posthog.models.utils import UUIDModelif TYPE_CHECKING:@@ -514,6 +516,7 @@ class UserGitHubIntegration(GitHubIntegrationBase):}config = dict(self.integration.config or {})config["user_token_refreshed_at"] = now+ config["credential_version"] = str(uuid4())# When GitHub disables user-token expiration, refresh responses omit expiry fields.# Clear stored expiries so we do not treat a non-expiring token as perpetually expired.if access_expires_in is not None:@@ -526,6 +529,7 @@ 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")def _discard(self, reason: str) -> None:"""Delete the integration when stored credentials are unusable.@@ -534,9 +538,12 @@ class UserGitHubIntegration(GitHubIntegrationBase):The user falls back to the Connect flow."""logger.info("UserGitHubIntegration: discarding integration", user_id=self.integration.user_id, reason=reason)+ audit = GitHubAudit.personal(self.integration)try:self.integration.delete()- except Exception:+ audit.record("credential_deleted", after_commit=True, reason=reason)+ 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)@@ -546,6 +553,7 @@ def user_github_integration_from_installation(authorization: "GitHubUserAuthorization",*,create_only: bool = False,+ originating_organization_id: UUID | None = None,) -> UserIntegration:"""Create or update a UserIntegration from a GitHub App installation + user authorization.@@ -564,6 +572,16 @@ def user_github_integration_from_installation(except (ValueError, AttributeError):expires_in = 3600+ # A re-link without organization context keeps the stored one, so later diagnostics stay durable.+ stored_organization_id = (+ None+ if originating_organization_id+ else UserIntegration.objects.filter(+ user=user, kind=UserIntegration.IntegrationKind.GITHUB, integration_id=installation.installation_id+ )+ .values_list("config__originating_organization_id", flat=True)+ .first()+ )config: dict[str, Any] = {"installation_id": installation.installation_id,"expires_in": expires_in,@@ -575,6 +593,11 @@ def user_github_integration_from_installation(},"github_user": {"login": authorization.gh_login, "id": authorization.gh_id},"user_token_refreshed_at": now,+ "credential_version": str(uuid4()),+ "identity_verified_at": authorization.identity_verified_at,+ "originating_organization_id": str(originating_organization_id)+ if originating_organization_id+ else stored_organization_id,}if authorization.access_token_expires_in is not None:config["user_access_token_expires_at"] = now + authorization.access_token_expires_in@@ -609,6 +632,13 @@ def user_github_integration_from_installation()invalidate_github_repository_caches_for_installation(installation.installation_id)+ if created or not create_only:+ GitHubAudit.personal(integration, user).record(+ "credential_created" if created else "credential_replaced",+ after_commit=True,+ reason="team_connect" if create_only else "personal_connect",+ )+if created:_report_personal_integration_created(user, config, auto_created=create_only)diff --git a/posthog/settings/logs.py b/posthog/settings/logs.pyindex 7d35d86c3018..c33867d9d03b 100644--- a/posthog/settings/logs.py+++ b/posthog/settings/logs.py@@ -140,6 +140,7 @@ LOGGING: dict[str, Any] = {},"root": {"handlers": ["console"], "level": DEFAULT_LOG_LEVEL},"loggers": {+ "posthog.github_diagnostics": {"level": "INFO", "handlers": ["console"], "propagate": False},"django": {"handlers": ["console"], "level": DEFAULT_LOG_LEVEL},"django.server": {"handlers": ["null"]}, # blackhole Django server logs (this is only needed in DEV)"django.utils.autoreload": {diff --git a/posthog/settings/test_logs.py b/posthog/settings/test_logs.pyindex c3873246cd96..1caa7f6efb3d 100644--- a/posthog/settings/test_logs.py+++ b/posthog/settings/test_logs.py@@ -47,6 +47,7 @@ def test_logging_config_can_be_applied() -> None:config = dict(logs.LOGGING)config["disable_existing_loggers"] = Falselogging.config.dictConfig(config)+ assert logging.getLogger("posthog.github_diagnostics").isEnabledFor(logging.INFO)def test_default_console_logging_handler_keeps_default_stream() -> None:diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex a72e5ab33176..9459c597e9b1 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -412,6 +412,8 @@ class TestActivityLogVisibilityManager(BaseTest):("instance_setting_updated", "InstanceSetting", "updated", False, True),# AI-gateway top-ups are staff-only and must be hidden from non-staff viewers("ai_gateway_credit_added", "AIGatewayCredit", "credit_added", False, True),+ ("github_diagnostic", "Integration", "github_diagnostic", False, True),+ ("github_connected", "Integration", "created", False, False),# Ticket comment rows reference support-ticket bodies (rows written before write-time# masking still hold plaintext) and must be hidden from non-staff viewers("ticket_comment", "Ticket", "commented", False, True),diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.tsindex 1ac5f3e1684e..15f4902a701a 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts@@ -56,7 +56,7 @@ export interface alertNotificationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface alertNotificationLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicloadIntegrationsFailure: (error: string,errorObject?: anydiff --git a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.tsindex f4cec8e7d0c5..0365b3303e7d 100644--- a/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts+++ b/products/data_warehouse/frontend/shared/logics/destinationModalLogic.ts@@ -81,7 +81,7 @@ export interface destinationModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface destinationModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogiccloseModal: () => {value: true}diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 1eeca929590e..5ef8f7e13fd9 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -458,6 +458,20 @@ export interface SlackUsersResponseApi {has_more?: boolean}+/**+ * * `ok` - Ok+ * * `not_connected` - Not Connected+ * * `unavailable` - Unavailable+ */+export type GitHubPersonalDiscoveryStatusEnumApi =+ (typeof GitHubPersonalDiscoveryStatusEnumApi)[keyof typeof GitHubPersonalDiscoveryStatusEnumApi]++export const GitHubPersonalDiscoveryStatusEnumApi = {+ Ok: 'ok',+ NotConnected: 'not_connected',+ Unavailable: 'unavailable',+} as const+export interface GitHubAvailableInstallationApi {/** GitHub installation ID to pass to github/link_existing when linking this installation. */installation_id: string@@ -476,9 +490,29 @@ export interface GitHubAvailableInstallationApi {* @nullable*/source_team_id: number | null+ /**+ * Name of the project in source_team_id, so the picker can say where the installation comes from. Null for an installation no project has linked yet.+ * @nullable+ */+ source_team_name: string | null}export interface GitHubAvailableInstallationsResponseApi {+ /** Correlation ID for this discovery response. */+ discovery_id: string+ /** Time this discovery completed. */+ discovered_at: string+ /**+ * GitHub identity of the credential used for personal discovery.+ * @nullable+ */+ personal_github_login: string | null+ /** Whether personal discovery succeeded, has no connection, or is unavailable.+ *+ * * `ok` - Ok+ * * `not_connected` - Not Connected+ * * `unavailable` - Unavailable */+ personal_discovery_status: GitHubPersonalDiscoveryStatusEnumApi/** GitHub installations available to link to this project: the organization's existing installations plus any the user's personal GitHub link can see but that aren't linked to any project yet. */installations: GitHubAvailableInstallationApi[]/** Whether the requesting user has a personal GitHub account linked (via Linked Accounts). Used to prompt for that link when it would surface more installations to adopt. */@@ -486,13 +520,21 @@ export interface GitHubAvailableInstallationsResponseApi {}export interface GitHubLinkExistingRequestApi {+ /**+ * Discovery response ID for diagnostics only; grants no authority.+ * @nullable+ */+ discovery_id?: string | null/*** Sibling team in the same organization whose GitHub installation should be reused.* @nullable*/source_team_id?: number | null- /** GitHub installation ID to link; resolved within the organization when source_team_id is omitted. */- installation_id?: string+ /**+ * GitHub installation ID to link; resolved within the organization when source_team_id is omitted.+ * @nullable+ */+ installation_id?: string | null}/**diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.tsindex 9cde3904733e..5299be58a7f0 100644--- a/products/integrations/frontend/generated/api.zod.ts+++ b/products/integrations/frontend/generated/api.zod.ts@@ -310,13 +310,14 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod* Reuse a GitHub installation already linked to a sibling team in the same organization.*/export const IntegrationsGithubLinkExistingCreateBody = /* @__PURE__ */ zod.object({+ discovery_id: zod.uuid().nullish().describe('Discovery response ID for diagnostics only; grants no authority.'),source_team_id: zod.number().nullish().describe('Sibling team in the same organization whose GitHub installation should be reused.'),installation_id: zod.string()- .optional()+ .nullish().describe('GitHub installation ID to link; resolved within the organization when source_team_id is omitted.'),})diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex 3923e7740c24..6333fad24fd8 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -52,7 +52,7 @@ export interface logsAlertNotificationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsAlertNotificationLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicloadIntegrationsFailure: (error: string,errorObject?: anydiff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.tsindex 99d8a5550c85..a02e9333317e 100644--- a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts@@ -50,7 +50,7 @@ export interface scannerAlertNotificationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerAlertNotificationLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicloadIntegrationsFailure: (error: string,errorObject?: anydiff --git a/products/signals/frontend/inbox/InboxScene.stories.tsx b/products/signals/frontend/inbox/InboxScene.stories.tsxindex 0bafad31d7be..b40911ec8b0a 100644--- a/products/signals/frontend/inbox/InboxScene.stories.tsx+++ b/products/signals/frontend/inbox/InboxScene.stories.tsx@@ -41,6 +41,14 @@ function routeTo(pathname: string, searchParams: Record<string, string> = {}): Dconst sceneMocks = mswDecorator({get: {+ '/api/projects/:id/integrations/github/available_installations/': {+ discovery_id: '11111111-1111-4111-8111-111111111111',+ discovered_at: '2026-06-11T00:00:00Z',+ installations: [],+ personal_github_connected: false,+ personal_github_login: null,+ personal_discovery_status: 'not_connected',+ },'/api/projects/:id/signals/reports': () => [200,{ results: allReports, count: allReports.length, next: null, previous: null },diff --git a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.tsindex c6dd97ded033..3bdafe6d8751 100644--- a/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/APNSSetup/apnsSetupModalLogic.ts@@ -85,7 +85,7 @@ export interface apnsSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface apnsSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetApnsIntegration: (values?: {bundleId: stringenvironment: 'production'diff --git a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.tsindex cd2f3a354e1e..b0e11385882e 100644--- a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts@@ -89,7 +89,7 @@ export interface emailSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface emailSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetEmailSender: (values?: EmailSenderFormType) => {values?: EmailSenderFormType}diff --git a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.tsindex 8875ce0249e2..80cfe0758653 100644--- a/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/FCMSetup/fcmSetupModalLogic.ts@@ -64,7 +64,7 @@ export interface fcmSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface fcmSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetFcmIntegration: (values?: {identityPublicKey: stringidentityVerification: PushIdentityVerificationModediff --git a/products/workflows/frontend/Channels/SlackSetup/slackSetupModalLogic.ts b/products/workflows/frontend/Channels/SlackSetup/slackSetupModalLogic.tsindex 635b5c4263cd..0df392c6e227 100644--- a/products/workflows/frontend/Channels/SlackSetup/slackSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/SlackSetup/slackSetupModalLogic.ts@@ -59,7 +59,7 @@ export interface slackSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface slackSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetSlackIntegration: (values?: { botToken: string; channelId: string }) => {values?: {botToken: stringdiff --git a/products/workflows/frontend/Channels/TwilioSetup/twilioSetupModalLogic.ts b/products/workflows/frontend/Channels/TwilioSetup/twilioSetupModalLogic.tsindex ba65b0a76cdc..91435fd6b597 100644--- a/products/workflows/frontend/Channels/TwilioSetup/twilioSetupModalLogic.ts+++ b/products/workflows/frontend/Channels/TwilioSetup/twilioSetupModalLogic.ts@@ -52,7 +52,7 @@ export interface twilioSetupModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface twilioSetupModalLogicActions {- loadIntegrations: () => any // integrationsLogic+ loadIntegrations: (_?: any) => any // integrationsLogicresetTwilioIntegration: (values?: { accountSid: string; authToken: string }) => {values?: {accountSid: stringdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 806e47494120..8eaca719d3fe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47432,9 +47432,43 @@ export namespace Schemas {* @nullable*/source_team_id: number | null;+ /**+ * Name of the project in source_team_id, so the picker can say where the installation comes from. Null for an installation no project has linked yet.+ * @nullable+ */+ source_team_name: string | null;}+ /**+ * * `ok` - Ok+ * * `not_connected` - Not Connected+ * * `unavailable` - Unavailable+ */+ export type GitHubPersonalDiscoveryStatusEnum = typeof GitHubPersonalDiscoveryStatusEnum[keyof typeof GitHubPersonalDiscoveryStatusEnum];+++ export const GitHubPersonalDiscoveryStatusEnum = {+ Ok: 'ok',+ NotConnected: 'not_connected',+ Unavailable: 'unavailable',+ } as const;+export interface GitHubAvailableInstallationsResponse {+ /** Correlation ID for this discovery response. */+ discovery_id: string;+ /** Time this discovery completed. */+ discovered_at: string;+ /**+ * GitHub identity of the credential used for personal discovery.+ * @nullable+ */+ personal_github_login: string | null;+ /** Whether personal discovery succeeded, has no connection, or is unavailable.+ *+ * * `ok` - Ok+ * * `not_connected` - Not Connected+ * * `unavailable` - Unavailable */+ personal_discovery_status: GitHubPersonalDiscoveryStatusEnum;/** GitHub installations available to link to this project: the organization's existing installations plus any the user's personal GitHub link can see but that aren't linked to any project yet. */installations: GitHubAvailableInstallation[];/** Whether the requesting user has a personal GitHub account linked (via Linked Accounts). Used to prompt for that link when it would surface more installations to adopt. */@@ -47513,13 +47547,21 @@ export namespace Schemas {}export interface GitHubLinkExistingRequest {+ /**+ * Discovery response ID for diagnostics only; grants no authority.+ * @nullable+ */+ discovery_id?: string | null;/*** Sibling team in the same organization whose GitHub installation should be reused.* @nullable*/source_team_id?: number | null;- /** GitHub installation ID to link; resolved within the organization when source_team_id is omitted. */- installation_id?: string;+ /**+ * GitHub installation ID to link; resolved within the organization when source_team_id is omitted.+ * @nullable+ */+ installation_id?: string | null;}export interface GitHubOAuthAuthorizeRequest {