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(agentic-provisioning): hydrate token scope at issuance and refresh (#61744)

Matt Brookerf2339e67fde8
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.py
index e85090e614bf..a93195948a38 100644
--- a/ee/api/agentic_provisioning/test/base.py
+++ b/ee/api/agentic_provisioning/test/base.py
@@ -56,8 +56,12 @@ class ProvisioningTestBase(APIBaseTest):
body: bytes
if content_type == "application/json":
body = json.dumps(data or {}).encode()
+ elif isinstance(data, bytes):
+ body = data
+ elif data is not None:
+ body = urlencode(data).encode()
else:
- body = data if isinstance(data, bytes) else b""
+ body = b""
sig = self._sign_body(body)
return self.client.post(
url,
@@ -100,7 +104,7 @@ class ProvisioningTestBase(APIBaseTest):
**kwargs,
)
- def _get_bearer_token(self) -> str:
+ def _request_bearer_token(self):
code = f"test_code_{id(self)}"
cache.set(
f"{AUTH_CODE_CACHE_PREFIX}{code}",
@@ -117,10 +121,12 @@ class ProvisioningTestBase(APIBaseTest):
body = urlencode({"grant_type": "authorization_code", "code": code}).encode()
ts = int(time.time())
sig = compute_signature(HMAC_SECRET, ts, body)
- res = self.client.post(
+ return self.client.post(
"/api/agentic/oauth/token",
data=body,
content_type="application/x-www-form-urlencoded",
headers={"stripe-signature": f"t={ts},v1={sig}", "api-version": "0.1d"},
)
- return res.json()["access_token"]
+
+ def _get_bearer_token(self) -> str:
+ return self._request_bearer_token().json()["access_token"]
diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.py
index 17165f85a270..d8a6835ec3d3 100644
--- a/ee/api/agentic_provisioning/test/test_resources.py
+++ b/ee/api/agentic_provisioning/test/test_resources.py
@@ -392,6 +392,8 @@ class TestProvisioningResources(ProvisioningTestBase):
)
project_id = "proj_race_same_org"
+ token = self._get_bearer_token()
+ access_token_app = OAuthAccessToken.objects.get(token=token).application
original_update_or_create = TeamProvisioningConfig.objects.update_or_create
raced: list[int] = []
@@ -399,11 +401,13 @@ class TestProvisioningResources(ProvisioningTestBase):
defaults = kwargs.get("defaults", {})
if "stripe_project_id" in defaults and not raced:
raced.append(1)
- original_update_or_create(team=winner_team, defaults={"stripe_project_id": project_id})
+ original_update_or_create(
+ team=winner_team,
+ defaults={"stripe_project_id": project_id, "application": access_token_app},
+ )
raise IntegrityError
return original_update_or_create(*args, **kwargs)
- token = self._get_bearer_token()
with patch.object(TeamProvisioningConfig.objects, "update_or_create", side_effect=race_then_raise):
res = self._post_signed_with_bearer(
"/api/agentic/provisioning/resources",
@@ -426,12 +430,13 @@ class TestProvisioningResources(ProvisioningTestBase):
organization=self.organization,
name="Pre-existing project",
)
- TeamProvisioningConfig.objects.update_or_create(
- team=existing_team, defaults={"stripe_project_id": "proj_existing"}
- )
token = self._get_bearer_token()
access_token = OAuthAccessToken.objects.get(token=token)
+ TeamProvisioningConfig.objects.update_or_create(
+ team=existing_team,
+ defaults={"stripe_project_id": "proj_existing", "application": access_token.application},
+ )
assert access_token.scoped_teams == [self.team.id]
res = self._post_signed_with_bearer(
@@ -465,8 +470,12 @@ class TestProvisioningResources(ProvisioningTestBase):
organization=self.organization,
name="Restricted project",
)
+
+ token = self._get_bearer_token()
+ access_token_obj = OAuthAccessToken.objects.get(token=token)
TeamProvisioningConfig.objects.update_or_create(
- team=restricted_team, defaults={"stripe_project_id": "proj_restricted"}
+ team=restricted_team,
+ defaults={"stripe_project_id": "proj_restricted", "application": access_token_obj.application},
)
AccessControl.objects.create(
team=restricted_team,
@@ -475,7 +484,6 @@ class TestProvisioningResources(ProvisioningTestBase):
resource_id=str(restricted_team.id),
)
- token = self._get_bearer_token()
res = self._post_signed_with_bearer(
"/api/agentic/provisioning/resources",
data={"service_id": "analytics", "project_id": "proj_restricted"},
@@ -487,6 +495,50 @@ class TestProvisioningResources(ProvisioningTestBase):
access_token = OAuthAccessToken.objects.get(token=token)
assert restricted_team.id not in (access_token.scoped_teams or [])
+ def test_create_resource_with_existing_project_id_owned_by_other_partner_does_not_leak(self):
+ # Same project_id but provisioned by a different OAuth application.
+ # The current partner must not be able to resolve into the other partner's
+ # team (which would otherwise hand back that team's api_token/PAT).
+ from posthog.models.oauth import OAuthApplication
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ other_partner = OAuthApplication.objects.create(
+ name="Other Partner",
+ client_id="other_partner_client_id",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ provisioning_partner_type="other_partner",
+ )
+ other_partner_team = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Other partner project",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=other_partner_team,
+ defaults={"stripe_project_id": "proj_shared_id", "application": other_partner},
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert access_token.application_id != other_partner.id
+
+ res = self._post_signed_with_bearer(
+ "/api/agentic/provisioning/resources",
+ data={"service_id": "analytics", "project_id": "proj_shared_id"},
+ token=token,
+ )
+ # stripe_project_id is unique across all TPCs, so the create branch hits
+ # IntegrityError and the race_winner lookup (also partner-bound) misses.
+ assert res.status_code == 409
+ assert res.json()["error"]["code"] == "project_id_conflict"
+
+ access_token.refresh_from_db()
+ assert other_partner_team.id not in (access_token.scoped_teams or [])
+
def test_create_resource_race_winner_rejects_when_user_lacks_team_access(self):
from unittest.mock import patch
@@ -518,6 +570,8 @@ class TestProvisioningResources(ProvisioningTestBase):
)
project_id = "proj_race_restricted"
+ token = self._get_bearer_token()
+ access_token_app = OAuthAccessToken.objects.get(token=token).application
original_update_or_create = TeamProvisioningConfig.objects.update_or_create
raced: list[int] = []
@@ -525,11 +579,13 @@ class TestProvisioningResources(ProvisioningTestBase):
defaults = kwargs.get("defaults", {})
if "stripe_project_id" in defaults and not raced:
raced.append(1)
- original_update_or_create(team=restricted_team, defaults={"stripe_project_id": project_id})
+ original_update_or_create(
+ team=restricted_team,
+ defaults={"stripe_project_id": project_id, "application": access_token_app},
+ )
raise IntegrityError
return original_update_or_create(*args, **kwargs)
- token = self._get_bearer_token()
with patch.object(TeamProvisioningConfig.objects, "update_or_create", side_effect=race_then_raise):
res = self._post_signed_with_bearer(
"/api/agentic/provisioning/resources",
@@ -587,6 +643,87 @@ class TestProvisioningResources(ProvisioningTestBase):
assert "personal_api_key" not in res.json()["complete"]["access_configuration"]
+@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
+class TestProvisioningResourceRemove(ProvisioningTestBase):
+ def test_remove_strips_team_from_sibling_tokens(self):
+ # Removing a resource has to revoke the team from every live token
+ # the partner installation holds for that user. Otherwise a sibling
+ # bearer that still has the team in scope can short-circuit past the
+ # auto-add guard and keep operating on the removed team.
+ from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ TeamProvisioningConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"stripe_project_id": "proj_remove_me", "application": access_token.application},
+ )
+
+ # Sibling token for the same user+application also has the team in scope.
+ sibling_at = OAuthAccessToken.objects.create(
+ application=access_token.application,
+ user=access_token.user,
+ token="sibling_access_token_value",
+ expires=access_token.expires,
+ scope=access_token.scope,
+ scoped_teams=[self.team.id, 99999],
+ )
+ sibling_rt = OAuthRefreshToken.objects.create(
+ application=access_token.application,
+ user=access_token.user,
+ token="sibling_refresh_token_value",
+ access_token=sibling_at,
+ scoped_teams=[self.team.id, 99999],
+ )
+
+ res = self._post_signed_with_bearer(
+ f"/api/agentic/provisioning/resources/{self.team.id}/remove",
+ token=token,
+ )
+ assert res.status_code == 200, res.json()
+ assert res.json()["status"] == "removed"
+
+ sibling_at.refresh_from_db()
+ sibling_rt.refresh_from_db()
+ assert self.team.id not in (sibling_at.scoped_teams or [])
+ assert self.team.id not in (sibling_rt.scoped_teams or [])
+
+ def test_remove_does_not_delete_other_partners_config(self):
+ # The base team is in the caller's scope, but its config belongs to a
+ # different partner. remove strips the caller's own scope but must leave
+ # the other partner's provisioning mapping intact.
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ other_partner = OAuthApplication.objects.create(
+ name="Other Partner",
+ client_id="other_partner_remove_client_id",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ provisioning_partner_type="other_partner",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=self.team, defaults={"application": other_partner, "stripe_project_id": "proj_other_owner"}
+ )
+
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(
+ f"/api/agentic/provisioning/resources/{self.team.id}/remove",
+ token=token,
+ )
+ assert res.status_code == 200, res.json()
+
+ config = TeamProvisioningConfig.objects.get(team=self.team)
+ assert config.application_id == other_partner.id
+
+ # the caller's token only had this team in scope, so stripping it revokes the token
+ assert not OAuthAccessToken.objects.filter(token=token).exists()
+
+
@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestCreateProvisionedPat(ProvisioningTestBase):
def _minting_app(self) -> OAuthApplication:
diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.py
new file mode 100644
index 000000000000..9858ec412438
--- /dev/null
+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py
@@ -0,0 +1,330 @@
+from io import StringIO
+
+from django.core.management import call_command
+from django.test import override_settings
+
+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+
+
+@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
+class TestPartnerTokenScopeHydration(ProvisioningTestBase):
+ def test_issuance_hydrates_with_previously_provisioned_teams(self):
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ previously_provisioned = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Previously provisioned",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=previously_provisioned,
+ defaults={"stripe_project_id": "proj_existing", "application": stripe_app},
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert self.team.id in access_token.scoped_teams
+ assert previously_provisioned.id in access_token.scoped_teams
+
+ def test_other_partner_teams_excluded(self):
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ other_partner = OAuthApplication.objects.create(
+ name="Other Partner",
+ client_id="other_partner_client_id",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ provisioning_partner_type="other_partner",
+ )
+ other_partner_team = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Other partner team",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=other_partner_team,
+ defaults={"stripe_project_id": "proj_other", "application": other_partner},
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert other_partner_team.id not in access_token.scoped_teams
+
+ def test_other_org_team_excluded_even_when_user_is_member(self):
+ # Same partner provisions teams in two orgs the user belongs to.
+ # The token is granted under org A's authorization; org B's team must
+ # not leak in just because the user can access it via org B membership.
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.organization import Organization, OrganizationMembership
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ other_org = Organization.objects.create(name="Other org")
+ OrganizationMembership.objects.create(
+ organization=other_org,
+ user=self.user,
+ level=OrganizationMembership.Level.ADMIN,
+ )
+ other_org_team = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=other_org,
+ name="Same partner, other org",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=other_org_team,
+ defaults={"stripe_project_id": "proj_other_org", "application": stripe_app},
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert self.team.id in access_token.scoped_teams
+ assert other_org_team.id not in access_token.scoped_teams
+
+ def test_cross_org_teams_excluded(self):
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.organization import Organization
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ other_org = Organization.objects.create(name="Other org")
+ foreign_team = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=other_org,
+ name="Foreign team",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=foreign_team,
+ defaults={"stripe_project_id": "proj_foreign", "application": stripe_app},
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert foreign_team.id not in access_token.scoped_teams
+
+ def test_team_with_revoked_access_excluded(self):
+ from posthog.constants import AvailableFeature
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+ from posthog.models.organization import OrganizationMembership
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ from ee.models.rbac.access_control import AccessControl
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ restricted_team = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Restricted team",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=restricted_team,
+ defaults={"stripe_project_id": "proj_restricted", "application": stripe_app},
+ )
+ AccessControl.objects.create(
+ team=restricted_team,
+ access_level="none",
+ resource="project",
+ resource_id=str(restricted_team.id),
+ )
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ assert restricted_team.id not in access_token.scoped_teams
+
+ def test_issuance_rejected_when_no_accessible_teams(self):
+ # When the base team is gone or the user lost access, _compute_partner_scoped_teams
+ # returns []. An empty scoped_teams is unrestricted under the standard permission
+ # check, so issuance must fail closed rather than mint a project-unrestricted token.
+ from posthog.constants import AvailableFeature
+ from posthog.models.oauth import OAuthAccessToken
+ from posthog.models.organization import OrganizationMembership
+
+ from ee.models.rbac.access_control import AccessControl
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ AccessControl.objects.create(
+ team=self.team,
+ access_level="none",
+ resource="project",
+ resource_id=str(self.team.id),
+ )
+
+ res = self._request_bearer_token()
+ assert res.status_code == 400, res.content
+ assert res.json()["error"] == "invalid_grant"
+ assert not OAuthAccessToken.objects.filter(user=self.user).exists()
+
+ def test_refresh_rehydrates_with_new_teams(self):
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
+ assert access_token.scoped_teams == [self.team.id]
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ newly_provisioned = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Newly provisioned",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=newly_provisioned,
+ defaults={"stripe_project_id": "proj_new", "application": stripe_app},
+ )
+
+ res = self._post_signed(
+ "/api/agentic/oauth/token",
+ data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
+ content_type="application/x-www-form-urlencoded",
+ )
+ assert res.status_code == 200, res.content
+ new_access_token = OAuthAccessToken.objects.get(token=res.json()["access_token"])
+ assert self.team.id in new_access_token.scoped_teams
+ assert newly_provisioned.id in new_access_token.scoped_teams
+
+ def test_refresh_rejected_when_access_lost_and_token_preserved(self):
+ # A refresh whose base team access was revoked recomputes to an empty scope.
+ # It must fail closed (not rotate into an unrestricted token) and, because the
+ # check runs before any token mutation, must leave the caller's refresh token intact.
+ from posthog.constants import AvailableFeature
+ from posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken
+ from posthog.models.organization import OrganizationMembership
+
+ from ee.models.rbac.access_control import AccessControl
+
+ token = self._get_bearer_token()
+ refresh_token = OAuthRefreshToken.objects.get(access_token__token=token)
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ AccessControl.objects.create(
+ team=self.team,
+ access_level="none",
+ resource="project",
+ resource_id=str(self.team.id),
+ )
+
+ res = self._post_signed(
+ "/api/agentic/oauth/token",
+ data={"grant_type": "refresh_token", "refresh_token": refresh_token.token},
+ content_type="application/x-www-form-urlencoded",
+ )
+ assert res.status_code == 400, res.content
+ assert res.json()["error"] == "invalid_grant"
+
+ refresh_token.refresh_from_db()
+ assert refresh_token.revoked is None
+ assert OAuthAccessToken.objects.filter(token=token).exists()
+
+ def test_backfill_rehydrates_stale_access_and_refresh_scope(self):
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+ from posthog.models.team.team import Team
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
+ assert access_token.scoped_teams == [self.team.id]
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ stripe_app.provisioning_partner_type = "stripe"
+ stripe_app.save()
+ newly_provisioned = Team.objects.create_with_data(
+ initiating_user=self.user,
+ organization=self.organization,
+ name="Newly provisioned",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=newly_provisioned,
+ defaults={"stripe_project_id": "proj_new", "application": stripe_app},
+ )
+
+ call_command("backfill_agentic_provisioning_scope", stdout=StringIO())
+
+ access_token.refresh_from_db()
+ refresh_token.refresh_from_db()
+ assert self.team.id in access_token.scoped_teams
+ assert newly_provisioned.id in access_token.scoped_teams
+ assert self.team.id in refresh_token.scoped_teams
+ assert newly_provisioned.id in refresh_token.scoped_teams
+
+ def test_backfill_leaves_scope_unchanged_when_recomputed_scope_is_empty(self):
+ # When the user has lost access, _compute_partner_scoped_teams returns [].
+ # An empty scoped_teams is unrestricted under the standard permission check, so the
+ # backfill must NOT overwrite a restricted token with [] — it leaves the existing
+ # restriction intact and reports the token for re-authorization.
+ from posthog.constants import AvailableFeature
+ from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+ from posthog.models.organization import OrganizationMembership
+
+ from ee.models.rbac.access_control import AccessControl
+
+ token = self._get_bearer_token()
+ access_token = OAuthAccessToken.objects.get(token=token)
+ refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)
+ assert access_token.scoped_teams == [self.team.id]
+
+ stripe_app = OAuthApplication.objects.get(client_id="test_stripe_oauth_client_id")
+ stripe_app.provisioning_partner_type = "stripe"
+ stripe_app.save()
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ AccessControl.objects.create(
+ team=self.team,
+ access_level="none",
+ resource="project",
+ resource_id=str(self.team.id),
+ )
+
+ out = StringIO()
+ call_command("backfill_agentic_provisioning_scope", stdout=out)
+
+ access_token.refresh_from_db()
+ refresh_token.refresh_from_db()
+ assert access_token.scoped_teams == [self.team.id]
+ assert refresh_token.scoped_teams == [self.team.id]
+ assert "needs re-authorization" in out.getvalue()
+
+ def test_application_none_yields_empty_scope(self):
+ # application is never None in practice (oauthrefreshtoken.application_id is
+ # NOT NULL and issuance always resolves an app), so this pins the helper's
+ # defensive branch: an unattributed token fails closed with no scope rather
+ # than silently retaining the base team.
+ from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams
+
+ assert _compute_partner_scoped_teams(None, self.user, self.team.id) == []
diff --git a/ee/api/agentic_provisioning/test/test_update_service.py b/ee/api/agentic_provisioning/test/test_update_service.py
index f407cf9aabf5..3e5fc4a29fae 100644
--- a/ee/api/agentic_provisioning/test/test_update_service.py
+++ b/ee/api/agentic_provisioning/test/test_update_service.py
@@ -154,3 +154,35 @@ class TestProvisioningUpdateService(ProvisioningTestBase):
token=token,
)
assert res.status_code == 400
+
+ def test_update_service_rejects_config_owned_by_other_partner(self):
+ # The base team is in the caller's scope, but its provisioning config
+ # belongs to a different partner. The caller must not be able to mutate it.
+ from posthog.models.oauth import OAuthApplication
+ from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
+
+ other_partner = OAuthApplication.objects.create(
+ name="Other Partner",
+ client_id="other_partner_update_client_id",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://localhost",
+ algorithm="RS256",
+ provisioning_partner_type="other_partner",
+ )
+ TeamProvisioningConfig.objects.update_or_create(
+ team=self.team, defaults={"application": other_partner, "service_id": "analytics"}
+ )
+
+ token = self._get_bearer_token()
+ res = self._post_signed_with_bearer(
+ f"/api/agentic/provisioning/resources/{self.team.id}/update_service",
+ data={"service_id": "free"},
+ token=token,
+ )
+ assert res.status_code == 403, res.content
+
+ config = TeamProvisioningConfig.objects.get(team=self.team)
+ assert config.application_id == other_partner.id
+ assert config.service_id == "analytics"
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index eb4d4b07e31e..2fa8c5ce45a6 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -38,6 +38,7 @@ from posthog.models.integration import StripeIntegration
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken, find_oauth_access_token
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team.team import Team
+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
from posthog.models.user import User
from posthog.models.utils import (
generate_random_oauth_access_token,
@@ -1141,6 +1142,22 @@ def _exchange_authorization_code(request: Request) -> Response:
else ACCESS_TOKEN_EXPIRY_SECONDS
)
+ scoped_teams = _compute_partner_scoped_teams(oauth_app, user, team_id)
+ # A partner token carries its restriction in scoped_teams alone, and the standard
+ # OAuth permission check treats an empty scoped_teams as unrestricted (permissions.py).
+ # _compute_partner_scoped_teams returns [] exactly when the base team is gone or the
+ # user lost access, so minting here would hand out a project-unrestricted bearer.
+ # Fail closed and force re-authorization.
+ if not scoped_teams:
+ _capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="authorization_code")
+ return Response(
+ {
+ "error": "invalid_grant",
+ "error_description": "No accessible teams for this authorization; re-authorize.",
+ },
+ status=400,
+ )
+
access_token_value = generate_random_oauth_access_token(None)
access_token = OAuthAccessToken.objects.create(
application=oauth_app,
@@ -1148,7 +1165,7 @@ def _exchange_authorization_code(request: Request) -> Response:
user=user,
expires=timezone.now() + timedelta(seconds=token_expiry),
scope=scope_str,
- scoped_teams=[team_id],
+ scoped_teams=scoped_teams,
)
refresh_token_value = generate_random_oauth_refresh_token(None)
@@ -1157,14 +1174,22 @@ def _exchange_authorization_code(request: Request) -> Response:
token=refresh_token_value,
user=user,
access_token=access_token,
- scoped_teams=[team_id],
+ scoped_teams=scoped_teams,
)
account_id = str(code_data.get("org_id", ""))
available_teams = _get_available_teams_for_user(user)
- _capture_provisioning_event("token_exchange", "success", partner=oauth_app, grant_type="authorization_code")
+ _capture_provisioning_event(
+ "token_exchange",
+ "success",
+ partner=oauth_app,
+ grant_type="authorization_code",
+ team_id=team_id,
+ user_id=user.id,
+ granted_team_count=len(scoped_teams),
+ )
return Response(
{
@@ -1213,7 +1238,29 @@ def _exchange_refresh_token(request: Request) -> Response:
oauth_app = locked_app
user = old_refresh.user
- scoped_teams = old_refresh.scoped_teams
+ old_scoped_teams = old_refresh.scoped_teams or []
+ # base_team_id at refresh: the first team in the prior scope. The consent team
+ # (authorized at grant time) has the lowest id and sorts first at issuance;
+ # partner-provisioned teams are always created later, so they take higher ids
+ # and are only ever appended after it. [0] is therefore the consent team. This
+ # ordering is load-bearing: _compute_partner_scoped_teams re-adds the consent
+ # team only when it is base_team_id (it has no TeamProvisioningConfig for this
+ # app), so a lower-id provisioned team becoming [0] would silently drop the
+ # consent team from the refreshed scope. If the prior token was somehow empty-
+ # scoped, fall back to zero so the helper short-circuits without claiming a team.
+ base_team_id = old_scoped_teams[0] if old_scoped_teams else 0
+ scoped_teams = _compute_partner_scoped_teams(oauth_app, user, base_team_id)
+ # Same fail-closed rule as issuance: an empty scoped_teams is unrestricted under the
+ # standard permission check, so a refresh whose base team vanished or whose access was
+ # revoked must re-authorize rather than rotate into a project-unrestricted token.
+ # Checked before any token row is mutated so a rejected refresh never revokes the
+ # caller's only token.
+ if not scoped_teams:
+ _capture_provisioning_event("token_exchange", "no_accessible_teams", grant_type="refresh_token")
+ return Response(
+ {"error": "invalid_grant", "error_description": "No accessible teams for this token; re-authorize."},
+ status=400,
+ )
old_scope = old_refresh.access_token.scope if old_refresh.access_token else StripeIntegration.SCOPES
sessions_revoked_at = locked_app.sessions_revoked_at if locked_app else None
@@ -1281,7 +1328,15 @@ def _exchange_refresh_token(request: Request) -> Response:
scoped_teams=scoped_teams,
)
- _capture_provisioning_event("token_exchange", "success", partner=oauth_app, grant_type="refresh_token")
+ _capture_provisioning_event(
+ "token_exchange",
+ "success",
+ partner=oauth_app,
+ grant_type="refresh_token",
+ team_id=base_team_id,
+ user_id=user.id if user else None,
+ granted_team_count=len(scoped_teams),
+ )
return Response(
{
@@ -1485,11 +1540,10 @@ def _resolve_or_create_project_team(
authenticated user lacks team-level access (honors advanced permissions
/ access controls on top of org membership).
"""
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
existing = (
TeamProvisioningConfig.objects.filter(
stripe_project_id=project_id,
+ application=access_token.application,
team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),
)
.select_related("team")
@@ -1514,13 +1568,14 @@ def _resolve_or_create_project_team(
try:
TeamProvisioningConfig.objects.update_or_create(
team=new_team,
- defaults={"stripe_project_id": project_id},
+ defaults={"stripe_project_id": project_id, "application": access_token.application},
)
except IntegrityError:
new_team.delete()
race_winner = (
TeamProvisioningConfig.objects.filter(
stripe_project_id=project_id,
+ application=access_token.application,
team__organization_id__in=Team.objects.filter(id__in=scoped_teams).values("organization_id"),
)
.select_related("team")
@@ -1552,6 +1607,66 @@ def _ensure_team_in_token_scopes(
return team, [*scoped_teams, team.id]
+def _compute_partner_scoped_teams(
+ application: OAuthApplication | None,
+ user: User,
+ base_team_id: int,
+) -> list[int]:
+ """Compute the durable scope for a partner OAuth token at issuance/refresh.
+
+ Returns the set of every team where ``TeamProvisioningConfig.application ==
+ application`` (i.e. this partner provisioned the team for this user, attributed
+ at create time) AND the team lives in the same organization as ``base_team_id``
+ AND the user still has team-level access. This is partner-agnostic, not
+ Stripe-specific: ``stripe_project_id`` is the (legacily named) external project
+ id every partner sets, always written alongside ``application`` in
+ ``_resolve_or_create_project_team``, so the ``application`` filter already
+ implies a provisioned team. The organization filter pins the token to the
+ authorization context:
+ a partner with OAuth grants in multiple orgs for the same user must not be
+ able to reach an org-B team via an org-A token just because the user happens
+ to be a member of both.
+
+ Returns ``[]`` when ``application`` is None (legacy refresh tokens with no
+ app binding). A partner-unattributed token cannot be safely scoped, so it
+ gets no teams and the holder must re-authorize. Falling through would let
+ ``filter(application=None)`` match every TPC row with NULL application
+ across every partner.
+
+ Returns ``[]`` if ``base_team_id`` no longer resolves to a team the user
+ can access; stale scope must not grant ongoing access after ACL revocation
+ or org removal.
+ """
+ if application is None:
+ return []
+
+ try:
+ base_team = Team.objects.select_related("organization").get(id=base_team_id)
+ except Team.DoesNotExist:
+ return []
+ if not _user_can_access_team(user, base_team):
+ return []
+
+ candidate_team_ids = set(
+ TeamProvisioningConfig.objects.filter(
+ application=application,
+ team__organization_id=base_team.organization_id,
+ ).values_list("team_id", flat=True)
+ )
+ candidate_team_ids.add(base_team_id)
+
+ granted: set[int] = {base_team_id}
+ other_teams = Team.objects.select_related("organization").filter(
+ id__in=candidate_team_ids - {base_team_id},
+ )
+ for team in other_teams:
+ if _user_can_access_team(user, team):
+ granted.add(team.id)
+
+ # sorted() only for deterministic test assertions and log diffs; scope order is not a correctness requirement
+ return sorted(granted)
+
+
def _user_can_access_team(user: User, team: Team) -> bool:
"""Verify the user has at least member-level access to the team.
@@ -1583,8 +1698,6 @@ def _add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> N
def _get_provisioning_service_id(team: Team) -> str:
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
try:
config = TeamProvisioningConfig.objects.get(team=team)
return config.service_id
@@ -1593,8 +1706,6 @@ def _get_provisioning_service_id(team: Team) -> str:
def _set_provisioning_service_id(team: Team, service_id: str) -> None:
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
TeamProvisioningConfig.objects.update_or_create(
team=team,
defaults={"service_id": service_id},
@@ -1880,6 +1991,17 @@ def provisioning_update_service(request: Request, resource_id: str) -> Response:
except Team.DoesNotExist:
return _error_response("not_found", "Resource not found", resource_id=resource_id, status=404)
+ # A config with a non-null application belongs to the partner that provisioned
+ # it; a null application is unclaimed (every team gets one by default) and is
+ # mutable by any in-scope caller. Reject only a cross-partner mutation.
+ owning_application_id = (
+ TeamProvisioningConfig.objects.filter(team_id=team_id).values_list("application_id", flat=True).first()
+ )
+ if owning_application_id is not None and owning_application_id != access_token.application_id:
+ return _error_response(
+ "forbidden", "Resource owned by a different provisioning partner", resource_id=resource_id, status=403
+ )
+
service_id = request.data.get("service_id", "")
if not service_id:
return _error_response("missing_service_id", "service_id is required", resource_id=resource_id)
@@ -1987,10 +2109,13 @@ def provisioning_resource_remove(request: Request, resource_id: str) -> Response
status=403,
)
- from posthog.models.team.team_provisioning_config import TeamProvisioningConfig
-
try:
- TeamProvisioningConfig.objects.filter(team_id=team_id).delete()
+ # Clear the mapping only if it is unclaimed or owned by the caller's
+ # application; an in-scope partner must not delete another partner's
+ # provisioning mapping for the same team.
+ config = TeamProvisioningConfig.objects.filter(team_id=team_id).first()
+ if config is not None and config.application_id in (None, access_token.application_id):
+ config.delete()
except Exception:
capture_exception(additional_properties={"team_id": team_id, "step": "remove_provisioning_config"})
_capture_provisioning_event("resource_removed", "error", team_id=team_id, error_code="remove_config_failed")
@@ -2011,25 +2136,61 @@ def provisioning_resource_remove(request: Request, resource_id: str) -> Response
def _remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:
- remaining = [t for t in (access_token.scoped_teams or []) if t != team_id]
+ """Strip ``team_id`` from every access/refresh token for this partner+user combo.
+
+ Removing a resource has to revoke access for any *other* live token the same
+ partner installation might be holding for the same user (e.g. a separate
+ bearer issued via a prior OAuth grant that still has the team in scope).
+ Touching only the calling ``access_token`` would let the partner continue
+ operating on the team via a sibling token after `remove` returned, since
+ operational endpoints accept any team currently in ``scoped_teams``.
+
+ Atomic so a refresh token can never be left with the removed team still in
+ scope while the access token has it stripped — otherwise the orchestrator
+ could refresh and replay the removed team right back into scope.
+ """
+ application = access_token.application
+ user = access_token.user
+ if application is None or user is None:
+ # Defensive: a provisioning bearer token without an app/user shouldn't
+ # exist in practice, but fall back to the single-token strip if it does.
+ application_filter: dict[str, object] = {"pk": access_token.pk}
+ user_filter: dict[str, object] = {}
+ else:
+ application_filter = {"application": application, "user": user}
+ user_filter = {"application": application, "user": user}
- # Atomic so a refresh token can never be left with the removed team still in
- # scope while the access token has it stripped — otherwise the orchestrator
- # could refresh and replay the removed team right back into scope.
with transaction.atomic():
- refresh_tokens = OAuthRefreshToken.objects.filter(access_token=access_token)
-
- if not remaining:
- refresh_tokens.update(access_token=None, revoked=timezone.now(), scoped_teams=[])
- access_token.delete()
- return
-
- access_token.scoped_teams = remaining
- access_token.save(update_fields=["scoped_teams"])
+ access_tokens = list(
+ OAuthAccessToken.objects.select_for_update()
+ .filter(scoped_teams__contains=[team_id], **application_filter)
+ .order_by("pk")
+ )
+ for at in access_tokens:
+ remaining = [t for t in (at.scoped_teams or []) if t != team_id]
+ refresh_tokens = OAuthRefreshToken.objects.select_for_update().filter(access_token=at)
+ if not remaining:
+ refresh_tokens.update(access_token=None, revoked=timezone.now(), scoped_teams=[])
+ at.delete()
+ continue
+ at.scoped_teams = remaining
+ at.save(update_fields=["scoped_teams"])
+ for rt in refresh_tokens:
+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]
+ rt.save(update_fields=["scoped_teams"])
- for rt in refresh_tokens:
- rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]
- rt.save(update_fields=["scoped_teams"])
+ if user_filter:
+ # Orphan refresh tokens (where the access token was already rotated
+ # or deleted) still carry scope. Strip the team from those too.
+ orphan_refresh = OAuthRefreshToken.objects.select_for_update().filter(
+ scoped_teams__contains=[team_id],
+ access_token__isnull=True,
+ revoked__isnull=True,
+ **user_filter,
+ )
+ for rt in orphan_refresh:
+ rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]
+ rt.save(update_fields=["scoped_teams"])
def _resolve_resource_response(request: Request, resource_id: str) -> Response:
diff --git a/posthog/management/commands/backfill_agentic_provisioning_scope.py b/posthog/management/commands/backfill_agentic_provisioning_scope.py
new file mode 100644
index 000000000000..158aafb68d5c
--- /dev/null
+++ b/posthog/management/commands/backfill_agentic_provisioning_scope.py
@@ -0,0 +1,143 @@
+import logging
+
+from django.core.management.base import BaseCommand
+from django.db import transaction
+from django.utils import timezone
+
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
+
+logger = logging.getLogger(__name__)
+
+
+class Command(BaseCommand):
+ help = (
+ "Rehydrate scoped_teams on existing agentic provisioning OAuth tokens. "
+ "Walks live access + refresh tokens for partner OAuth applications and "
+ "recomputes scoped_teams via _compute_partner_scoped_teams. Idempotent."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--application-id",
+ type=str,
+ help="Limit to a single OAuthApplication id. Defaults to every application with provisioning_partner_type set.",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Compute new scope without writing.",
+ )
+
+ def handle(self, *args, **options):
+ # Local import so the import graph stays small for the management command
+ # registry; views.py pulls in a much larger dependency surface than the
+ # rest of the command suite.
+ from ee.api.agentic_provisioning.views import _compute_partner_scoped_teams
+
+ application_id = options.get("application_id")
+ dry_run: bool = options["dry_run"]
+
+ application_qs = OAuthApplication.objects.exclude(provisioning_partner_type="")
+ if application_id:
+ application_qs = application_qs.filter(id=application_id)
+
+ applications = list(application_qs)
+ if not applications:
+ self.stdout.write("No matching provisioning partner applications found.")
+ return
+
+ total_access = 0
+ total_refresh = 0
+ changed_access = 0
+ changed_refresh = 0
+ skipped_empty = 0
+
+ for application in applications:
+ self.stdout.write(f"Application {application.id} ({application.name}):")
+
+ # OAuthAccessToken has no `revoked` column (only refresh tokens do); a revoked
+ # access token is hard-deleted, so live tokens are the unexpired ones.
+ access_tokens = OAuthAccessToken.objects.filter(application=application)
+ for access_token in access_tokens.iterator(chunk_size=200):
+ total_access += 1
+ if access_token.expires and access_token.expires < timezone.now():
+ continue
+ user = access_token.user
+ if user is None:
+ continue
+ old_scope = list(access_token.scoped_teams or [])
+ base_team_id = old_scope[0] if old_scope else 0
+ new_scope = _compute_partner_scoped_teams(application, user, base_team_id)
+ # _compute_partner_scoped_teams returns [] when the base team is gone or the
+ # user lost access. An empty scoped_teams is treated as unrestricted by the
+ # OAuth permission check (permissions.py), so writing [] here would strip the
+ # project restriction from a live token. Leave the existing scope intact and
+ # report it for re-authorization, matching the fail-closed issuance/refresh paths.
+ if not new_scope:
+ skipped_empty += 1
+ self.stdout.write(
+ f" access_token={access_token.pk} user={user.id} old={sorted(old_scope)} "
+ f"new=[] (empty scope; left unchanged, needs re-authorization)"
+ )
+ continue
+ if sorted(new_scope) == sorted(old_scope):
+ continue
+ changed_access += 1
+ self.stdout.write(
+ f" access_token={access_token.pk} user={user.id} old={sorted(old_scope)} new={sorted(new_scope)}"
+ )
+ if not dry_run:
+ try:
+ with transaction.atomic():
+ locked = OAuthAccessToken.objects.select_for_update().get(pk=access_token.pk)
+ locked.scoped_teams = new_scope
+ locked.save(update_fields=["scoped_teams"])
+ except OAuthAccessToken.DoesNotExist:
+ # A concurrent refresh deleted this row between read and lock; skip
+ # it rather than aborting the whole backfill.
+ self.stdout.write(f" access_token={access_token.pk} gone before lock; skipping")
+
+ refresh_tokens = OAuthRefreshToken.objects.filter(
+ application=application,
+ revoked__isnull=True,
+ )
+ for refresh_token in refresh_tokens.iterator(chunk_size=200):
+ total_refresh += 1
+ user = refresh_token.user
+ if user is None:
+ continue
+ old_scope = list(refresh_token.scoped_teams or [])
+ base_team_id = old_scope[0] if old_scope else 0
+ new_scope = _compute_partner_scoped_teams(application, user, base_team_id)
+ # Same fail-closed rule as access tokens: never overwrite a restricted scope
+ # with an empty (unrestricted) one. Leave it for re-authorization.
+ if not new_scope:
+ skipped_empty += 1
+ self.stdout.write(
+ f" refresh_token={refresh_token.pk} user={user.id} old={sorted(old_scope)} "
+ f"new=[] (empty scope; left unchanged, needs re-authorization)"
+ )
+ continue
+ if sorted(new_scope) == sorted(old_scope):
+ continue
+ changed_refresh += 1
+ self.stdout.write(
+ f" refresh_token={refresh_token.pk} user={user.id} old={sorted(old_scope)} new={sorted(new_scope)}"
+ )
+ if not dry_run:
+ try:
+ with transaction.atomic():
+ locked = OAuthRefreshToken.objects.select_for_update().get(pk=refresh_token.pk)
+ locked.scoped_teams = new_scope
+ locked.save(update_fields=["scoped_teams"])
+ except OAuthRefreshToken.DoesNotExist:
+ # A concurrent refresh removed this row between read and lock; skip
+ # it rather than aborting the whole backfill.
+ self.stdout.write(f" refresh_token={refresh_token.pk} gone before lock; skipping")
+
+ verb = "Would update" if dry_run else "Updated"
+ self.stdout.write(
+ f"{verb} {changed_access}/{total_access} access tokens and "
+ f"{changed_refresh}/{total_refresh} refresh tokens. "
+ f"{skipped_empty} tokens left unchanged with empty recomputed scope (need re-authorization)."
+ )
diff --git a/posthog/migrations/1228_teamprovisioningconfig_application.py b/posthog/migrations/1228_teamprovisioningconfig_application.py
new file mode 100644
index 000000000000..90a4cf3df960
--- /dev/null
+++ b/posthog/migrations/1228_teamprovisioningconfig_application.py
@@ -0,0 +1,21 @@
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1227_alter_datadeletionrequest_delete_all_events")]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamprovisioningconfig",
+ name="application",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="provisioned_team_configs",
+ to=settings.OAUTH2_PROVIDER_APPLICATION_MODEL,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/1229_teamprovisioningconfig_application_idx.py b/posthog/migrations/1229_teamprovisioningconfig_application_idx.py
new file mode 100644
index 000000000000..35530a47c839
--- /dev/null
+++ b/posthog/migrations/1229_teamprovisioningconfig_application_idx.py
@@ -0,0 +1,17 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction. Lives in its own
+ # migration per PostHog policy (don't mix CONCURRENTLY operations with regular DDL).
+ atomic = False
+ dependencies = [("posthog", "1228_teamprovisioningconfig_application")]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="teamprovisioningconfig",
+ index=models.Index(fields=["application"], name="tpc_application_idx"),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index f41fe5dc8d46..29c9a938ed90 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1227_alter_datadeletionrequest_delete_all_events
+1229_teamprovisioningconfig_application_idx
diff --git a/posthog/models/team/team_provisioning_config.py b/posthog/models/team/team_provisioning_config.py
index cd63cccb7e4c..effab744bdd1 100644
--- a/posthog/models/team/team_provisioning_config.py
+++ b/posthog/models/team/team_provisioning_config.py
@@ -10,8 +10,25 @@ logger = logging.getLogger(__name__)
class TeamProvisioningConfig(models.Model):
team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True)
+ # The OAuth application that provisioned this team. Bound to the issuing
+ # partner so resource endpoints can verify that the bearer token's app owns
+ # the team before auto-adding it to scope. Null for rows created before the
+ # field was added; legacy rows are not auto-add eligible.
+ application = models.ForeignKey(
+ "posthog.OAuthApplication",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ related_name="provisioned_team_configs",
+ )
+
stripe_project_id = models.CharField(max_length=255, null=True, blank=True, unique=True)
service_id = models.CharField(max_length=255, default="analytics")
+ class Meta:
+ indexes = [
+ models.Index(fields=["application"], name="tpc_application_idx"),
+ ]
+
register_team_extension_signal(TeamProvisioningConfig, logger=logger)