:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(integrations): Let project members add integrations (#67548)
Michael Matlokaf2507ebe2f44
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c9849c3d26fa..e0c8c6ea12b4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6767,7 +6767,7 @@ snapshots:scenes-app-settings-organization--settings-organization-details--dark:hash: v1.k794b7964.42bb07ba29e5727f687fd3792eff1df7c8cb4b536343c95d9e51658a89677e3e.cGfJpWmm01Oxd5JLWEfkzexgdZI7AGiVVPdWvziNzPIscenes-app-settings-organization--settings-organization-details--light:- hash: v1.k794b7964.5832cdd23724d21e797adaeb677a0ee983e7e61bd3ec7095aff87966b99a3f3b.hqLxN9o3Ki2bs4ZUCNCgCF07IvOl6mm-DzG0H3ku2S8+ hash: v1.k794b7964.29b8ac9b106df49b30d8acd6aeca3b24ff6f5754066f4f97d1e7b7ae5f6a0354.XR0nCLUHueSiJ3lsue0N67EIY-inQ5eoldh5MqE_iTgscenes-app-settings-organization--settings-organization-members--dark:hash: v1.k794b7964.9b7c856187e6b01c2abe4dfcfcba4593258de828b3a289d2924cfcf1fb5497dc.n-Z_pbWeZvSzYjKOkvb-ajQi97HcZHzhXCPKhN6M1g0scenes-app-settings-organization--settings-organization-members--light:@@ -7201,9 +7201,9 @@ snapshots:scenes-other-integration-landing-page--connected--light:hash: v1.k794b7964.ba48a93a593c5f797a544b13c655b8059d3543626607d8fb27d40861d209c50a.fqR6y3FcAFj555Q9VsR2DDKUtyI_BTR-Y9VR-576kN0scenes-other-integration-landing-page--no-permission--dark:- hash: v1.k794b7964.edc6fdc9b3a5c3eb31e0a8cdb73e13a12c619346e4d7eac30c59878750956f85.3Q-zDItMKYrHxBvyEFF7M3susL3DOxMcN7rJ8ChckU4+ hash: v1.k794b7964.674e5a613b6d3f2933862db144b0fab805875bfb9926e2f1f49e502c375363f5.HHRhYsPPj9lhRPMJvLxGHitZUPgG5-Zg9K3k26fM2kIscenes-other-integration-landing-page--no-permission--light:- hash: v1.k794b7964.7f93d512d0142c17eafe747de8bfcdd6961db0703ac3360a8be8d412cde4fc6a.WbhSRpAfD82DBbv6lJRATjNhISJKW-XAd3tpIoasJyY+ hash: v1.k794b7964.fe31b9b4308a40ebe93aaf37ac256bc1a21917798708dada68092982307706ac.GYO6l0kkFqPf9TA5o7k0AuLhY6WjXqxPCSUOI0ni8cAscenes-other-integration-landing-page--not-connected--dark:hash: v1.k794b7964.674e5a613b6d3f2933862db144b0fab805875bfb9926e2f1f49e502c375363f5.KcBmjEDBWtXtN_WsV0TL9ePVzhfYEyfr4qrLBdoyGyMscenes-other-integration-landing-page--not-connected--light:diff --git a/frontend/src/scenes/integrations/IntegrationFullPage.tsx b/frontend/src/scenes/integrations/IntegrationFullPage.tsxindex 7c85b81565d1..96ba4570c9c8 100644--- a/frontend/src/scenes/integrations/IntegrationFullPage.tsx+++ b/frontend/src/scenes/integrations/IntegrationFullPage.tsx@@ -67,10 +67,12 @@ function ConnectView({SettingsSection: SettingsSectionComponent}): JSX.Element {const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)- // Connecting an integration requires project admin access (enforced again in the backend).+ // Connecting an integration requires project membership (enforced again in the backend);+ // editing or removing one still requires admin. Users with no project access fall back to+ // the request-access flow below.const restrictionReason = useRestrictedArea({scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,+ minimumAccessLevel: TeamMembershipLevel.Member,})const onConnectClick = (): void => {diff --git a/frontend/src/scenes/integrations/components/Integrations.tsx b/frontend/src/scenes/integrations/components/Integrations.tsxindex 9f49772dea68..04d168c51f8e 100644--- a/frontend/src/scenes/integrations/components/Integrations.tsx+++ b/frontend/src/scenes/integrations/components/Integrations.tsx@@ -4,8 +4,6 @@ import { PropsWithChildren, useMemo, useState } from 'react'import { LemonButton } from '@posthog/lemon-ui'import api from 'lib/api'-import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { IntegrationView } from 'lib/integrations/IntegrationView'import { GitLabSetupModal } from 'scenes/integrations/gitlab/GitLabSetupModal'@@ -16,13 +14,9 @@ import { IntegrationKind, IntegrationType } from '~/types'export function GitLabIntegration(): JSX.Element {const [isOpen, setIsOpen] = useState<boolean>(false)- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })return (<Integration kind="gitlab">- <LemonButton type="secondary" onClick={() => setIsOpen(true)} disabledReason={restrictedReason}>+ <LemonButton type="secondary" onClick={() => setIsOpen(true)}>Connect project</LemonButton><GitLabSetupModal isOpen={isOpen} onComplete={() => setIsOpen(false)} />@@ -52,10 +46,6 @@ const OAuthIntegration = ({next?: string}): JSX.Element => {const { currentTeam } = useValues(teamLogic)- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })const settingsPath = next ?? urls.settings('environment-integrations')const authorizationUrl = api.integrations.authorizeUrl({next: currentTeam?.id ? urls.project(currentTeam.id, settingsPath) : settingsPath,@@ -64,12 +54,7 @@ const OAuthIntegration = ({return (<Integration kind={kind}>- <LemonButton- type="secondary"- disableClientSideRouting- to={authorizationUrl}- disabledReason={restrictedReason}- >+ <LemonButton type="secondary" disableClientSideRouting to={authorizationUrl}>{connectText}</LemonButton></Integration>diff --git a/frontend/src/scenes/integrations/components/SlackIntegration.tsx b/frontend/src/scenes/integrations/components/SlackIntegration.tsxindex bc3f50c2b39c..564b00ff4ff6 100644--- a/frontend/src/scenes/integrations/components/SlackIntegration.tsx+++ b/frontend/src/scenes/integrations/components/SlackIntegration.tsx@@ -5,8 +5,6 @@ import { LemonButton, Link } from '@posthog/lemon-ui'import api from 'lib/api'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'-import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { IntegrationView } from 'lib/integrations/IntegrationView'import { urls } from 'scenes/urls'@@ -56,18 +54,10 @@ export function SlackIntegration({ next }: { next?: string } = {}): JSX.Elementconst { slackIntegrations, slackAvailable } = useValues(integrationsLogic)const [showSlackInstructions, setShowSlackInstructions] = useState(false)const { user } = useValues(userLogic)- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })const requiredScopesArr = useSlackRequiredScopes()const requiredScopes = useMemo(() => requiredScopesArr.join(' '), [requiredScopesArr])- if (restrictedReason) {- return <p>{restrictedReason}</p>- }-return (<div><div className="deprecated-space-y-2">diff --git a/posthog/api/github_callback/state.py b/posthog/api/github_callback/state.pyindex ce91773350d3..7337c97f2b22 100644--- a/posthog/api/github_callback/state.py+++ b/posthog/api/github_callback/state.py@@ -61,6 +61,17 @@ def has_team_management_access(user: User, team: Team) -> bool:return level is not None and level >= OrganizationMembership.Level.ADMIN+def has_team_membership_access(user: User, team: Team) -> bool:+ """Whether ``user`` may add a new team-level integration for ``team``.++ Adding an integration only requires effective project membership; modifying or removing an+ existing one still requires admin (see ``has_team_management_access``). Mirrors+ ``TeamMemberAccessPermission`` on the DRF side.+ """+ level = UserPermissions(user).team(team).effective_membership_level+ return level is not None++def resolve_github_setup_callback_context(user: User,state_raw: str | None,diff --git a/posthog/api/github_callback/team_services.py b/posthog/api/github_callback/team_services.pyindex 10b36a0839eb..043dcfeb9ed7 100644--- a/posthog/api/github_callback/team_services.py+++ b/posthog/api/github_callback/team_services.py@@ -486,10 +486,23 @@ def finish_team_setup(http_request) -> FinishResult:# team deleted) are rare enough to not warrant a typed error; let them 500.team = Team.objects.select_related("organization").get(id=team_id)- # Membership alone isn't enough — creating a team integration requires admin access, matching- # the strict permission that gates setup initiation. The callback's team_id can come from a- # user-controlled `next`/`state` param, so a plain member must not complete the install here.- if not github_callback_state.has_team_management_access(user, team):+ # Adding a new team integration requires only project membership; modifying an existing one+ # (reconnect / settings update) still requires admin. The callback's team_id can come from a+ # user-controlled `next`/`state` param, so a plain member must never alter an integration that+ # already exists — only create the team's first link for this installation. State-token+ # validation downstream still guards against forged callbacks regardless of membership level.+ existing_team_integration = (+ Integration.objects.first_github_for_team_installation(team.id, installation_id_str)+ if is_valid_github_installation_id(installation_id_str)+ else None+ )+ modifying_existing = existing_team_integration is not None or setup_action == "update"+ has_required_access = (+ github_callback_state.has_team_management_access(user, team)+ if modifying_existing+ else github_callback_state.has_team_membership_access(user, team)+ )+ if not has_required_access:return FinishResult(redirect_kind="team_setup",next_url=next_url,diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex a0580a9279fa..83ce997cc735 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -6,6 +6,7 @@ from urllib.parse import urlencodefrom django.conf import settingsfrom django.core.cache import cache+from django.db import transactionfrom django.http import HttpResponsefrom django.shortcuts import redirectfrom django.utils import timezone@@ -408,6 +409,28 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerialreturn valuedef create(self, validated_data: Any) -> Any:+ team_id = self.context["team_id"]+ kind = validated_data["kind"]++ # `create` is a POST with upsert semantics: each kind's helper does an `update_or_create`+ # keyed on (team, kind, integration_id), so re-submitting the same resource overwrites the+ # existing integration instead of adding a new one. Adding is allowed for any project+ # member, but overwriting an existing integration is an edit and requires admin. If a+ # non-admin's request resolves to an integration that already existed, roll the write back+ # and reject.+ with transaction.atomic():+ existing_integration_ids = set(+ Integration.objects.filter(team_id=team_id, kind=kind).values_list("integration_id", flat=True)+ )+ instance = self._build_integration(validated_data)+ is_overwrite = instance.integration_id in existing_integration_ids+ if is_overwrite and not github_callback_state.has_team_management_access(+ self.context["request"].user, self.context["get_team"]()+ ):+ raise PermissionDenied("Editing an existing integration requires project admin access.")+ return instance++ def _build_integration(self, validated_data: Any) -> Any:request = self.context["request"]team_id = self.context["team_id"]@@ -887,22 +910,19 @@ class IntegrationViewSet(return super().handle_exception(exc)def dangerously_get_permissions(self):+ base_permissions = [+ IsAuthenticated(),+ APIScopePermission(),+ AccessControlPermission(),+ TeamMemberAccessPermission(),+ ]+ # Adding (connecting) an integration only requires project membership; editing or removing+ # one still requires admin, enforced by the default TeamMemberStrictManagementPermission.+ # The GitHub browser callback applies the same create-vs-modify split (see github_callback).+ if self.action in ("create", "github_link_existing", "github_oauth_authorize", "request_access"):+ return base_permissionsif self.action == "refresh_github_repos":- return [- IsAuthenticated(),- APIScopePermission(),- AccessControlPermission(),- TeamMemberAccessPermission(),- TeamMemberLightManagementPermission(),- ]- # Any project member may ask an admin to connect an integration — connecting still requires admin.- if self.action == "request_access":- return [- IsAuthenticated(),- APIScopePermission(),- AccessControlPermission(),- TeamMemberAccessPermission(),- ]+ return [*base_permissions, TeamMemberLightManagementPermission()]raise NotImplementedError()def get_throttles(self):diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 8196542184c8..a333a83fdcb7 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -2296,14 +2296,15 @@ class TestGitHubTeamIntegrationComplete:assert cache.get(f"github_authorize:{state_token}") is Noneassert cache.get(f"github_authorize_pending:{self.user.id}") is None- def test_non_admin_member_cannot_complete_team_install(self, client: HttpClient):+ def test_forged_state_cannot_complete_team_install(self, client: HttpClient):member = User.objects.create_and_join(self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER)client.force_login(member)# No valid authorize state — the member supplies the team via the user-controlled `state` `next`,- # which resolves team_id purely from the path. Membership alone must not let them complete it.+ # which resolves team_id purely from the path. Membership now suffices to *add* an integration, so+ # state-token validation (not the permission gate) is what must stop a forged callback from creating one.next_path = f"/project/{self.team.pk}/integrations/github"response = client.get("/integrations/github/callback/",@@ -2316,9 +2317,75 @@ class TestGitHubTeamIntegrationComplete:)assert response.status_code == status.HTTP_302_FOUND- assert "github_setup_error=insufficient_permissions" in response["Location"]+ assert "github_setup_error=invalid_state" in response["Location"]assert not Integration.objects.filter(team=self.team, kind="github").exists()+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")+ @patch("posthog.models.integration.GitHubIntegration.github_user_from_code")+ @patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")+ @patch("posthog.models.user_integration.user_github_integration_from_installation")+ def test_member_can_complete_fresh_team_install(+ self, mock_user_integration, mock_from_install, mock_from_code, mock_verify, client: HttpClient+ ):+ # Adding a brand-new integration only requires project membership.+ member = User.objects.create_and_join(+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER+ )+ client.force_login(member)+ next_path = f"/project/{self.team.pk}/settings/environment-integrations"+ state_token = "member-install-token"+ store_unified_authorize_state(+ GitHubAuthorizeState(+ token=state_token,+ flow=FlowKind.TEAM_INSTALL,+ user_id=member.id,+ team_id=self.team.pk,+ next_url=next_path,+ ),+ )+ mock_from_code.return_value = self._github_user_authorization()+ mock_verify.return_value = True+ # side_effect (not return_value) so the row is created when execute runs — after the+ # permission check — matching a genuine first-time install where nothing exists yet.+ mock_from_install.side_effect = lambda *args, **kwargs: self._team_github_integration()++ response = client.get(+ "/integrations/github/callback/",+ {+ "installation_id": "12345",+ "code": "oauth-code-abc",+ "setup_action": "install",+ "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_member_cannot_modify_existing_team_integration(self, client: HttpClient):+ # An integration already exists, so completing the callback would *modify* it — that still needs admin.+ existing = self._team_github_integration()+ member = User.objects.create_and_join(+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.MEMBER+ )+ client.force_login(member)+ next_path = f"/project/{self.team.pk}/integrations/github"++ response = client.get(+ "/integrations/github/callback/",+ {+ "installation_id": "12345",+ "setup_action": "update",+ "state": urlencode({"next": next_path, "token": "no-such-token"}),+ },+ )++ assert response.status_code == status.HTTP_302_FOUND+ assert "github_setup_error=insufficient_permissions" in response["Location"]+ # The existing integration must be untouched — no member-driven reconnect.+ assert Integration.objects.filter(id=existing.id).count() == 1+@patch("posthog.models.github_integration_base.GitHubIntegrationBase.verify_user_installation_access")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")@@ -4306,6 +4373,69 @@ class TestIntegrationRequestAccessAPI(APIBaseTest):mock_report.assert_not_called()+class TestIntegrationMembershipPermissions(APIBaseTest):+ def setUp(self):+ super().setUp()+ # A plain project member: allowed to add integrations, but not edit or remove them.+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ @patch("posthog.models.integration.AwsS3Integration.validate_credentials", return_value="123456789012")+ def test_member_can_create_integration(self, _mock_validate):+ response = self.client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "aws-s3",+ "config": {"name": "prod-aws", "aws_access_key_id": "AKIAEXAMPLE", "aws_secret_access_key": "secret"},+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ assert Integration.objects.filter(id=response.json()["id"], team=self.team).exists()++ def test_member_cannot_delete_integration(self):+ integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T123", config={})++ response = self.client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert Integration.objects.filter(id=integration.id).exists()++ def test_member_cannot_overwrite_existing_integration(self):+ # POST is an upsert (update_or_create keyed on team/kind/integration_id), so re-submitting the+ # same resource edits an existing integration. Members may add a new one, but overwriting an+ # existing one is an edit and requires admin — the write must roll back, leaving config intact.+ email = "[email protected]"+ existing = Integration.objects.create(+ team=self.team,+ kind="google-cloud-service-account",+ integration_id=f"{email}-{self.team.pk}-key-file",+ config={"project_id": "original-project", "service_account_email": email},+ sensitive_config={"private_key": "orig", "private_key_id": "orig", "token_uri": "orig"},+ )++ response = self.client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "google-cloud-service-account",+ "config": {+ "service_account_email": email,+ "project_id": "hijacked-project",+ "private_key": "new",+ "private_key_id": "new",+ "token_uri": "new",+ },+ },+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ existing.refresh_from_db()+ assert existing.config["project_id"] == "original-project"+ assert Integration.objects.filter(team=self.team, kind="google-cloud-service-account").count() == 1++class TestGoogleSearchConsoleSitesEndpoint:_SESSION_PATH = ("products.warehouse_sources.backend.temporal.data_imports.sources.google_search_console."