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): allow GitHub App to connect multiple projects per org (#69916)

posthog[bot]f34b67311d64
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 923e2d6f9e91..c00b7a6d18b4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6743,9 +6743,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-details--light:
hash: v1.k794b7964.d4b5e0030757796876fa680f389ca76201f098f3b1b65eb303ca73b5e1be6ae4.nm2ebJO-70lgkubc-wOB4EFtPnO-885kq4I93mt0TNs
scenes-app-settings-environment--settings-environment-error-tracking--dark:
- hash: v1.k794b7964.d9746c3b1642ad99c59abb47fca6148f7fef38360db45495f4021ef44d29f11b.BJPn8eeV7whhcq_hIw8THSYQwJKAysey6wDSaVSxmD8
+ hash: v1.k794b7964.8c31cf4377cc4aa217ef13e05c56ccfa53994f780b73471c5d0982de4fa78d64.347ACdUg244bCzms7KAIMTpLv1WjkTahcO-uJXTkiyg
scenes-app-settings-environment--settings-environment-error-tracking--light:
- hash: v1.k794b7964.34564919bb8e3dd4c4f3f2d929ac349c0f4e68511a52370ca1a98688a5a791e6.TdwiSrM8i4SiYlk_3cucgjew961g8Fi0OnvgTlL5suA
+ hash: v1.k794b7964.26a597269ab5fffa13b4ee537a28a9dbb6dea5b74d2ba7c476792d89fea18f2e.TkgSHX0A7P-GqH7EyapdL8uq40FkIW2sq0tdL5EouTc
scenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:
hash: v1.k794b7964.56ec7a0f848a210db0b28301b8de7a858daa47b4075114d92e49dcc314e53771.eBsNSzM5P7mAshc2EMJhB6A8K6MuESVzMaT_zktP0jI
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
@@ -6759,9 +6759,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-heatmaps--light:
hash: v1.k794b7964.05c858527b6a3deecc54799e4d4fad6c2b88ff83a26dc0baadff3448bf6635b4.u3Xak3I8OzaYGlO_KlLOvHMh7sWvmjOVDrKURMJBQLs
scenes-app-settings-environment--settings-environment-integrations--dark:
- hash: v1.k794b7964.267d7524ca5fcccbcf3bcc4976aa5a5712732f2da1536d6acba79fb92c82e6ff.4A2m7dOY1F_x7oGH2mYvR9MPO15YyDETZrMFnhFbKcc
+ hash: v1.k794b7964.81a9ac1dae6f0520d24618ca1164d13febe35d137184e985a344dcd1632e0cec.fQFE2wr9G3dtsonE4swvWZ_5-LveeCtXd6lkJAqR2pg
scenes-app-settings-environment--settings-environment-integrations--light:
- hash: v1.k794b7964.bdb297f3f990891a6ddebf4c59c2b3c4a80389703a299cdd5686dc2aa28ed0db.YCcA9PQsfM7ia2p_ELBJ8xWt1TV0aQzsUzxQCTLSPl8
+ hash: v1.k794b7964.1934174417b65042ff2e3e967e833f604198ee713c7f7711f67b57646d9326a1.s9GyCmxzjPtnJ5aQsAbXkjY0WFJxqavzA2JTDDgFi34
scenes-app-settings-environment--settings-environment-marketing-analytics--dark:
hash: v1.k794b7964.72d483d5eeffbd82927b8b748abb1f6a624ed157f86db39b7c231b26e1c0a574.DdQZfV_I433UB3bh4bmxnivledUaDRg0EVOIWqWfTOQ
scenes-app-settings-environment--settings-environment-marketing-analytics--light:
@@ -6779,9 +6779,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-product-analytics--light:
hash: v1.k794b7964.42878951a5a737ae797432ce85c2cbf0763fb9ac3a62eb1e47d20151a3e278d5.k-NnRkG14-uobsxt6XWRHYJNmy15Kba83FzaYuIWe3k
scenes-app-settings-environment--settings-environment-replay--dark:
- hash: v1.k794b7964.08644ed36d368da1fae9b0d32966dc3a6c7c577e5a42b36ca20bda2c9f8842d0.3zlijaWwPUmQgX_BlNEqraL6KmRHP-T-FFI7IRDuvgI
+ hash: v1.k794b7964.420f87c12f0437816ce82f7e13a45851e78a6e84198cbd81262c964a90bdc47e.CaLkZAptUT5gtkAbv8PMsSfuCUSfKnhks4ojIwUks0E
scenes-app-settings-environment--settings-environment-replay--light:
- hash: v1.k794b7964.5482609ec0a994d99850b77a02fea74d49b852e26f74b4cb8c0482549e577206.lz8X59e56V7-bHY3PXD5IXkECw8IQEGKRM0WxYmNx80
+ hash: v1.k794b7964.7eff7d4f78ea0ebea1712c75a344af72769a1370cb89df2207419498ec5ca613.BYQaF3dooPNLprvFYODHlQwcc6VmfgnZ81Td6MzcOd0
scenes-app-settings-environment--settings-environment-revenue-analytics--dark:
hash: v1.k794b7964.f43cea177c46b279176a719412b6c25cc7c38f91c263587411c23aebf3814e35.dIeCQK0M_i9Ii0B-xfK5gaIxfY9nX1BZuhKwm2UukU8
scenes-app-settings-environment--settings-environment-revenue-analytics--light:
@@ -6843,17 +6843,17 @@ snapshots:
scenes-app-settings-project--settings-project-details--light:
hash: v1.k794b7964.b1a9ae1806176e7fbf86e77a213017877a903dae86ec32a7836b67e463a82c76.D8CZqYjdoVO_RmUP49-RtsHB66w0ANl7yRgj_v-9vH4
scenes-app-settings-project--settings-project-integrations--dark:
- hash: v1.k794b7964.267d7524ca5fcccbcf3bcc4976aa5a5712732f2da1536d6acba79fb92c82e6ff.0vc6z4hUfajTpJq8APgEwREXcjOpatjwkvqasakpZz8
+ hash: v1.k794b7964.81a9ac1dae6f0520d24618ca1164d13febe35d137184e985a344dcd1632e0cec.oySHN778JskP5Yz0hvSlx4gjJijO83k8OJLXyCNqb1w
scenes-app-settings-project--settings-project-integrations--light:
- hash: v1.k794b7964.bdb297f3f990891a6ddebf4c59c2b3c4a80389703a299cdd5686dc2aa28ed0db.cvulZy42NwBA199hucM177b-km651eDMUwzij5Vwvv4
+ hash: v1.k794b7964.1934174417b65042ff2e3e967e833f604198ee713c7f7711f67b57646d9326a1.DxQZ3xs0WrHP48Y9r13SVaHcJsN4h1KJVK-NSPUSXpg
scenes-app-settings-project--settings-project-product-analytics--dark:
hash: v1.k794b7964.45ea7514f9bccedbd5ae65668dd7371f224a979516841725244f373eeff5368e.evnI8G2A5e-j4FXrMDySKcCpeXKTFgOOS_Ke0u_72qc
scenes-app-settings-project--settings-project-product-analytics--light:
hash: v1.k794b7964.60b35997018c27307f9b9095cafa3a7ff618d500769e8c2f65f3ad43b54d2310.aMhUrmnvzq6XNQFQN0iwciI3HhAWPfRLX9NAuyaszGQ
scenes-app-settings-project--settings-project-replay--dark:
- hash: v1.k794b7964.37645030b128dacaf0f8bb7d58ab202b5b3c755e42d29578041ff9a9092a76bc.4zHd_UrRAjEOvFumCS-5WMgs0ZE4-RiO_W8pM3dm_yw
+ hash: v1.k794b7964.420f87c12f0437816ce82f7e13a45851e78a6e84198cbd81262c964a90bdc47e.MbG5FcxBuIFHRdrwoHEbyKJb_Pz8doVuDwvq1AaJeXM
scenes-app-settings-project--settings-project-replay--light:
- hash: v1.k794b7964.5482609ec0a994d99850b77a02fea74d49b852e26f74b4cb8c0482549e577206.gcAMR30ZD4v4xslRRhvd3diEilfz5bqR3D1MoTsRcII
+ hash: v1.k794b7964.7eff7d4f78ea0ebea1712c75a344af72769a1370cb89df2207419498ec5ca613.MmWu9UBGKmS-G4nQoVPXkW1Po6RDl327aG2XZYgKm-c
scenes-app-settings-project--settings-project-surveys--dark:
hash: v1.k794b7964.116b8618e7355d13ff8ddc83c5095b98edd1bca44d8326d7a05c2922e967b0d8.mYqdrV9UEmN1USMnHw5MMm3DWaOk8_s_BNmFP-aRMFU
scenes-app-settings-project--settings-project-surveys--light:
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 79ff0d158c4c..2b6a226946b7 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -131,7 +131,7 @@ export const integrationsLogic = kea<integrationsLogicType>([
},
],
}),
- loaders(({ values }) => ({
+ loaders(({ actions, values }) => ({
integrations: [
null as IntegrationType[] | null,
{
@@ -181,6 +181,25 @@ export const integrationsLogic = kea<integrationsLogicType>([
},
},
],
+ linkedGithubInstallation: [
+ null as IntegrationType | 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.
+ linkExistingGithubInstallation: async () => {
+ try {
+ const integration = await api.integrations.githubLinkExisting({})
+ lemonToast.success('Linked the existing GitHub installation to this project.')
+ actions.loadIntegrations()
+ return integration
+ } catch (e) {
+ toastApiError(e)
+ throw e
+ }
+ },
+ },
+ ],
accessRequest: [
null as IntegrationKind | null,
{
diff --git a/frontend/src/scenes/integrations/components/Integrations.tsx b/frontend/src/scenes/integrations/components/Integrations.tsx
index 04d168c51f8e..de8000c86df6 100644
--- a/frontend/src/scenes/integrations/components/Integrations.tsx
+++ b/frontend/src/scenes/integrations/components/Integrations.tsx
@@ -1,4 +1,4 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { PropsWithChildren, useMemo, useState } from 'react'
import { LemonButton } from '@posthog/lemon-ui'
@@ -29,7 +29,44 @@ export function LinearIntegration({ next }: { next?: string }): JSX.Element {
}
export function GithubIntegration({ next }: { next?: string }): JSX.Element {
- return <OAuthIntegration kind="github" connectText="Connect organization" next={next} />
+ const { currentTeam } = useValues(teamLogic)
+ const { linkedGithubInstallationLoading } = useValues(integrationsLogic)
+ const { linkExistingGithubInstallation } = useActions(integrationsLogic)
+ const githubIntegrations = useIntegrations('github')
+
+ const settingsPath = next ?? urls.settings('environment-integrations')
+ const authorizationUrl = api.integrations.authorizeUrl({
+ next: currentTeam?.id ? urls.project(currentTeam.id, settingsPath) : settingsPath,
+ kind: 'github',
+ })
+
+ return (
+ <Integration kind="github">
+ <div className="flex flex-col gap-y-2">
+ <div className="flex gap-x-2">
+ <LemonButton type="secondary" disableClientSideRouting to={authorizationUrl}>
+ Connect organization
+ </LemonButton>
+ {githubIntegrations.length === 0 && (
+ <LemonButton
+ type="secondary"
+ loading={linkedGithubInstallationLoading}
+ onClick={() => linkExistingGithubInstallation()}
+ >
+ Link existing installation
+ </LemonButton>
+ )}
+ </div>
+ {githubIntegrations.length === 0 && (
+ <p className="text-secondary text-xs mb-0">
+ Already installed the PostHog GitHub App for another project in this organization? A GitHub App
+ installs once per organization, so use "Link existing installation" to connect it here instead
+ of reinstalling.
+ </p>
+ )}
+ </div>
+ </Integration>
+ )
}
export function JiraIntegration({ next }: { next?: string }): JSX.Element {
diff --git a/posthog/api/github_callback/README.md b/posthog/api/github_callback/README.md
index 2987f4d712d8..9752d4237164 100644
--- a/posthog/api/github_callback/README.md
+++ b/posthog/api/github_callback/README.md
@@ -85,6 +85,18 @@ Env vars alone create nothing — you must complete the install flow:
- `code`; the frontend POSTs them and the `Integration(kind="github")` row is
created (and the repository cache begins syncing).
+### Connecting a second project to the same org
+
+A GitHub App installs **once per org**, so a second PostHog project in the same
+org can't reinstall it: GitHub shows "already configured" and may not redirect
+back with a fresh `code`. For that case the GitHub integration settings expose a
+**Link existing installation** button (`GithubIntegration` in
+`Integrations.tsx`), which POSTs to `integrations/github/link_existing`
+(`link_existing_team_github_integration`) and reuses the org's existing
+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`).
+
## Callback routes
| Route | Handler | Flow |
diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.py
index 043dcfeb9ed7..aedddb8f13cc 100644
--- a/posthog/api/github_callback/team_services.py
+++ b/posthog/api/github_callback/team_services.py
@@ -142,6 +142,47 @@ def create_team_github_integration_from_oauth_code(
return instance
+def authorize_link_existing_installation(
+ *,
+ user: User,
+ team: Team,
+ source_installation_id: str,
+) -> None:
+ """Confirm ``user`` may link an installation already present in their org to ``team``.
+
+ The installation is already linked to another team in the same organization, so the org
+ already has legitimate access to it. A user with admin access to the target team can therefore
+ attach another of the org's own projects to that installation without re-proving personal
+ GitHub access, because team admin within the org is sufficient ownership proof. This is what
+ lets a second PostHog project reuse a GitHub App that installs only once per org.
+
+ For anyone without team admin access (e.g. a plain member using the explicit link endpoint),
+ fall back to proving access with the user's personal GitHub OAuth token, raising
+ ``GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED`` when that proof is missing or fails.
+ """
+ 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
+ )
+ if not user_access_token:
+ raise ValidationError(
+ PERSONAL_GITHUB_REQUIRED_MESSAGE,
+ code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ )
+ try:
+ has_access = GitHubIntegration.verify_user_installation_access(source_installation_id, user_access_token)
+ except requests.RequestException:
+ raise ValidationError("Failed to verify installation access")
+ if not has_access:
+ raise ValidationError(
+ PERSONAL_GITHUB_REQUIRED_MESSAGE,
+ code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ )
+
+
def finish_team_github_setup_update(
*,
user: User,
@@ -212,28 +253,9 @@ def execute_team_github_finish_setup(
if not source_installation_id:
raise ValidationError("Source integration is missing installation_id")
- 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
+ authorize_link_existing_installation(
+ user=user, team=team, source_installation_id=str(source_installation_id)
)
- if not user_access_token:
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
- try:
- has_access = GitHubIntegration.verify_user_installation_access(
- str(source_installation_id), user_access_token
- )
- except requests.RequestException:
- raise ValidationError("Failed to verify installation access")
- if not has_access:
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
integration = GitHubIntegration.integration_from_installation_id(str(source_installation_id), team.id, user)
@@ -402,30 +424,43 @@ def link_existing_team_github_integration(
)
source = existing
else:
- raise ValidationError("source_team_id or installation_id is required")
+ # No source specified: auto-resolve the org's existing GitHub installation. This backs the
+ # one-click "Link existing installation" UI, where a second project reuses the org's single
+ # install without the caller having to know a sibling team id or the installation id.
+ org_github = (
+ Integration.objects.filter(team__organization_id=organization.id, kind="github")
+ .exclude(team_id=team_id)
+ .order_by("id")
+ )
+ distinct_installation_ids = {
+ str(config_installation_id)
+ for integration in org_github
+ if (config_installation_id := (integration.config or {}).get("installation_id"))
+ }
+ if not distinct_installation_ids:
+ raise ValidationError(
+ "No team in your organization has a GitHub installation to link",
+ code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ )
+ if len(distinct_installation_ids) > 1:
+ raise ValidationError(
+ "Your organization has multiple GitHub installations; specify which one to link via installation_id"
+ )
+ source = org_github.for_github_installation_id(next(iter(distinct_installation_ids))).first()
+ if source is None:
+ raise ValidationError(
+ "No team in your organization has a GitHub installation to link",
+ code=GITHUB_LINK_EXISTING_ERROR_ORPHAN_INSTALLATION,
+ )
installation_id = (source.config or {}).get("installation_id")
if not installation_id:
raise ValidationError("Source integration is missing installation_id")
- 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
- )
- if not user_access_token:
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
- try:
- has_access = GitHubIntegration.verify_user_installation_access(str(installation_id), user_access_token)
- except requests.RequestException:
- raise ValidationError("Failed to verify installation access")
- if not has_access:
- raise ValidationError(
- PERSONAL_GITHUB_REQUIRED_MESSAGE,
- code=GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
- )
+ target_team = organization.teams.filter(id=team_id).first()
+ if target_team is None:
+ raise ValidationError("Target team not found in your organization")
+ 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)
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 9856ae0ccbaf..c2c23a7faffa 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -17,8 +17,14 @@ from django.utils import timezone
import requests
from parameterized import parameterized
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from posthog.api.github_callback.state import store_unified_authorize_state
+from posthog.api.github_callback.team_services import (
+ GITHUB_LINK_EXISTING_ERROR_PERSONAL_GITHUB_REQUIRED,
+ authorize_link_existing_installation,
+ link_existing_team_github_integration,
+)
from posthog.api.github_callback.types import FlowKind, GitHubAuthorizeState
from posthog.api.integration import IntegrationSerializer, IntegrationViewSet
from posthog.models.integration import (
@@ -2956,6 +2962,108 @@ class TestGitHubTeamIntegrationComplete:
assert response["Location"].startswith("https://github.com/login/oauth/authorize")
mock_build_oauth_url.assert_called_once()
+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")
+ def test_admin_links_existing_org_installation_without_personal_github(self, mock_from_install, client: HttpClient):
+ # A GitHub App installs once per org, so a second project hits the Setup URL with
+ # setup_action=update and no OAuth code. A team admin must be able to complete that link
+ # off the installation already connected to a sibling team, without a personal GitHub link.
+ sibling = Team.objects.create(organization=self.organization, name="Sibling Team")
+ Integration.objects.create(
+ team=sibling,
+ kind="github",
+ integration_id="12345",
+ config={"installation_id": "12345", "connecting_user_github_login": "owneruser"},
+ sensitive_config={"access_token": "ghs_sibling"},
+ )
+ # self.user is an org admin with no UserIntegration (personal GitHub link).
+ assert not UserIntegration.objects.filter(user=self.user, kind="github").exists()
+ mock_from_install.side_effect = lambda *args, **kwargs: self._team_github_integration()
+
+ client.force_login(self.user)
+ next_path = f"/project/{self.team.pk}/integrations/github"
+ state_token = "link-existing-token"
+ store_unified_authorize_state(
+ GitHubAuthorizeState(
+ token=state_token,
+ flow=FlowKind.TEAM_INSTALL,
+ user_id=self.user.id,
+ team_id=self.team.pk,
+ next_url=next_path,
+ ),
+ )
+
+ response = client.get(
+ "/integrations/github/callback/",
+ {
+ "installation_id": "12345",
+ "setup_action": "update",
+ "state": urlencode({"next": next_path, "token": state_token}),
+ },
+ )
+
+ assert response.status_code == status.HTTP_302_FOUND
+ assert "github_setup_error" not in response["Location"]
+ assert Integration.objects.filter(team=self.team, kind="github", integration_id="12345").exists()
+
+ def test_authorize_link_existing_requires_personal_github_for_non_admin(self):
+ # The admin bypass must not leak to plain members: without team admin access and without a
+ # personal GitHub link, linking an existing installation still demands the personal token.
+ member = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER
+ )
+ with pytest.raises(ValidationError) as exc_info:
+ authorize_link_existing_installation(user=member, team=self.team, source_installation_id="12345")
+ 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.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;
+ # the service must resolve the org's single existing installation and link it to this team.
+ sibling = Team.objects.create(organization=self.organization, name="Sibling Team")
+ Integration.objects.create(
+ team=sibling,
+ kind="github",
+ integration_id="12345",
+ config={"installation_id": "12345"},
+ sensitive_config={"access_token": "ghs_sibling"},
+ )
+ mock_from_install.side_effect = lambda *args, **kwargs: self._team_github_integration()
+
+ result = link_existing_team_github_integration(
+ user=self.user,
+ organization=self.organization,
+ team_id=self.team.pk,
+ source_team_id=None,
+ installation_id_param=None,
+ )
+
+ assert result is not None
+ assert mock_from_install.call_args.args[0] == "12345"
+ assert mock_from_install.call_args.args[1] == self.team.pk
+
+ @parameterized.expand([("no_installations", []), ("ambiguous_installations", ["111", "222"])])
+ def test_link_existing_auto_resolve_rejects_when_not_exactly_one(self, _name, installation_ids):
+ # Auto-resolve is only safe when the org has exactly one installation: zero has nothing to
+ # link, and multiple is ambiguous, so the caller must disambiguate rather than guess.
+ for idx, installation_id in enumerate(installation_ids):
+ team = Team.objects.create(organization=self.organization, name=f"Sibling {idx}")
+ Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id=installation_id,
+ config={"installation_id": installation_id},
+ sensitive_config={"access_token": "ghs_sibling"},
+ )
+ 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=None,
+ )
+
def test_cross_user_state_rejected_on_unified_callback(self, client: HttpClient):
# State tokens are bound to a user via the pending-pointer cache key.
# Another admin in the same team must not be able to finish a callback