:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(provisioning): record the partner on accounts it creates (#107081)
Matt Brookerc383a2116d6e
diff --git a/ee/api/agentic_provisioning/accounts.py b/ee/api/agentic_provisioning/accounts.pyindex 36544da7ed05..a210c7153598 100644--- a/ee/api/agentic_provisioning/accounts.py+++ b/ee/api/agentic_provisioning/accounts.py@@ -268,11 +268,7 @@ def handle_new_user(team_id=team.id,)- # Attribute the bootstrap team to the creating partner. The row already exists- # (the Team extension signal created it inside bootstrap), so this is an update.- # Without it the mapping stays unclaimed, and resource removal treats unclaimed as- # fair game for any partner whose token happens to scope the team.- TeamProvisioningConfig.objects.filter(team_id=team.id, application__isnull=True).update(application=partner)+ TeamProvisioningConfig.objects.get_or_create(team=team, defaults={"application": partner})# Every provisioned account is treated as already onboarded — apply the flags at# bootstrap so the account is covered regardless of which follow-up blocks (if any)diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.pyindex 1bd7a2c04186..5025c3468eaa 100644--- a/ee/api/agentic_provisioning/test/base.py+++ b/ee/api/agentic_provisioning/test/base.py@@ -3,6 +3,7 @@ import base64import hashlibimport secretsimport dataclasses+from typing import TYPE_CHECKINGfrom urllib.parse import quote_plusfrom posthog.test.base import APIBaseTest@@ -21,6 +22,11 @@ from products.access_control.backend.models.access_control import AccessControlfrom ee.api.agentic_provisioning.constants import AUTH_CODE_CACHE_PREFIX+if TYPE_CHECKING:+ from rest_framework.response import _MonkeyPatchedResponse++ from posthog.models.oauth import OAuthApplication+TEST_PARTNER_CLIENT_ID = "test_partner_client_id"# Stored hashed by ClientSecretField.pre_save, so the plaintext has to live here for# requests to present it.@@ -146,7 +152,9 @@ class ProvisioningTestBase(APIBaseTest):challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode()return verifier, challenge- def _mint_auth_code(self, scopes: list[str] | None = None, partner=None) -> tuple[str, str]:+ def _mint_auth_code(+ self, scopes: list[str] | None = None, partner: "OAuthApplication | None" = None, team_id: int | None = None+ ) -> tuple[str, str]:"""Seed an auth code in the cache for the test partner. Returns (code, code_verifier)."""partner = partner or self.partnerverifier, challenge = self._pkce_pair()@@ -157,7 +165,7 @@ class ProvisioningTestBase(APIBaseTest):"issued_at": timezone.now().isoformat(),"user_id": self.user.id,"org_id": str(self.organization.id),- "team_id": self.team.id,+ "team_id": team_id if team_id is not None else self.team.id,"partner_id": str(partner.id),"scopes": scopes if scopes is not None else ["query:read"],"region": "US",@@ -168,9 +176,15 @@ class ProvisioningTestBase(APIBaseTest):)return code, verifier- def _request_bearer_token(self, scopes: list[str] | None = None, partner=None, secret: str | None = None):+ def _request_bearer_token(+ self,+ scopes: list[str] | None = None,+ partner: "OAuthApplication | None" = None,+ secret: str | None = None,+ team_id: int | None = None,+ ) -> "_MonkeyPatchedResponse":partner = partner or self.partner- code, verifier = self._mint_auth_code(scopes=scopes, partner=partner)+ code, verifier = self._mint_auth_code(scopes=scopes, partner=partner, team_id=team_id)data = {"grant_type": "authorization_code", "code": code, "code_verifier": verifier}# A confidential partner has to authenticate at the token endpoint; a public one# exchanges on the code_verifier alone.diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.pyindex f0142a87eace..9ce946566903 100644--- a/ee/api/agentic_provisioning/test/test_account_requests.py+++ b/ee/api/agentic_provisioning/test/test_account_requests.py@@ -12,6 +12,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom posthog.models.oauth import OAuthApplication+from posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.user import Userfrom ee.api.agentic_provisioning.analytics import capture_provisioning_event@@ -53,11 +54,12 @@ class TestAccountRequests(ProvisioningTestBase):assert len(data["oauth"]["code"]) > 0assert User.objects.filter(email="[email protected]").exists()- def test_new_user_creates_org_and_team(self):+ def test_new_user_creates_org_and_team_attributed_to_partner(self):self._post_account_request(self._account_request_payload())user = User.objects.get(email="[email protected]")assert user.organization is not Noneassert user.team is not None+ assert TeamProvisioningConfig.objects.get(team=user.team).application_id == self.partner.iddef test_new_user_starts_unverified(self):# Partner-asserted email ownership is not trusted: the user must prove they owndiff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex 62e1739bd24d..940187bb4e9e 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -5,6 +5,7 @@ from parameterized import parameterizedfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom ee.api.agentic_provisioning.credentials import maybe_create_provisioned_patfrom ee.api.agentic_provisioning.ratelimits import RATE_LIMITED_MESSAGE@@ -651,11 +652,12 @@ class TestProvisioningResources(ProvisioningTestBase):class TestProvisioningResourceRemove(ProvisioningTestBase):- def test_remove_strips_team_from_sibling_tokens(self):+ @parameterized.expand([("same_user", False), ("other_org_member", True)])+ def test_remove_strips_team_from_sibling_tokens(self, _name: str, sibling_is_other_member: bool) -> None:# 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.+ # the partner holds, for any 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, OAuthRefreshTokenfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfig@@ -666,10 +668,16 @@ class TestProvisioningResourceRemove(ProvisioningTestBase):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_user = (+ User.objects.create_and_join(+ organization=self.organization, email="[email protected]", password="testpass", first_name="Mate"+ )+ if sibling_is_other_member+ else access_token.user+ )sibling_at = OAuthAccessToken.objects.create(application=access_token.application,- user=access_token.user,+ user=sibling_user,token="sibling_access_token_value",expires=access_token.expires,scope=access_token.scope,@@ -677,7 +685,7 @@ class TestProvisioningResourceRemove(ProvisioningTestBase):)sibling_rt = OAuthRefreshToken.objects.create(application=access_token.application,- user=access_token.user,+ user=sibling_user,token="sibling_refresh_token_value",access_token=sibling_at,scoped_teams=[self.team.id, 99999],diff --git a/ee/api/agentic_provisioning/test/test_scope_hydration.py b/ee/api/agentic_provisioning/test/test_scope_hydration.pyindex 3d9ec0f06ea9..f18af6fb5218 100644--- a/ee/api/agentic_provisioning/test/test_scope_hydration.py+++ b/ee/api/agentic_provisioning/test/test_scope_hydration.py@@ -2,6 +2,8 @@ from io import StringIOfrom django.core.management import call_command+from parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshTokenfrom posthog.models.organization import Organization, OrganizationMembership@@ -138,6 +140,31 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):assert self.team.id in new_access_token.scoped_teamsassert newly_provisioned.id in new_access_token.scoped_teams+ @parameterized.expand([("issued", False), ("stored_in_id_order", True)])+ def test_consented_project_stays_first_across_refreshes_in_partner_created_org(+ self, _name: str, stored_in_id_order: bool+ ) -> None:+ TeamProvisioningConfig.objects.update_or_create(team=self.team, defaults={"application": self.partner})+ consented = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Consented"+ )++ tokens = self._request_bearer_token(team_id=consented.id).json()+ if stored_in_id_order:+ OAuthRefreshToken.objects.filter(token=tokens["refresh_token"]).update(+ scoped_teams=[self.team.id, consented.id]+ )+ for _ in range(2):+ res = self._refresh(tokens["refresh_token"])+ assert res.status_code == 200, res.content+ tokens = res.json()++ access_token = OAuthAccessToken.objects.get(token=tokens["access_token"])+ assert access_token.scoped_teams == [consented.id, self.team.id]+ res = self._post_with_bearer("/api/agentic/provisioning/resources", token=tokens["access_token"])+ assert res.status_code == 200, res.content+ assert res.json()["id"] == str(consented.id)+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@@ -173,6 +200,25 @@ class TestPartnerTokenScopeHydration(ProvisioningTestBase):assert self.team.id in refresh_token.scoped_teamsassert newly_provisioned.id in refresh_token.scoped_teams+ def test_backfill_keeps_consent_team_when_scope_is_stored_in_id_order(self) -> None:+ TeamProvisioningConfig.objects.update_or_create(team=self.team, defaults={"application": self.partner})+ consented = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Consented"+ )+ token = self._request_bearer_token(team_id=consented.id).json()["access_token"]+ access_token = OAuthAccessToken.objects.get(token=token)+ refresh_token = OAuthRefreshToken.objects.get(access_token=access_token)+ for stored in (access_token, refresh_token):+ stored.scoped_teams = [self.team.id, consented.id]+ stored.save(update_fields=["scoped_teams"])++ call_command("backfill_agentic_provisioning_scope", stdout=StringIO())++ access_token.refresh_from_db()+ refresh_token.refresh_from_db()+ assert access_token.scoped_teams == [consented.id, self.team.id]+ assert refresh_token.scoped_teams == [consented.id, self.team.id]+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 thediff --git a/ee/api/agentic_provisioning/tokens.py b/ee/api/agentic_provisioning/tokens.pyindex da8c932876d0..b8a068ae915c 100644--- a/ee/api/agentic_provisioning/tokens.py+++ b/ee/api/agentic_provisioning/tokens.py@@ -100,8 +100,29 @@ def compute_partner_scoped_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)+ # The base team must stay at index 0. Refresh passes scoped_teams[0] back in as+ # base_team_id, and resource creation and deep links default to it.+ return [base_team_id, *sorted(granted - {base_team_id})]+++def base_team_id_from_scope(application: OAuthApplication | None, scoped_teams: list[int]) -> int:+ """Pick the ``base_team_id`` for re-deriving a stored scope.++ Every scoped team except the consent team has a TeamProvisioningConfig row for+ ``application``, so the first team without one is the consent team. Stored order+ is not enough on its own, because some stored scopes are sorted by id. When every+ team is attributed, the base does not change the re-derived set.+ """+ if not scoped_teams:+ return 0+ if application is None:+ return scoped_teams[0]+ attributed = set(+ TeamProvisioningConfig.objects.filter(application=application, team_id__in=scoped_teams).values_list(+ "team_id", flat=True+ )+ )+ return next((team_id for team_id in scoped_teams if team_id not in attributed), scoped_teams[0])def ensure_team_in_token_scopes(@@ -133,11 +154,11 @@ def add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> Nodef remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:- """Strip ``team_id`` from every access/refresh token for this partner+user combo.+ """Strip ``team_id`` from every access/refresh token this partner holds, for every user.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).+ partner holds for the team, for this user or another member of the org (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 continueoperating on the team via a sibling token after `remove` returned, sinceoperational endpoints accept any team currently in ``scoped_teams``.@@ -152,10 +173,10 @@ def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int)# 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] = {}+ orphan_filter: dict[str, object] = {}else:- application_filter = {"application": application, "user": user}- user_filter = {"application": application, "user": user}+ application_filter = {"application": application}+ orphan_filter = {"application": application}with transaction.atomic():access_tokens = list(@@ -176,14 +197,14 @@ def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int)rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]rt.save(update_fields=["scoped_teams"])- if user_filter:+ if orphan_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,+ **orphan_filter,)for rt in orphan_refresh:rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.pyindex 55230801a97b..d38c8f113bd5 100644--- a/ee/api/agentic_provisioning/views/oauth_token.py+++ b/ee/api/agentic_provisioning/views/oauth_token.py@@ -37,6 +37,7 @@ from ee.api.agentic_provisioning.constants import (from ee.api.agentic_provisioning.exceptions import ProvisioningErrorfrom ee.api.agentic_provisioning.ratelimits import Budget, rate_limitedfrom ee.api.agentic_provisioning.tokens import (+ base_team_id_from_scope,compute_partner_scoped_teams,get_available_teams_for_user,lock_application,@@ -339,16 +340,12 @@ class OAuthTokenView(ProvisioningAPIView):capture_provisioning_event("token_exchange", "user_inactive", grant_type="refresh_token")raise ProvisioningError("invalid_grant", "User is not active; re-authorize.")- # 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+ # base_team_id at refresh must be the consent team. compute_partner_scoped_teams+ # keeps base_team_id unconditionally but keeps other teams only when they have a+ # TeamProvisioningConfig for this app, so any other base silently drops an+ # unattributed consent team from the refreshed scope. An empty prior scope yields+ # zero, so the helper short-circuits without claiming a team.+ base_team_id = base_team_id_from_scope(oauth_app, old_scoped_teams)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 thediff --git a/ee/partners/stripe/api/provisioning/core.py b/ee/partners/stripe/api/provisioning/core.pyindex f4a1cd48196c..703d0ba9e28e 100644--- a/ee/partners/stripe/api/provisioning/core.py+++ b/ee/partners/stripe/api/provisioning/core.py@@ -383,8 +383,29 @@ def compute_partner_scoped_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)+ # The base team must stay at index 0. Refresh passes scoped_teams[0] back in as+ # base_team_id, and resource creation and deep links default to it.+ return [base_team_id, *sorted(granted - {base_team_id})]+++def base_team_id_from_scope(application: OAuthApplication | None, scoped_teams: list[int]) -> int:+ """Pick the ``base_team_id`` for re-deriving a stored scope.++ Every scoped team except the consent team has a TeamProvisioningConfig row for+ ``application``, so the first team without one is the consent team. Stored order+ is not enough on its own, because some stored scopes are sorted by id. When every+ team is attributed, the base does not change the re-derived set.+ """+ if not scoped_teams:+ return 0+ if application is None:+ return scoped_teams[0]+ attributed = set(+ TeamProvisioningConfig.objects.filter(application=application, team_id__in=scoped_teams).values_list(+ "team_id", flat=True+ )+ )+ return next((team_id for team_id in scoped_teams if team_id not in attributed), scoped_teams[0])def add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:@@ -407,11 +428,11 @@ def add_team_to_token_scopes(access_token: OAuthAccessToken, team_id: int) -> Nodef remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int) -> None:- """Strip ``team_id`` from every access/refresh token for this app+user combo.+ """Strip ``team_id`` from every access/refresh token this partner holds, for every user.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).+ partner holds for the team, for this user or another member of the org (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 continueoperating on the team via a sibling token after `remove` returned, sinceoperational endpoints accept any team currently in ``scoped_teams``.@@ -426,10 +447,10 @@ def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int)# 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] = {}+ orphan_filter: dict[str, object] = {}else:- application_filter = {"application": application, "user": user}- user_filter = {"application": application, "user": user}+ application_filter = {"application": application}+ orphan_filter = {"application": application}with transaction.atomic():access_tokens = list(@@ -450,14 +471,14 @@ def remove_team_from_token_scopes(access_token: OAuthAccessToken, team_id: int)rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]rt.save(update_fields=["scoped_teams"])- if user_filter:+ if orphan_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,+ **orphan_filter,)for rt in orphan_refresh:rt.scoped_teams = [t for t in (rt.scoped_teams or []) if t != team_id]diff --git a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py b/ee/partners/stripe/api/provisioning/test/test_oauth_token.pyindex 9e42a8fa181a..c405f5fa9596 100644--- a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py+++ b/ee/partners/stripe/api/provisioning/test/test_oauth_token.py@@ -12,6 +12,7 @@ from posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.utils import generate_random_oauth_refresh_tokenfrom products.access_control.backend.models.access_control import AccessControl@@ -134,6 +135,34 @@ class TestOAuthToken(StripeProvisioningTestBase):)assert detail.status_code == 401+ @parameterized.expand([("issued", False), ("stored_in_id_order", True)])+ def test_consented_team_stays_first_across_refreshes_when_a_lower_id_team_is_provisioned(+ self, _name: str, stored_in_id_order: bool+ ) -> None:+ TeamProvisioningConfig.objects.update_or_create(+ team=self.team, defaults={"stripe_project_id": "proj_earlier", "application": self.stripe_app}+ )+ consented = Team.objects.create_with_data(+ initiating_user=self.user, organization=self.organization, name="Consented"+ )+ self._seed_auth_code("code_consented", team_id=consented.id)++ tokens = self._post_token({"grant_type": "authorization_code", "code": "code_consented"}).json()+ if stored_in_id_order:+ OAuthRefreshToken.objects.filter(token=tokens["refresh_token"]).update(+ scoped_teams=[self.team.id, consented.id]+ )+ for _ in range(2):+ res = self._post_token({"grant_type": "refresh_token", "refresh_token": tokens["refresh_token"]})+ assert res.status_code == 200, res.content+ tokens = res.json()++ access_token = OAuthAccessToken.objects.get(token=tokens["access_token"])+ assert access_token.scoped_teams == [consented.id, self.team.id]+ res = self._post_signed_with_bearer(f"{BASE_PATH}/provisioning/resources", token=tokens["access_token"])+ assert res.status_code == 200, res.content+ assert res.json()["id"] == str(consented.id)+def test_available_teams_exclude_acl_restricted_teams(self):self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},diff --git a/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py b/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.pyindex 173c5d6b29e4..d107afc98cf6 100644--- a/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py+++ b/ee/partners/stripe/api/provisioning/test/test_remove_and_rotate.py@@ -1,5 +1,7 @@+from posthog.models.oauth import OAuthAccessToken, OAuthRefreshTokenfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfig+from posthog.models.user import Userfrom ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBase@@ -41,6 +43,25 @@ class TestRemoveAndRotate(StripeProvisioningTestBase):create = self._post_signed_with_bearer(RESOURCES_URL, data={"service_id": "analytics"}, token=token)assert create.status_code == 200assert TeamProvisioningConfig.objects.filter(team=self.team).exists()+ access_token = OAuthAccessToken.objects.get(token=token)+ teammate = User.objects.create_and_join(+ organization=self.organization, email="[email protected]", password="testpass", first_name="Mate"+ )+ teammate_at = OAuthAccessToken.objects.create(+ application=access_token.application,+ user=teammate,+ token="teammate_access_token_value",+ expires=access_token.expires,+ scope=access_token.scope,+ scoped_teams=[self.team.id, 99999],+ )+ teammate_rt = OAuthRefreshToken.objects.create(+ application=access_token.application,+ user=teammate,+ token="teammate_refresh_token_value",+ access_token=teammate_at,+ scoped_teams=[self.team.id, 99999],+ )res = self._post_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}/remove", token=token)assert res.status_code == 200@@ -51,3 +72,7 @@ class TestRemoveAndRotate(StripeProvisioningTestBase):# token itself is gone, so further calls are unauthorized.detail = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)assert detail.status_code == 401+ teammate_at.refresh_from_db()+ teammate_rt.refresh_from_db()+ assert teammate_at.scoped_teams == [99999]+ assert teammate_rt.scoped_teams == [99999]diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.pyindex 722027f791b1..a8faedc494a3 100644--- a/ee/partners/stripe/api/provisioning/views.py+++ b/ee/partners/stripe/api/provisioning/views.py@@ -58,6 +58,7 @@ from ee.partners.stripe.api.provisioning.constants import (from ee.partners.stripe.api.provisioning.core import (ProjectIdCollisionError,StripeOAuthAppMissingError,+ base_team_id_from_scope,compute_partner_scoped_teams,get_available_teams_for_user,get_oauth_app_for_code,@@ -477,16 +478,12 @@ class OAuthTokenView(StripeProvisioningAPIView):raise SpecError("invalid_grant", "Refresh token was not issued for the Stripe Projects app")user = old_refresh.userold_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+ # base_team_id at refresh must be the consent team. compute_partner_scoped_teams+ # keeps base_team_id unconditionally but keeps other teams only when they have a+ # TeamProvisioningConfig for this app, so any other base silently drops an+ # unattributed consent team from the refreshed scope. An empty prior scope yields+ # zero, so the helper short-circuits without claiming a team.+ base_team_id = base_team_id_from_scope(oauth_app, old_scoped_teams)# Deactivation drops the user's login sessions but leaves their OAuth tokens# intact, and the team check below answers only about membership and roles, so adiff --git a/posthog/management/commands/backfill_agentic_provisioning_attribution.py b/posthog/management/commands/backfill_agentic_provisioning_attribution.pynew file mode 100644index 000000000000..03e947ace1d8--- /dev/null+++ b/posthog/management/commands/backfill_agentic_provisioning_attribution.py@@ -0,0 +1,136 @@+import csv+import uuid+from argparse import ArgumentParser+from collections import Counter, defaultdict+from collections.abc import Iterable, Mapping+from enum import StrEnum+from pathlib import Path+from typing import Any++from django.core.management.base import BaseCommand, CommandError++from posthog.models.oauth import OAuthApplication+from posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig++REQUIRED_COLUMNS = {"team_id", "partner_id"}+++class Outcome(StrEnum):+ CREATE = "create"+ FILL = "fill"+ ALREADY_ATTRIBUTED = "already_attributed"+ SKIPPED_OTHER_APPLICATION = "skipped_other_application"+ SKIPPED_CONFLICTING_PARTNERS = "skipped_conflicting_partners"+ SKIPPED_TEAM_NOT_FOUND = "skipped_team_not_found"+ SKIPPED_APPLICATION_NOT_FOUND = "skipped_application_not_found"+ SKIPPED_NOT_PROVISIONING_PARTNER = "skipped_not_provisioning_partner"+ SKIPPED_INVALID_ROW = "skipped_invalid_row"+++WRITE_OUTCOMES = {Outcome.CREATE, Outcome.FILL}+++def _parse_row(row: Mapping[str, str | None]) -> tuple[int, uuid.UUID] | None:+ try:+ return int(row["team_id"] or ""), uuid.UUID((row["partner_id"] or "").strip())+ except ValueError:+ return None+++def _classify(+ team_id: int,+ application: OAuthApplication | None,+ existing_team_ids: set[int],+ attributed: dict[int, uuid.UUID | None],+) -> Outcome:+ if application is None:+ return Outcome.SKIPPED_APPLICATION_NOT_FOUND+ if not application.is_provisioning_partner:+ return Outcome.SKIPPED_NOT_PROVISIONING_PARTNER+ if team_id not in existing_team_ids:+ return Outcome.SKIPPED_TEAM_NOT_FOUND+ if team_id not in attributed:+ return Outcome.CREATE+ if attributed[team_id] is None:+ return Outcome.FILL+ if attributed[team_id] == application.id:+ return Outcome.ALREADY_ATTRIBUTED+ return Outcome.SKIPPED_OTHER_APPLICATION+++def _write(team_id: int, application: OAuthApplication, outcome: Outcome) -> Outcome:+ if outcome is Outcome.CREATE:+ _, created = TeamProvisioningConfig.objects.get_or_create(+ team_id=team_id, defaults={"application": application}+ )+ if created:+ return Outcome.CREATE+ if TeamProvisioningConfig.objects.filter(team_id=team_id, application__isnull=True).update(application=application):+ return Outcome.FILL+ current = TeamProvisioningConfig.objects.filter(team_id=team_id).values_list("application_id", flat=True).first()+ return Outcome.ALREADY_ATTRIBUTED if current == application.id else Outcome.SKIPPED_OTHER_APPLICATION+++def backfill_partner_attribution(rows: Iterable[Mapping[str, str | None]], *, live_run: bool) -> Counter[Outcome]:+ outcomes: Counter[Outcome] = Counter()+ partners_by_team: defaultdict[int, set[uuid.UUID]] = defaultdict(set)+ for row in rows:+ parsed = _parse_row(row)+ if parsed is None:+ outcomes[Outcome.SKIPPED_INVALID_ROW] += 1+ else:+ team_id, partner_id = parsed+ partners_by_team[team_id].add(partner_id)++ pairs: dict[int, uuid.UUID] = {}+ for team_id, partner_ids in partners_by_team.items():+ if len(partner_ids) > 1:+ outcomes[Outcome.SKIPPED_CONFLICTING_PARTNERS] += 1+ else:+ pairs[team_id] = next(iter(partner_ids))++ applications = OAuthApplication.objects.in_bulk(set(pairs.values()))+ existing_team_ids = set(Team.objects.filter(id__in=pairs).values_list("id", flat=True))+ attributed: dict[int, uuid.UUID | None] = dict(+ TeamProvisioningConfig.objects.filter(team_id__in=pairs).values_list("team_id", "application_id")+ )++ for team_id, partner_id in pairs.items():+ application = applications.get(partner_id)+ outcome = _classify(team_id, application, existing_team_ids, attributed)+ if live_run and application is not None and outcome in WRITE_OUTCOMES:+ outcome = _write(team_id, application, outcome)+ outcomes[outcome] += 1+ return outcomes+++class Command(BaseCommand):+ help = (+ "Attribute partner-created teams to the provisioning partner that created them, from a CSV "+ "with team_id and partner_id (OAuthApplication id) columns. Creates a missing "+ "TeamProvisioningConfig row or fills a null application, and never replaces a different one."+ )++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument("csv_file", type=Path)+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Write the changes. Without it the command only reports what it would do.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ live_run: bool = options["live_run"]+ csv_path: Path = options["csv_file"]+ with csv_path.open(newline="", encoding="utf-8-sig") as csv_file:+ reader = csv.DictReader(csv_file)+ missing_columns = REQUIRED_COLUMNS - set(reader.fieldnames or [])+ if missing_columns:+ raise CommandError(f"CSV is missing column(s): {', '.join(sorted(missing_columns))}")+ outcomes = backfill_partner_attribution(reader, live_run=live_run)++ self.stdout.write("Live run." if live_run else "Dry run, nothing written. Pass --live-run to write.")+ for outcome in Outcome:+ label = f"would {outcome}" if not live_run and outcome in WRITE_OUTCOMES else str(outcome)+ self.stdout.write(f"{label}: {outcomes[outcome]}")diff --git a/posthog/management/commands/backfill_agentic_provisioning_scope.py b/posthog/management/commands/backfill_agentic_provisioning_scope.pyindex 32930eb92c40..7a26804dcfa0 100644--- a/posthog/management/commands/backfill_agentic_provisioning_scope.py+++ b/posthog/management/commands/backfill_agentic_provisioning_scope.py@@ -33,6 +33,7 @@ class Command(BaseCommand):# registry; the provisioning package pulls in a much larger dependency# surface than the rest of the command suite.from ee.api.agentic_provisioning.tokens import (+ base_team_id_from_scope,compute_partner_scoped_teams, # noqa: PLC0415 — keeps the heavy dep off the import path)@@ -68,7 +69,7 @@ class Command(BaseCommand):if user is None:continueold_scope = list(access_token.scoped_teams or [])- base_team_id = old_scope[0] if old_scope else 0+ base_team_id = base_team_id_from_scope(application, old_scope)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@@ -82,12 +83,10 @@ class Command(BaseCommand):f"new=[] (empty scope; left unchanged, needs re-authorization)")continue- if sorted(new_scope) == sorted(old_scope):+ if new_scope == old_scope:continuechanged_access += 1- self.stdout.write(- f" access_token={access_token.pk} user={user.id} old={sorted(old_scope)} new={sorted(new_scope)}"- )+ self.stdout.write(f" access_token={access_token.pk} user={user.id} old={old_scope} new={new_scope}")if not dry_run:try:with transaction.atomic():@@ -109,7 +108,7 @@ class Command(BaseCommand):if user is None:continueold_scope = list(refresh_token.scoped_teams or [])- base_team_id = old_scope[0] if old_scope else 0+ base_team_id = base_team_id_from_scope(application, old_scope)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.@@ -120,12 +119,10 @@ class Command(BaseCommand):f"new=[] (empty scope; left unchanged, needs re-authorization)")continue- if sorted(new_scope) == sorted(old_scope):+ if new_scope == old_scope:continuechanged_refresh += 1- self.stdout.write(- f" refresh_token={refresh_token.pk} user={user.id} old={sorted(old_scope)} new={sorted(new_scope)}"- )+ self.stdout.write(f" refresh_token={refresh_token.pk} user={user.id} old={old_scope} new={new_scope}")if not dry_run:try:with transaction.atomic():diff --git a/posthog/management/commands/test/test_backfill_agentic_provisioning_attribution.py b/posthog/management/commands/test/test_backfill_agentic_provisioning_attribution.pynew file mode 100644index 000000000000..344cb6083a64--- /dev/null+++ b/posthog/management/commands/test/test_backfill_agentic_provisioning_attribution.py@@ -0,0 +1,114 @@+import csv+import uuid+import tempfile+from io import StringIO+from pathlib import Path++from posthog.test.base import BaseTest++from django.core.management import call_command++from parameterized import parameterized++from posthog.models.oauth import OAuthApplication+from posthog.models.team.team import Team+from posthog.models.team.team_provisioning_config import TeamProvisioningConfig++NO_ROW = "no_row"+++class TestBackfillAgenticProvisioningAttribution(BaseTest):+ def setUp(self):+ super().setUp()+ self.apps = {+ "partner": self._create_app("partner", is_provisioning_partner=True),+ "other_partner": self._create_app("other-partner", is_provisioning_partner=True),+ "non_partner": self._create_app("non-partner", is_provisioning_partner=False),+ }++ def _create_app(self, client_id: str, *, is_provisioning_partner: bool) -> OAuthApplication:+ return OAuthApplication.objects.create(+ client_id=client_id,+ name=client_id,+ client_secret="",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://partner.example.com/callback",+ algorithm="RS256",+ is_provisioning_partner=is_provisioning_partner,+ )++ def _run_command(self, rows: list[tuple[object, object]], *args: str) -> str:+ out = StringIO()+ with tempfile.TemporaryDirectory() as tmp_dir:+ csv_path = Path(tmp_dir) / "attribution.csv"+ with csv_path.open("w", newline="") as csv_file:+ writer = csv.writer(csv_file)+ writer.writerow(["team_id", "partner_id"])+ writer.writerows(rows)+ call_command("backfill_agentic_provisioning_attribution", str(csv_path), *args, stdout=out)+ return out.getvalue()++ def _seed_config(self, team: Team, application: str | None) -> None:+ TeamProvisioningConfig.objects.create(team=team, application=self.apps[application] if application else None)++ def _attribution(self, team: Team) -> str | None:+ config = TeamProvisioningConfig.objects.filter(team=team).first()+ if config is None:+ return NO_ROW+ if config.application_id is None:+ return None+ return next(name for name, app in self.apps.items() if app.id == config.application_id)++ @parameterized.expand(+ [+ ("creates_missing_row", NO_ROW, "partner", "partner"),+ ("fills_null_application", None, "partner", "partner"),+ ("never_replaces_another_application", "other_partner", "partner", "other_partner"),+ ("ignores_app_that_is_not_a_provisioning_partner", NO_ROW, "non_partner", NO_ROW),+ ]+ )+ def test_live_run_attribution(self, _name, existing, listed, expected):+ if existing != NO_ROW:+ self._seed_config(self.team, existing)++ self._run_command([(self.team.id, self.apps[listed].id)], "--live-run")++ assert self._attribution(self.team) == expected++ def test_dry_run_writes_nothing(self):+ null_team = Team.objects.create(organization=self.organization, name="Unclaimed team")+ self._seed_config(null_team, None)+ partner_id = self.apps["partner"].id++ output = self._run_command([(self.team.id, partner_id), (null_team.id, partner_id)])++ assert self._attribution(self.team) == NO_ROW+ assert self._attribution(null_team) is None+ assert "would create: 1" in output+ assert "would fill: 1" in output++ def test_live_run_skips_unresolvable_rows_and_attributes_the_rest(self):+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ conflicting_team = Team.objects.create(organization=self.organization, name="Conflicting team")+ partner_id = self.apps["partner"].id++ output = self._run_command(+ [+ (999_999_999, partner_id),+ (self.team.id, uuid.uuid4()),+ ("not-a-team-id", partner_id),+ (other_team.id, partner_id),+ (conflicting_team.id, partner_id),+ (conflicting_team.id, self.apps["other_partner"].id),+ ],+ "--live-run",+ )++ assert self._attribution(self.team) == NO_ROW+ assert self._attribution(other_team) == "partner"+ assert self._attribution(conflicting_team) == NO_ROW+ assert "skipped_team_not_found: 1" in output+ assert "skipped_application_not_found: 1" in output+ assert "skipped_invalid_row: 1" in output+ assert "skipped_conflicting_partners: 1" in output