Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(integrations): adopt GitHub installations approved outside the connect flow (#79179)

Matt Brookeradd61d9f5025
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 6e7c73873588..7620085ab95b 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -23,6 +23,7 @@ import {
} from 'products/integrations/frontend/generated/api'
import type {
GitHubAvailableInstallationApi,
+ GitHubAvailableInstallationsResponseApi,
GitHubRepoApi,
IntegrationKindEnumApi,
} from 'products/integrations/frontend/generated/api.schemas'
@@ -93,8 +94,10 @@ export interface integrationsLogicValues {
)[]
) => IntegrationType[]
githubAvailableInstallations: GitHubAvailableInstallationApi[] | null
- githubAvailableInstallationsLoading: boolean
+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null
+ githubAvailableInstallationsResponseLoading: boolean
githubIntegrations: IntegrationType[]
+ githubPersonalConnected: boolean | null
githubRepositories: Record<number, GitHubRepoApi[]>
githubRepositoriesLoading: boolean
integrations: IntegrationType[] | null
@@ -217,10 +220,10 @@ export interface integrationsLogicActions {
errorObject?: any
}
loadGithubAvailableInstallationsSuccess: (
- githubAvailableInstallations: GitHubAvailableInstallationApi[],
+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi,
payload?: any
) => {
- githubAvailableInstallations: GitHubAvailableInstallationApi[]
+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi
payload?: any
}
loadIntegrations: () => any
@@ -626,6 +629,12 @@ export interface integrationsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
slackIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[] | undefined
githubIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[]
+ githubAvailableInstallations: (
+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null
+ ) => GitHubAvailableInstallationApi[] | null
+ githubPersonalConnected: (
+ githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null
+ ) => boolean | null
getIntegrationsByKind: (
integrations: IntegrationType[] | null
) => (
@@ -863,16 +872,13 @@ export const integrationsLogic = kea<integrationsLogicType>([
},
},
],
- githubAvailableInstallations: [
- null as GitHubAvailableInstallationApi[] | null,
+ 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 () => {
- const response = await integrationsGithubAvailableInstallationsRetrieve(
- String(values.currentProjectId)
- )
- return response.installations
+ return await integrationsGithubAvailableInstallationsRetrieve(String(values.currentProjectId))
},
},
],
@@ -1058,6 +1064,18 @@ export const integrationsLogic = kea<integrationsLogicType>([
return integrations?.filter((x) => x.kind === 'github') ?? []
},
],
+ githubAvailableInstallations: [
+ (s) => [s.githubAvailableInstallationsResponse],
+ (response: GitHubAvailableInstallationsResponseApi | null): GitHubAvailableInstallationApi[] | null => {
+ return response?.installations ?? null
+ },
+ ],
+ githubPersonalConnected: [
+ (s) => [s.githubAvailableInstallationsResponse],
+ (response: GitHubAvailableInstallationsResponseApi | null): boolean | null => {
+ return response ? response.personal_github_connected : null
+ },
+ ],
getIntegrationsByKind: [
(s) => [s.integrations],
(integrations: IntegrationType[] | null) => {
diff --git a/frontend/src/scenes/integrations/components/GithubIntegration.tsx b/frontend/src/scenes/integrations/components/GithubIntegration.tsx
index 8af4bf9d0c7f..2f18b3db3292 100644
--- a/frontend/src/scenes/integrations/components/GithubIntegration.tsx
+++ b/frontend/src/scenes/integrations/components/GithubIntegration.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconChevronDown } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
import api from 'lib/api'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
@@ -16,7 +16,8 @@ import { Integration, useIntegrations } from './Integration'
export function GithubIntegration({ next }: { next?: string }): JSX.Element {
const { currentTeam } = useValues(teamLogic)
- const { linkedGithubInstallationLoading, githubAvailableInstallations } = useValues(integrationsLogic)
+ const { linkedGithubInstallationLoading, githubAvailableInstallations, githubPersonalConnected } =
+ useValues(integrationsLogic)
const { linkExistingGithubInstallation, loadGithubAvailableInstallations } = useActions(integrationsLogic)
const githubIntegrations = useIntegrations('github')
@@ -39,34 +40,53 @@ export function GithubIntegration({ next }: { next?: string }): JSX.Element {
return (
<Integration kind="github">
- <div className="flex flex-col gap-y-2">
+ {/* w-full because Integration drops its children into a bare flex row, which would
+ otherwise size the banner to its longest word. */}
+ <div className="flex flex-col gap-y-4 w-full">
+ {/* An install GitHub already has is the exception, not a second way to connect, so it
+ reads as an aside with its own action rather than a button competing with the one
+ below. */}
+ {canLinkExisting && (
+ <LemonBanner type="info" hideIcon>
+ <div className="flex items-center gap-3">
+ <span className="min-w-0 text-sm font-normal">
+ {multipleInstallations ? (
+ <>Already installed on more than one of your GitHub accounts.</>
+ ) : (
+ <>
+ Already installed on your GitHub account{' '}
+ <code>{accountLabel(installations[0])}</code>.
+ </>
+ )}
+ </span>
+ <GitHubInstallationLink
+ installations={installations}
+ loading={linkedGithubInstallationLoading}
+ onLink={linkExistingGithubInstallation}
+ projectName={currentTeam?.name}
+ />
+ </div>
+ </LemonBanner>
+ )}
<div className="flex flex-wrap gap-2">
{/* This leaves PostHog entirely, and a GitHub App installs at most once per
account, so GitHub offers install where it's missing and configure where it
- isn't. Connecting is only a promise we can keep while this project has
- nothing linked; past that the honest label is the destination. */}
+ isn't. "Connect account" matches the Linear and Jira cards, which name the
+ third party's container. */}
<LemonButton type="secondary" disableClientSideRouting to={authorizationUrl}>
- {isConnected ? 'Manage on GitHub' : 'Connect organization'}
+ {isConnected ? 'Manage on GitHub' : 'Connect account'}
</LemonButton>
- {canLinkExisting && (
- <GitHubInstallationLink
- installations={installations}
- loading={linkedGithubInstallationLoading}
- onLink={linkExistingGithubInstallation}
- />
- )}
</div>
{isConnected && (
<p className="text-secondary text-xs mb-0">
- Install the PostHog app on another GitHub account, or change which repositories this
- installation can see.
+ Add the PostHog app to another GitHub account, or change which repositories it can see.
</p>
)}
- {canLinkExisting && (
+ {!isConnected && installations.length === 0 && githubPersonalConnected === false && (
<p className="text-secondary text-xs mb-0">
- {multipleInstallations
- ? 'Choose an existing GitHub installation to connect to this project.'
- : 'A GitHub App installs once per organization. Link the installation you already have instead of reinstalling.'}
+ Already installed the PostHog GitHub App but don't see it here? Connect your GitHub account
+ under <Link to={urls.settings('user-personal-integrations')}>Personal integrations</Link> so
+ PostHog can find it.
</p>
)}
</div>
@@ -74,23 +94,39 @@ export function GithubIntegration({ next }: { next?: string }): JSX.Element {
)
}
+// 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}`
+}
+
export function GitHubInstallationLink({
installations,
loading,
onLink,
+ projectName,
}: {
installations: GitHubAvailableInstallationApi[]
loading: boolean
onLink: (installationId?: string) => void
+ /** Named on the button, so it's clear which project the install lands in. */
+ projectName?: string
}): JSX.Element | null {
if (installations.length === 0) {
return null
}
if (installations.length === 1) {
+ // Always name the installation, even when there's only one to pick. Omitting it asks the
+ // backend to auto-resolve from a sibling project, which an orphan installation has none of.
return (
- <LemonButton type="secondary" loading={loading} onClick={() => onLink()}>
- Link existing installation
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={loading}
+ onClick={() => onLink(installations[0].installation_id)}
+ >
+ Connect to {projectName ?? 'this project'}
</LemonButton>
)
}
@@ -99,13 +135,13 @@ export function GitHubInstallationLink({
<LemonMenu
items={installations.map((installation) => ({
key: installation.installation_id,
- label: installation.account_name ?? `Installation ${installation.installation_id}`,
- disabledReason: loading ? 'Linking an installation' : undefined,
+ label: accountLabel(installation),
+ disabledReason: loading ? 'Connecting an account' : undefined,
onClick: () => onLink(installation.installation_id),
}))}
>
- <LemonButton type="secondary" loading={loading} sideIcon={<IconChevronDown />}>
- Link existing installation
+ <LemonButton type="secondary" size="small" loading={loading} sideIcon={<IconChevronDown />}>
+ Choose an account
</LemonButton>
</LemonMenu>
)
diff --git a/frontend/src/scenes/integrations/components/Integrations.test.tsx b/frontend/src/scenes/integrations/components/Integrations.test.tsx
index 553e61781214..33e76f06da4a 100644
--- a/frontend/src/scenes/integrations/components/Integrations.test.tsx
+++ b/frontend/src/scenes/integrations/components/Integrations.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { render, screen } from '@testing-library/react'
+import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { GitHubAvailableInstallationApi } from 'products/integrations/frontend/generated/api.schemas'
@@ -28,12 +28,38 @@ describe('GitHubInstallationLink', () => {
render(<GitHubInstallationLink installations={installations} loading={false} onLink={onLink} />)
- expect(screen.getAllByText('Link existing installation')).toHaveLength(1)
+ expect(screen.getAllByText('Choose an account')).toHaveLength(1)
expect(screen.queryByText('PostHog')).not.toBeInTheDocument()
- await user.click(screen.getByText('Link existing installation'))
+ await user.click(screen.getByText('Choose an account'))
await user.click(await screen.findByText('PostHog'))
expect(onLink).toHaveBeenCalledWith('101')
})
+
+ it('names the installation when only one is available', async () => {
+ // Linking without an installation id asks the backend to auto-resolve from a sibling
+ // project. An orphan installation has no sibling, so dropping the id here dead-ends the
+ // one case adoption exists for.
+ const user = userEvent.setup()
+ const onLink = jest.fn()
+ const installations: GitHubAvailableInstallationApi[] = [
+ {
+ installation_id: '303',
+ account_name: 'PostHog',
+ account_type: 'Organization',
+ source_team_id: null,
+ },
+ ]
+
+ const { container } = render(
+ <GitHubInstallationLink installations={installations} loading={false} onLink={onLink} />
+ )
+
+ // Scoped to this render: the menu case above leaves its portal in the document, so a
+ // `screen` query here would depend on test order.
+ await user.click(within(container).getByRole('button'))
+
+ expect(onLink).toHaveBeenCalledWith('303')
+ })
})
diff --git a/posthog/api/github_callback/README.md b/posthog/api/github_callback/README.md
index 9752d4237164..ee5783615a86 100644
--- a/posthog/api/github_callback/README.md
+++ b/posthog/api/github_callback/README.md
@@ -97,6 +97,18 @@ installation without the install redirect. A team admin can link without a
personal GitHub OAuth link; non-admins still need one as an ownership proof (see
`authorize_link_existing_installation`).
+The same endpoint also **adopts orphan installations**: ones installed on
+GitHub (e.g. an install request approved by a GitHub org admin directly on
+github.com, which never round-trips the setup callback) but not linked to any
+PostHog team. `github/available_installations` surfaces them from the user's
+personal `GET /user/installations`. Adoption (`adopt_orphan_installation`)
+requires both PostHog project admin — a new installation entering the org is
+held to the setup callback's first-time-connect bar, since adoption has no
+GitHub-side gate on who submits the installation id — and the personal-token
+access proof. Sibling reuse stays member-grade with proof. An installation
+linked solely to projects the caller can't access is refused, not offered for
+adoption.
+
## Callback routes
| Route | Handler | Flow |
diff --git a/posthog/api/github_callback/personal_state.py b/posthog/api/github_callback/personal_state.py
new file mode 100644
index 000000000000..e48b31012020
--- /dev/null
+++ b/posthog/api/github_callback/personal_state.py
@@ -0,0 +1,103 @@
+"""Read-only helpers for a user's *personal* GitHub App state.
+
+Distinct from ``team_services.py``, which manages team-scoped ``Integration`` rows: this module
+answers what a user's own OAuth-linked ``UserIntegration`` can see on GitHub, independent of any
+team. Shared by the personal "unlinked installations" check, the org installation picker, and
+orphan-installation adoption.
+"""
+
+from typing import Any
+
+import requests
+
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request
+from posthog.models.user import User
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+
+_OBSERVABILITY_SOURCE = "integration"
+
+
+def _newest_personal_github_integration(user: User) -> UserIntegration | None:
+ return (
+ UserIntegration.objects.filter(user=user, kind="github")
+ .exclude(sensitive_config={})
+ .order_by("-created_at")
+ .first()
+ )
+
+
+def user_has_personal_github_integration(user: User) -> bool:
+ """Whether ``user`` has a usable personal GitHub App link at all."""
+ return _newest_personal_github_integration(user) is not None
+
+
+def personal_github_login(user: User) -> str | None:
+ """The user's own GitHub login from their most recent personal GitHub link, if any."""
+ integration = _newest_personal_github_integration(user)
+ if integration is None:
+ return None
+ return UserGitHubIntegration(integration).github_login
+
+
+def usable_personal_github_token(user: User) -> str | 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
+ while an older one still refreshes fine. Returns None when no link yields a token — callers
+ must treat this as "can't verify" rather than raise, since a stale personal link is common and
+ not itself an error.
+ """
+ integrations = (
+ UserIntegration.objects.filter(user=user, kind="github").exclude(sensitive_config={}).order_by("-created_at")
+ )
+ for integration in integrations:
+ try:
+ token = UserGitHubIntegration(integration).get_usable_user_access_token()
+ except Exception:
+ continue
+ if token:
+ return token
+ return None
+
+
+def list_user_github_app_installations(user: User) -> 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``,
+ ``account`` with ``login``/``type``, etc.), or None when the check can't be answered — no
+ personal GitHub link, a token refresh failure, a network error, or a non-200 response. Callers
+ must treat None as "unknown" and degrade gracefully rather than fail the request.
+ """
+ token = usable_personal_github_token(user)
+ if token is None:
+ return None
+
+ try:
+ # Identity-blind: user OAuth token, metered against the user's budget, not an installation's.
+ response = github_request(
+ "GET",
+ "https://api.github.com/user/installations",
+ source=_OBSERVABILITY_SOURCE,
+ headers={"Authorization": f"Bearer {token}"},
+ params={"per_page": 100},
+ timeout=10,
+ )
+ except (requests.RequestException, GitHubEgressBudgetExhausted):
+ return None
+
+ if response.status_code != 200:
+ return None
+
+ try:
+ installations = response.json().get("installations", [])
+ except ValueError:
+ return None
+
+ if not isinstance(installations, list):
+ return None
+
+ return [
+ installation
+ for installation in installations
+ if isinstance(installation, dict) and installation.get("id") is not None
+ ]
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index d3a7295a28ac..c67359319202 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -17,6 +17,11 @@ from posthog.api.github_callback import (
redirects,
state as github_callback_state,
)
+from posthog.api.github_callback.personal_state import (
+ list_user_github_app_installations,
+ personal_github_login,
+ usable_personal_github_token,
+)
from posthog.api.github_callback.types import (
FinishResult,
FlowKind,
@@ -25,6 +30,7 @@ from posthog.api.github_callback.types import (
is_valid_github_installation_id,
)
from posthog.auth import SessionAuthentication
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted
from posthog.models import Team
from posthog.models.integration import (
GitHubInstallationAccess,
@@ -37,7 +43,7 @@ from posthog.models.integration import (
)
from posthog.models.organization import Organization
from posthog.models.user import User
-from posthog.models.user_integration import UserIntegration, user_github_integration_from_installation
+from posthog.models.user_integration import user_github_integration_from_installation
from posthog.utils import is_relative_url
logger = structlog.get_logger(__name__)
@@ -123,7 +129,7 @@ def link_github_installation_for_user(
raise ValidationError("Invalid installation_id")
try:
has_access = GitHubIntegration.verify_user_installation_access(installation_id, authorization.access_token)
- except requests.RequestException:
+ except (requests.RequestException, GitHubEgressBudgetExhausted):
logger.warning(
"github_integration_create: installation ownership check failed",
installation_id=installation_id,
@@ -183,10 +189,7 @@ def authorize_link_existing_installation(
if github_callback_state.has_team_management_access(user, team):
return
- user_github_integration = UserIntegration.objects.filter(user=user, kind="github").order_by("-created_at").first()
- user_access_token = (
- user_github_integration.sensitive_config.get("access_token") if user_github_integration else None
- )
+ user_access_token = usable_personal_github_token(user)
if not user_access_token:
raise ValidationError(
PERSONAL_GITHUB_REQUIRED_MESSAGE,
@@ -194,7 +197,7 @@ def authorize_link_existing_installation(
)
try:
has_access = GitHubIntegration.verify_user_installation_access(source_installation_id, user_access_token)
- except requests.RequestException:
+ except (requests.RequestException, GitHubEgressBudgetExhausted):
raise ValidationError("Failed to verify installation access")
if not has_access:
raise ValidationError(
@@ -203,6 +206,54 @@ def authorize_link_existing_installation(
)
+GITHUB_ADOPTION_ADMIN_REQUIRED_MESSAGE = (
+ "Linking a GitHub installation that no project has connected yet requires admin access to this "
+ "project. Ask a project admin to link it."
+)
+
+
+def adopt_orphan_installation(*, user: User, team: Team, installation_id: str) -> Integration:
+ """Create the team's first ``Integration`` row for a GitHub App installation that exists on
+ GitHub but was never linked to any PostHog team — e.g. a non-admin clicked "Connect
+ organization", GitHub created an install *request*, and a GitHub org admin approved it
+ directly on github.com without completing PostHog's callback.
+
+ Introducing a new installation to the org is held to the same bar as a first-time connect
+ through the setup callback: PostHog project admin. On top of that, personal GitHub access
+ proof is always required — unlike sibling reuse, there's no existing PostHog integration to
+ imply the org already has legitimate access, and the admin requirement alone proves nothing
+ on the GitHub side. The create/update flows are additionally gated by GitHub itself (only a
+ GitHub org admin reaches the callback with a valid installation_id); adoption has no such
+ gate, so neither check here can be dropped.
+ """
+ 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:
+ 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)
+ except (requests.RequestException, GitHubEgressBudgetExhausted):
+ raise ValidationError("Failed to verify installation access")
+ if not has_access:
+ 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)
+
+ login = personal_github_login(user)
+ if login:
+ instance.config["connecting_user_github_login"] = login
+ instance.save(update_fields=["config"])
+
+ return instance
+
+
def finish_team_github_setup_update(
*,
user: User,
@@ -410,6 +461,25 @@ def _accessible_org_team_ids(user: User, organization: Organization) -> set[int]
return set(user.teams.filter(organization_id=organization.id).values_list("id", flat=True))
+def _org_linked_github_installation_ids(organization: Organization) -> set[str]:
+ """Every GitHub installation id linked to *any* team in ``organization``, including projects the
+ current user can't access.
+
+ Used to tell a genuinely orphan installation (no PostHog row anywhere in the org) apart from
+ one that's merely linked to a project the caller can't see — the latter must keep raising the
+ access error rather than being offered up for adoption, or the access boundary in
+ ``_accessible_org_team_ids`` would leak through the adoption path.
+ """
+ org_github = defer_repository_cache_fields(
+ Integration.objects.filter(team__organization_id=organization.id, kind="github")
+ )
+ return {
+ str(installation_id)
+ for integration in org_github
+ if (installation_id := (integration.config or {}).get("installation_id"))
+ }
+
+
def link_existing_team_github_integration(
*,
user: User,
@@ -439,25 +509,38 @@ def link_existing_team_github_integration(
if installation_id_param:
qs = qs.for_github_installation_id(str(installation_id_param))
- source = qs.order_by("id").first()
+ source = defer_repository_cache_fields(qs).order_by("id").first()
if source is None:
raise ValidationError("Source team does not have a GitHub integration")
elif installation_id_param:
+ installation_id_str = str(installation_id_param)
existing = (
- Integration.objects.filter(
- team__organization_id=organization.id,
- team_id__in=accessible_team_ids,
- kind="github",
+ defer_repository_cache_fields(
+ Integration.objects.filter(
+ team__organization_id=organization.id,
+ team_id__in=accessible_team_ids,
+ kind="github",
+ ).for_github_installation_id(installation_id_str)
)
- .for_github_installation_id(str(installation_id_param))
.order_by("id")
.first()
)
if existing is None:
- raise ValidationError(
- "No team in your organization has this GitHub installation linked",
- code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
- )
+ if installation_id_str in _org_linked_github_installation_ids(organization):
+ # Linked to a team elsewhere in the org that this user can't access — not an orphan,
+ # just invisible to them. Falling through to adoption here would let personal GitHub
+ # access override the project access boundary `_accessible_org_team_ids` enforces.
+ raise ValidationError(
+ "No team in your organization has this GitHub installation linked",
+ code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ )
+ # No PostHog team anywhere in the org has this installation linked. It may still be
+ # installed on GitHub — e.g. approved by a GitHub org admin without completing PostHog's
+ # callback. Adoption re-proves personal access rather than raising outright.
+ 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)
source = existing
else:
# No source specified: auto-resolve the org's existing GitHub installation. This backs the
@@ -516,7 +599,7 @@ def list_org_github_installations(
organization: Organization,
exclude_team_id: int | None = None,
) -> list[dict[str, Any]]:
- """List the distinct GitHub App installations ``user`` may reuse within ``organization``.
+ """List the distinct GitHub App installations ``user`` can link to a project in ``organization``.
A GitHub App installs once per org, so when an org has more than one installation the caller
can't rely on the single-install auto-resolve path in ``link_existing_team_github_integration``.
@@ -524,28 +607,34 @@ def list_org_github_installations(
``installation_id``. The first integration seen for each installation id (deterministic
``order_by("id")``) provides the representative account metadata and source team.
- Only installations linked to source projects the user can access are returned — mirroring the
- access boundary enforced in ``link_existing_team_github_integration`` so the picker never
- surfaces an installation the user couldn't actually link.
+ Only installations linked to source projects the user can access are returned as sibling
+ entries (``source_team_id`` set) — mirroring the access boundary enforced in
+ ``link_existing_team_github_integration`` so the picker never surfaces an installation the user
+ couldn't actually link that way.
+
+ Installations visible to the user's own personal GitHub token but not yet linked to any team in
+ the org are also included, with ``source_team_id: None`` — these are adoptable orphans (see
+ ``adopt_orphan_installation``). Entries already present as a sibling installation are not
+ duplicated.
"""
+ accessible_team_ids = _accessible_org_team_ids(user, organization)
org_github = defer_repository_cache_fields(
- Integration.objects.filter(
- team__organization_id=organization.id,
- team_id__in=_accessible_org_team_ids(user, organization),
- kind="github",
- )
- )
- if exclude_team_id is not None:
- org_github = org_github.exclude(team_id=exclude_team_id)
- org_github = org_github.order_by("id")
+ Integration.objects.filter(team__organization_id=organization.id, kind="github")
+ ).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()
for integration in org_github:
config = integration.config or {}
raw_installation_id = config.get("installation_id")
if not raw_installation_id:
continue
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:
+ continue
if installation_id in installations:
continue
account = config.get("account") or {}
@@ -555,6 +644,23 @@ def list_org_github_installations(
"account_type": account.get("type"),
"source_team_id": integration.team_id,
}
+
+ personal_installations = 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:
+ continue
+ account = raw_installation.get("account") or {}
+ installations[installation_id] = {
+ "installation_id": installation_id,
+ "account_name": account.get("login"),
+ "account_type": account.get("type"),
+ "source_team_id": None,
+ }
+
return list(installations.values())
diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.py
index 2586c3290473..22e298c6df93 100644
--- a/posthog/api/github_callback/types.py
+++ b/posthog/api/github_callback/types.py
@@ -18,7 +18,9 @@ from posthog.models.instance_setting import get_instance_settings
GITHUB_INSTALL_STATE_CACHE_PREFIX = "github_user_install_state:"
GITHUB_INSTALL_STATE_TTL_SECONDS = 10 * 60
-GITHUB_INSTALLATION_ID_PATTERN = re.compile(r"\d{1,20}")
+# No leading zeros: security checks compare these ids as strings against DB-stored canonical
+# values, so "0111" must not validate and then miss an equality check against "111".
+GITHUB_INSTALLATION_ID_PATTERN = re.compile(r"[1-9]\d{0,19}")
GITHUB_AUTHORIZE_STATE_CACHE_TTL_SECONDS = 60 * 15
GITHUB_UNIFIED_AUTHORIZE_CACHE_PREFIX = "github_authorize:"
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 0ab02a3c27b1..12f5ff700183 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -24,6 +24,7 @@ from rest_framework.response import Response
from slack_sdk.errors import SlackApiError
from 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.team_services import (
build_team_oauth_authorize_url,
create_team_github_integration_from_oauth_code,
@@ -953,14 +954,23 @@ class GitHubAvailableInstallationSerializer(serializers.Serializer):
help_text="GitHub account type, e.g. 'Organization' or 'User'.",
)
source_team_id = serializers.IntegerField(
- help_text="A project in the organization that already has this installation linked.",
+ allow_null=True,
+ help_text="A project in the organization that already has this installation linked. "
+ "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.",
)
class GitHubAvailableInstallationsResponseSerializer(serializers.Serializer):
installations = GitHubAvailableInstallationSerializer(
many=True,
- help_text="Distinct GitHub installations in the organization available to link to this project.",
+ help_text="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.",
+ )
+ personal_github_connected = serializers.BooleanField(
+ help_text="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.",
)
@@ -1648,18 +1658,27 @@ class IntegrationViewSet(
@extend_schema(responses={200: GitHubAvailableInstallationsResponseSerializer})
@action(methods=["GET"], detail=False, url_path="github/available_installations")
def github_available_installations(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- """List the org's existing GitHub installations this project can reuse.
+ """List GitHub installations this project can link.
A GitHub App installs once per organization, so a second project links an existing
- installation rather than reinstalling. This backs the picker: when the org has more than
- one installation, the client passes the chosen installation_id to github/link_existing.
+ installation rather than reinstalling. This backs the picker: when more than one option
+ exists, the client passes the chosen installation_id to github/link_existing. The list also
+ includes installations the user's personal GitHub link can see but that aren't linked to any
+ project yet (``source_team_id: null``) — orphan installations approved on GitHub outside
+ PostHog's callback, which ``github/link_existing`` can adopt.
"""
+ user = cast(User, request.user)
installations = list_org_github_installations(
- user=cast(User, request.user),
+ user=user,
organization=self.organization,
exclude_team_id=self.team_id,
)
- return Response({"installations": GitHubAvailableInstallationSerializer(installations, many=True).data})
+ return Response(
+ {
+ "installations": GitHubAvailableInstallationSerializer(installations, many=True).data,
+ "personal_github_connected": user_has_personal_github_integration(user),
+ }
+ )
@extend_schema(
request=GitHubLinkExistingRequestSerializer,
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 3fe22c970e77..4f8d626fb93d 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -20,6 +20,7 @@ from rest_framework import status
from rest_framework.exceptions import ValidationError
from slack_sdk.errors import SlackApiError
+from posthog.api.github_callback.personal_state import usable_personal_github_token
from posthog.api.github_callback.state import store_unified_authorize_state
from posthog.api.github_callback.team_services import (
GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
@@ -31,6 +32,7 @@ from posthog.api.github_callback.team_services import (
from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
from posthog.api.integration import IntegrationSerializer, IntegrationViewSet
from posthog.constants import AvailableFeature
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted
from posthog.models.integration import (
ERROR_TOKEN_REFRESH_FAILED,
GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,
@@ -3154,6 +3156,20 @@ class TestGitHubTeamIntegrationComplete:
codes = exc_info.value.get_codes()
assert isinstance(codes, list) and GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED in codes
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ def test_authorize_link_existing_proves_non_admin_access_with_personal_oauth_token(self, mock_verify):
+ # The proof must run on the user-to-server OAuth token, not the installation-scoped
+ # access_token: /user/installations/{id}/repositories authenticates as the user, and an
+ # installation token from a different installation would fail for a legitimate member.
+ member = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER
+ )
+ self._personal_github_integration(member)
+
+ authorize_link_existing_installation(user=member, team=self.team, source_installation_id="12345")
+
+ mock_verify.assert_called_once_with("12345", "gho_personal_token")
+
@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
def test_link_existing_auto_resolves_single_org_installation(self, mock_from_install):
# The one-click "Link existing installation" UI sends no source_team_id / installation_id;
@@ -3281,6 +3297,17 @@ class TestGitHubTeamIntegrationComplete:
sensitive_config={"access_token": f"ghs_{installation_id}"},
)
+ def _personal_github_integration(self, user: User, github_login: str = "personaluser") -> UserIntegration:
+ # No expiry timestamps in config: `get_usable_user_access_token` then returns this token
+ # directly without a refresh network call, matching a freshly-linked personal integration.
+ return UserIntegration.objects.create(
+ user=user,
+ kind="github",
+ integration_id="55555",
+ config={"github_user": {"login": github_login, "id": 1}},
+ sensitive_config={"user_access_token": "gho_personal_token"},
+ )
+
def test_link_existing_rejects_installation_from_inaccessible_source_project(self):
# A user who admins the target project but is locked out of a private sibling must not be able
# to discover or reuse that sibling's installation — target-team admin is not access to the
@@ -3305,6 +3332,29 @@ class TestGitHubTeamIntegrationComplete:
codes = exc_info.value.get_codes()
assert isinstance(codes, list) and GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION in codes
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ def test_link_existing_never_adopts_installation_linked_to_inaccessible_project(self, mock_verify):
+ # Personal GitHub access must not override the project access boundary: an installation
+ # linked to a private sibling isn't an orphan, so adoption must not even be attempted,
+ # however legitimate the caller's GitHub-side access to it is.
+ member = self._org_member_with_access_control()
+ self._personal_github_integration(member)
+ self._sibling_github_integration("Private Project", "777", private=True)
+
+ with pytest.raises(ValidationError) as exc_info:
+ link_existing_team_github_integration(
+ user=member,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="777",
+ )
+
+ codes = exc_info.value.get_codes()
+ assert isinstance(codes, list) and GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION in codes
+ mock_verify.assert_not_called()
+ assert not Integration.objects.filter(team=self.team, kind="github", integration_id="777").exists()
+
@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
def test_link_existing_links_installation_also_held_by_an_inaccessible_project(self, mock_from_install):
# One installation shared by a private project and an accessible one. Resolving the source
@@ -3450,6 +3500,260 @@ class TestGitHubTeamIntegrationComplete:
assert f"integration_id={team_integration.id}" in response["Location"]
mock_refresh.assert_called_once()
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_link_existing_adopts_orphan_installation_with_personal_github_proof(self, mock_from_install, mock_verify):
+ # No PostHog team anywhere has installation "424242" linked, so it's a true orphan: installed
+ # on GitHub but never round-tripped through PostHog's callback. Proving personal access to it
+ # must create the team integration instead of raising the old unconditional orphan error.
+ self._personal_github_integration(self.user)
+ mock_from_install.side_effect = lambda *args, **kwargs: self._team_github_integration(installation_id="424242")
+
+ result = link_existing_team_github_integration(
+ user=self.user,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="424242",
+ )
+
+ assert result is not None
+ assert mock_from_install.call_args.args[0] == "424242"
+ assert mock_from_install.call_args.args[1] == self.team.pk
+ mock_verify.assert_called_once_with("424242", "gho_personal_token")
+ integration = Integration.objects.get(team=self.team, kind="github", integration_id="424242")
+ assert integration.config["connecting_user_github_login"] == "personaluser"
+
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=False)
+ def test_link_existing_adoption_rejects_when_verification_fails(self, _mock_verify):
+ self._personal_github_integration(self.user)
+
+ with pytest.raises(ValidationError) as exc_info:
+ link_existing_team_github_integration(
+ user=self.user,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="424242",
+ )
+
+ codes = exc_info.value.get_codes()
+ assert isinstance(codes, list) and "installation_access_denied" in codes
+ assert not Integration.objects.filter(kind="github", integration_id="424242").exists()
+
+ @patch(
+ "posthog.models.integration.GitHubIntegration.verify_user_installation_access",
+ side_effect=requests.RequestException("boom"),
+ )
+ def test_link_existing_adoption_rejects_when_verification_errors(self, _mock_verify):
+ self._personal_github_integration(self.user)
+
+ with pytest.raises(ValidationError):
+ link_existing_team_github_integration(
+ user=self.user,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="424242",
+ )
+
+ assert not Integration.objects.filter(kind="github", integration_id="424242").exists()
+
+ @parameterized.expand([("member",), ("admin",)])
+ def test_link_existing_adoption_requires_personal_github_regardless_of_admin(self, role):
+ # Adoption needs both gates: project admin (a new installation entering the org is a
+ # first-time connect, same bar as the setup callback) and personal GitHub proof (admin on
+ # the PostHog side proves nothing about GitHub). A member fails the admin gate outright;
+ # an admin without a personal link still fails the proof gate.
+ if role == "admin":
+ user = self.user
+ expected_code = GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED
+ else:
+ user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER
+ )
+ expected_code = "github_adoption_admin_required"
+ assert not UserIntegration.objects.filter(user=user, kind="github").exists()
+
+ with pytest.raises(ValidationError) as exc_info:
+ link_existing_team_github_integration(
+ user=user,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="424242",
+ )
+
+ codes = exc_info.value.get_codes()
+ assert isinstance(codes, list) and expected_code in codes
+ assert not Integration.objects.filter(kind="github", integration_id="424242").exists()
+
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ def test_link_existing_adoption_refuses_member_even_with_valid_github_proof(self, mock_verify):
+ # Valid personal GitHub access must not let a plain member introduce a new installation to
+ # the org: unlike the create/update flows, adoption has no GitHub-side gate on who submits
+ # the installation id, so the project-admin requirement is what stands in for it.
+ member = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER
+ )
+ self._personal_github_integration(member)
+
+ with pytest.raises(ValidationError) as exc_info:
+ link_existing_team_github_integration(
+ user=member,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="424242",
+ )
+
+ codes = exc_info.value.get_codes()
+ assert isinstance(codes, list) and "github_adoption_admin_required" in codes
+ mock_verify.assert_not_called()
+ assert not Integration.objects.filter(kind="github", integration_id="424242").exists()
+
+ @patch("posthog.api.github_callback.personal_state.github_request")
+ def test_available_installations_includes_adoptable_and_dedupes_sibling(self, mock_request):
+ # The picker must offer both kinds of installation together: ones already linked to a
+ # sibling project (source_team_id set) and ones only visible via the user's personal GitHub
+ # link (source_team_id null). A personal installation that's already a sibling entry must
+ # not be listed twice.
+ sibling = self._sibling_github_integration("Acme Org", "111")
+ self._personal_github_integration(self.user)
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "installations": [
+ {"id": 111, "account": {"login": "Acme Org", "type": "Organization"}},
+ {"id": 222, "account": {"login": "coderabbitai", "type": "Organization"}},
+ ]
+ }
+ mock_request.return_value = mock_response
+
+ installations = list_org_github_installations(
+ user=self.user, organization=self.organization, exclude_team_id=self.team.pk
+ )
+
+ by_id = {installation["installation_id"]: installation for installation in installations}
+ assert set(by_id.keys()) == {"111", "222"}
+ assert by_id["111"]["source_team_id"] == sibling.team_id
+ assert by_id["222"]["source_team_id"] is None
+ assert by_id["222"]["account_name"] == "coderabbitai"
+ assert by_id["222"]["account_type"] == "Organization"
+
+ @pytest.mark.parametrize("fetch_error", [requests.RequestException("boom"), GitHubEgressBudgetExhausted()])
+ @patch("posthog.api.github_callback.personal_state.github_request")
+ def test_available_installations_degrades_to_sibling_only_when_personal_fetch_fails(
+ self, mock_request, fetch_error
+ ):
+ # A stale personal token, a GitHub outage, or our own exhausted egress budget must not
+ # break the sibling-only listing that already worked before adoption existed.
+ mock_request.side_effect = fetch_error
+ sibling = self._sibling_github_integration("Acme Org", "111")
+ self._personal_github_integration(self.user)
+
+ installations = list_org_github_installations(
+ user=self.user, organization=self.organization, exclude_team_id=self.team.pk
+ )
+
+ assert [installation["installation_id"] for installation in installations] == ["111"]
+ assert installations[0]["source_team_id"] == sibling.team_id
+
+ @patch("posthog.api.github_callback.personal_state.UserGitHubIntegration.get_usable_user_access_token")
+ def test_usable_personal_github_token_falls_back_to_older_link(self, mock_get_token):
+ # The newest personal link can hold stale credentials while an older one still refreshes.
+ mock_get_token.side_effect = [requests.RequestException("stale"), "gho_older_token"]
+ self._personal_github_integration(self.user)
+ older = UserIntegration.objects.create(
+ user=self.user,
+ kind="github",
+ integration_id="66666",
+ config={"github_user": {"login": "personaluser", "id": 1}},
+ sensitive_config={"user_access_token": "gho_older_token"},
+ )
+ older.created_at = older.created_at - timedelta(days=30)
+ older.save(update_fields=["created_at"])
+
+ assert usable_personal_github_token(self.user) == "gho_older_token"
+ assert mock_get_token.call_count == 2
+
+ @patch("posthog.models.integration.GitHubIntegration.verify_user_installation_access", return_value=True)
+ def test_link_existing_rejects_leading_zero_installation_id(self, mock_verify):
+ # "0111" would miss the string-equality check against the stored "111" and fall through to
+ # adoption of an installation a private sibling already holds, so it must fail validation.
+ member = self._org_member_with_access_control()
+ self._personal_github_integration(member)
+ self._sibling_github_integration("Private Project", "111", private=True)
+
+ with pytest.raises(ValidationError, match="Invalid installation_id"):
+ link_existing_team_github_integration(
+ user=member,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param="0111",
+ )
+
+ mock_verify.assert_not_called()
+
+ @patch("posthog.api.github_callback.personal_state.github_request")
+ def test_available_installations_never_advertises_installation_linked_to_inaccessible_project(self, mock_request):
+ # Personal GitHub access to an installation must not surface a private sibling's install in
+ # the picker — that would advertise an adoption link_existing then has to refuse.
+ member = self._org_member_with_access_control()
+ self._personal_github_integration(member)
+ self._sibling_github_integration("Private Project", "777", private=True)
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "installations": [{"id": 777, "account": {"login": "Private Org", "type": "Organization"}}]
+ }
+ mock_request.return_value = mock_response
+
+ installations = list_org_github_installations(
+ user=member, organization=self.organization, exclude_team_id=self.team.pk
+ )
+
+ assert installations == []
+
+ @patch("posthog.api.github_callback.personal_state.github_request", side_effect=requests.RequestException("boom"))
+ def test_available_installations_endpoint_still_reports_connected_when_fetch_fails(
+ self, _mock_request, client: HttpClient
+ ):
+ # Pins today's behavior on a transient GitHub failure: the personal link still reports
+ # connected while adoptable entries are silently absent, so the UI shows no hint. If this
+ # changes, it should be to surface the failed check, not to flip connected to false.
+ client.force_login(self.user)
+ self._personal_github_integration(self.user)
+ self._sibling_github_integration("Acme Org", "111")
+
+ response = client.get(f"/api/environments/{self.team.pk}/integrations/github/available_installations/")
+
+ assert response.status_code == status.HTTP_200_OK
+ payload = response.json()
+ assert payload["personal_github_connected"] is True
+ assert [entry["installation_id"] for entry in payload["installations"]] == ["111"]
+
+ @pytest.mark.parametrize("connected", [True, False])
+ @patch("posthog.api.github_callback.personal_state.github_request")
+ def test_available_installations_endpoint_reports_personal_github_connected(
+ self, mock_request, connected, client: HttpClient
+ ):
+ # Wiring guard: the service-level tests above prove the merge/degrade logic; this proves the
+ # viewset actually surfaces `personal_github_connected` in the response.
+ client.force_login(self.user)
+ if connected:
+ self._personal_github_integration(self.user)
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"installations": []}
+ mock_request.return_value = mock_response
+
+ response = client.get(f"/api/environments/{self.team.pk}/integrations/github/available_installations/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["personal_github_connected"] is connected
+
class TestStripeIntegration:
@pytest.fixture(autouse=True)
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index 112acc724408..4fc9d1789a56 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -15,7 +15,6 @@ import os
from typing import Any, cast
from urllib.parse import urlencode
-import requests
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
@@ -26,6 +25,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.github_callback import state as github_callback_state
+from posthog.api.github_callback.personal_state import list_user_github_app_installations
from posthog.api.github_callback.types import (
APP_CONNECT_FROM_VALUES,
PERSONAL_INTEGRATIONS_SETTINGS_PATH,
@@ -44,7 +44,7 @@ from posthog.api.integration import (
validate_github_repository_name,
)
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
-from posthog.egress.github.transport import GitHubRateLimitError, github_request
+from posthog.egress.github.transport import GitHubRateLimitError
from posthog.exceptions_capture import capture_exception
from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integration
from posthog.models.user import User
@@ -701,45 +701,15 @@ def _resolve_team_for_github_start(user: User, request: Request):
def _has_unlinked_github_installations(user: User) -> bool | None:
"""Check whether the user has GitHub App installations they haven't linked yet.
- Uses the user's existing OAuth token to call ``GET /user/installations``
- and compares against their ``UserIntegration`` rows.
-
Returns ``True`` if unlinked installations exist, ``False`` if all are
linked, or ``None`` if the check couldn't be performed (no existing
integration, token refresh failed, network error).
"""
- any_integration = UserIntegration.objects.filter(user=user, kind="github").exclude(sensitive_config={}).first()
- if any_integration is None:
- return None
-
- github = UserGitHubIntegration(any_integration)
- try:
- token = github.get_usable_user_access_token()
- except Exception:
- return None
-
- try:
- # Identity-blind: user OAuth token, metered against the user's budget, not an installation's.
- response = github_request(
- "GET",
- "https://api.github.com/user/installations",
- source="integration",
- headers={"Authorization": f"Bearer {token}"},
- params={"per_page": 100},
- timeout=10,
- )
- except requests.RequestException:
- return None
-
- if response.status_code != 200:
- return None
-
- try:
- installations = response.json().get("installations", [])
- except Exception:
+ installations = list_user_github_app_installations(user)
+ if installations is None:
return None
- github_installation_ids = {str(inst["id"]) for inst in installations if isinstance(inst, dict) and "id" in inst}
+ github_installation_ids = {str(installation["id"]) for installation in installations}
linked_ids = set(UserIntegration.objects.filter(user=user, kind="github").values_list("integration_id", flat=True))
return bool(github_installation_ids - linked_ids)
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index e42e31d96eb9..1861118bb417 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -408,13 +408,18 @@ export interface GitHubAvailableInstallationApi {
* @nullable
*/
account_type: string | null
- /** A project in the organization that already has this installation linked. */
- source_team_id: number
+ /**
+ * A project in the organization that already has this installation linked. 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.
+ * @nullable
+ */
+ source_team_id: number | null
}
export interface GitHubAvailableInstallationsResponseApi {
- /** Distinct GitHub installations in the organization available to link to this project. */
+ /** 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. */
+ personal_github_connected: boolean
}
export interface GitHubLinkExistingRequestApi {
diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.ts
index 794ad2028130..86b72f60ba85 100644
--- a/products/integrations/frontend/generated/api.ts
+++ b/products/integrations/frontend/generated/api.ts
@@ -678,11 +678,14 @@ export const getIntegrationsGithubAvailableInstallationsRetrieveUrl = (projectId
}
/**
- * List the org's existing GitHub installations this project can reuse.
+ * List GitHub installations this project can link.
*
* A GitHub App installs once per organization, so a second project links an existing
- * installation rather than reinstalling. This backs the picker: when the org has more than
- * one installation, the client passes the chosen installation_id to github/link_existing.
+ * installation rather than reinstalling. This backs the picker: when more than one option
+ * exists, the client passes the chosen installation_id to github/link_existing. The list also
+ * includes installations the user's personal GitHub link can see but that aren't linked to any
+ * project yet (``source_team_id: null``) — orphan installations approved on GitHub outside
+ * PostHog's callback, which ``github/link_existing`` can adopt.
*/
export const integrationsGithubAvailableInstallationsRetrieve = async (
projectId: string,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 01d6f170e9bc..a6abfcc0732e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35304,13 +35304,18 @@ export namespace Schemas {
* @nullable
*/
account_type: string | null;
- /** A project in the organization that already has this installation linked. */
- source_team_id: number;
+ /**
+ * A project in the organization that already has this installation linked. 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.
+ * @nullable
+ */
+ source_team_id: number | null;
}
export interface GitHubAvailableInstallationsResponse {
- /** Distinct GitHub installations in the organization available to link to this project. */
+ /** 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. */
+ personal_github_connected: boolean;
}
export interface GitHubBranchesResponse {