: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(provisioning): default-off provisioned PAT mint gate (#61760)
Matt Brooker42199fb20d14
diff --git a/ee/api/agentic_provisioning/test/base.py b/ee/api/agentic_provisioning/test/base.pyindex d81f85e3da9a..e49f42b71988 100644--- a/ee/api/agentic_provisioning/test/base.py+++ b/ee/api/agentic_provisioning/test/base.py@@ -59,6 +59,9 @@ class ProvisioningTestBase(APIBaseTest):"redirect_uris": "https://localhost","algorithm": "RS256","provisioning_can_issue_deep_links": True,+ # The test app stands in for the grandfathered legacy Stripe app, which is+ # the one app that still mints a provisioned PAT.+ "provisioning_issues_personal_api_key": True,},)diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex d9cf9113dc53..569e658bd9ca 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -370,7 +370,7 @@ class TestProvisioningAuthentication(APIBaseTest):# --- PAT scopes ---- def test_provisioned_pat_created(self):+ def test_default_off_app_mints_no_provisioned_pat(self):from posthog.models.personal_api_key import PersonalAPIKeyverifier, challenge = _pkce_pair()@@ -414,8 +414,9 @@ class TestProvisioningAuthentication(APIBaseTest):from posthog.models.user import Useruser = User.objects.get(email=email)+ # The wizard app does not set provisioning_issues_personal_api_key, so no PAT is minted.pat = PersonalAPIKey.objects.filter(user=user).first()- assert pat is not None+ assert pat is None# --- is_active kill switch ---diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex 824ca6bff6c1..17165f85a270 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -4,12 +4,12 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.models.oauth import OAuthAccessToken+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase-from ee.api.agentic_provisioning.views import _create_provisioned_pat+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase+from ee.api.agentic_provisioning.views import _maybe_create_provisioned_pat@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)@@ -152,8 +152,13 @@ class TestProvisioningResources(ProvisioningTestBase):assert pat is not Noneassert pat.label == self.team.name[:40]- def test_create_resource_pat_is_scoped_to_authorized_team(self):+ def test_create_resource_pat_inherits_app_scope_ceiling(self):token = self._get_bearer_token()+ # Seed the grandfathered app's ceiling after minting the bearer so the PAT is+ # capped at the app's scopes rather than the old hardcoded ["*"].+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ app.scopes = ["insight:read", "query:read"]+ app.save(update_fields=["scopes"])self._post_signed_with_bearer("/api/agentic/provisioning/resources",data={"service_id": "analytics"},@@ -161,10 +166,48 @@ class TestProvisioningResources(ProvisioningTestBase):)pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not None- assert pat.scopes == ["*"]+ assert pat.scopes == ["insight:read", "query:read"]assert pat.scoped_teams == [self.team.id]assert pat.scoped_organizations == [str(self.team.organization_id)]+ def test_create_resource_omits_pat_when_app_gate_off(self):+ token = self._get_bearer_token()+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ app.provisioning_issues_personal_api_key = False+ app.save(update_fields=["provisioning_issues_personal_api_key"])+ before = PersonalAPIKey.objects.filter(user=self.user).count()+ res = self._post_signed_with_bearer(+ "/api/agentic/provisioning/resources",+ data={"service_id": "analytics"},+ token=token,+ )+ assert res.status_code == 200+ assert "personal_api_key" not in res.json()["complete"]["access_configuration"]+ assert PersonalAPIKey.objects.filter(user=self.user).count() == before++ @parameterized.expand([("gate_off", False), ("gate_on", True)])+ def test_create_provisioned_pat_gate(self, _name, gate_on):+ app = OAuthApplication.objects.create(+ name="Gate test app",+ client_id=f"gate_test_{gate_on}",+ client_secret="",+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://localhost",+ algorithm="RS256",+ scopes=["insight:read"],+ provisioning_issues_personal_api_key=gate_on,+ )+ result = _maybe_create_provisioned_pat(self.user, self.team, app)+ if gate_on:+ assert result is not None+ pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()+ assert pat is not None+ assert pat.scopes == ["insight:read"]+ else:+ assert result is None+ assert not PersonalAPIKey.objects.filter(user=self.user).exists()+def test_create_resource_does_not_delete_existing_pats(self):token = self._get_bearer_token()self._post_signed_with_bearer(@@ -546,6 +589,12 @@ class TestProvisioningResources(ProvisioningTestBase):@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)class TestCreateProvisionedPat(ProvisioningTestBase):+ def _minting_app(self) -> OAuthApplication:+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ app.scopes = ["query:read"]+ app.save(update_fields=["scopes"])+ return app+@parameterized.expand([("default_when_none", None, "{team_name}"),@@ -554,7 +603,7 @@ class TestCreateProvisionedPat(ProvisioningTestBase):])def test_label_prefix_resolution(self, _name, label_prefix, expected_label_template):- api_key = _create_provisioned_pat(self.user, self.team, label_prefix=label_prefix)+ api_key = _maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), label_prefix=label_prefix)assert api_key is not Nonepat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not None@@ -563,8 +612,17 @@ class TestCreateProvisionedPat(ProvisioningTestBase):def test_label_is_truncated_to_40_chars(self):self.team.name = "A" * 60self.team.save()- _create_provisioned_pat(self.user, self.team, label_prefix="LongPartnerName")+ _maybe_create_provisioned_pat(self.user, self.team, self._minting_app(), label_prefix="LongPartnerName")pat = PersonalAPIKey.objects.filter(user=self.user).order_by("-created_at").first()assert pat is not Noneassert len(pat.label) == 40assert pat.label.startswith("LongPartnerName - ")++ def test_no_pat_when_ceiling_unseeded(self):+ # A flag-on app without a scope ceiling must not fall back to ["*"] or+ # mint an empty-scope key — skip the mint entirely.+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ assert app.scopes == []+ initial_count = PersonalAPIKey.objects.filter(user=self.user).count()+ assert _maybe_create_provisioned_pat(self.user, self.team, app) is None+ assert PersonalAPIKey.objects.filter(user=self.user).count() == initial_countdiff --git a/ee/api/agentic_provisioning/test/test_rotate_credentials.py b/ee/api/agentic_provisioning/test/test_rotate_credentials.pyindex f99a75221b81..b5fc0d88c720 100644--- a/ee/api/agentic_provisioning/test/test_rotate_credentials.py+++ b/ee/api/agentic_provisioning/test/test_rotate_credentials.py@@ -4,11 +4,11 @@ from django.test import override_settingsfrom parameterized import parameterized-from posthog.models.oauth import OAuthAccessToken+from posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team-from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase+from ee.api.agentic_provisioning.test.base import HMAC_SECRET, TEST_STRIPE_OAUTH_CLIENT_ID, ProvisioningTestBase@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)@@ -97,6 +97,18 @@ class TestProvisioningRotateCredentials(ProvisioningTestBase):personal_api_key = res.json()["complete"]["access_configuration"]["personal_api_key"]assert personal_api_key.startswith("phx_")+ def test_rotate_omits_pat_when_app_gate_off(self):+ token = self._get_bearer_token()+ app = OAuthApplication.objects.get(client_id=TEST_STRIPE_OAUTH_CLIENT_ID)+ app.provisioning_issues_personal_api_key = False+ app.save(update_fields=["provisioning_issues_personal_api_key"])+ res = self._post_signed_with_bearer(+ f"/api/agentic/provisioning/resources/{self.team.id}/rotate_credentials",+ token=token,+ )+ assert res.status_code == 200+ assert "personal_api_key" not in res.json()["complete"]["access_configuration"]+def test_rotate_pat_is_scoped_to_authorized_team(self):token = self._get_bearer_token()self._post_signed_with_bearer(diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 218880cce762..fbc5c2414e07 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -1340,12 +1340,21 @@ def _extract_label_prefix(request: Request) -> str | None:return stripped-def _create_provisioned_pat(user: User, team: Team, label_prefix: str | None = None) -> str | None:+def _maybe_create_provisioned_pat(+ user: User, team: Team, app: OAuthApplication | None, label_prefix: str | None = None+) -> str | None:"""Create a Personal API Key for a provisioned user and return the raw key value.- Scopes are ["*"] so downstream tooling (e.g. the wizard CI install flow)- can use the key without silent 403s — a narrow default has no in-product- recovery path since there's no scope upgrade UI.+ Gated by ``app.provisioning_issues_personal_api_key``: off by default, so most+ apps never receive a provisioned PAT (the OAuth token is the credential).+ Returns ``None`` when the gate is off, and the caller omits ``personal_api_key``+ from the response entirely.++ When enabled (the grandfathered legacy Stripe app), the key is scoped to the+ app's ``scopes`` ceiling rather than ``["*"]`` so a provisioned PAT can never+ exceed what the issuing app is itself allowed. A flag-on app with an unseeded+ ceiling mints nothing: an empty-scope PAT fails every scope check, and widening+ to a wildcard would bypass the ceiling.scoped_teams is set to [team.id] so the PAT only grants access to the teambeing provisioned, matching the scoping of the OAuth token issued in the@@ -1355,6 +1364,11 @@ def _create_provisioned_pat(user: User, team: Team, label_prefix: str | None = N``label_prefix`` should be pre-validated by ``_extract_label_prefix``; pass``None`` (or any falsy value) to label the key with just the team name."""+ if not app or not app.provisioning_issues_personal_api_key:+ return None+ if not app.scopes:+ _capture_provisioning_event("pat_mint", "skipped_unseeded_ceiling", partner=app, team_id=team.id)+ return Nonetry:api_key_value = generate_random_token_personal()label_base = f"{label_prefix} - {team.name}" if label_prefix else team.name@@ -1367,7 +1381,7 @@ def _create_provisioned_pat(user: User, team: Team, label_prefix: str | None = Nlabel=label,secure_value=hash_key_value(api_key_value),mask_value=mask_key_value(api_key_value),- scopes=["*"],+ scopes=list(app.scopes),scoped_teams=[team.id],scoped_organizations=[str(team.organization_id)],)@@ -1645,7 +1659,9 @@ def provisioning_resources_create(request: Request) -> Response:"api_key": team.api_token,"host": host,}- if personal_api_key := _create_provisioned_pat(user, team, label_prefix=label_prefix):+ if personal_api_key := _maybe_create_provisioned_pat(+ user, team, access_token.application, label_prefix=label_prefix+ ):access_configuration["personal_api_key"] = personal_api_keyreturn Response(@@ -1734,7 +1750,9 @@ def provisioning_rotate_credentials(request: Request, resource_id: str) -> Respo"api_key": team.api_token,"host": host,}- if personal_api_key := _create_provisioned_pat(user, team, label_prefix=label_prefix):+ if personal_api_key := _maybe_create_provisioned_pat(+ user, team, access_token.application, label_prefix=label_prefix+ ):access_configuration["personal_api_key"] = personal_api_keyreturn Response(diff --git a/posthog/admin/admins/oauth_admin.py b/posthog/admin/admins/oauth_admin.pyindex 9f7b24c7f798..29795fb9996d 100644--- a/posthog/admin/admins/oauth_admin.py+++ b/posthog/admin/admins/oauth_admin.py@@ -123,6 +123,7 @@ class OAuthApplicationAdmin(admin.ModelAdmin): # nosemgrep: admin-modeladmin-ne"provisioning_active","provisioning_skip_existing_user_consent","provisioning_can_issue_deep_links",+ "provisioning_issues_personal_api_key","provisioning_can_create_accounts","provisioning_can_provision_resources","provisioning_rate_limit_account_requests",diff --git a/posthog/migrations/1211_oauthapplication_provisioning_issues_personal_api_key.py b/posthog/migrations/1211_oauthapplication_provisioning_issues_personal_api_key.pynew file mode 100644index 000000000000..bf459671a8a7--- /dev/null+++ b/posthog/migrations/1211_oauthapplication_provisioning_issues_personal_api_key.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.14 on 2026-06-05 19:54++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1210_team_ingested_production_event"),+ ]++ operations = [+ migrations.AddField(+ model_name="oauthapplication",+ name="provisioning_issues_personal_api_key",+ field=models.BooleanField(+ db_default=False,+ default=False,+ help_text="Whether provisioning mints a Personal API Key for this app. Off by default; only grandfathered apps (the legacy Stripe app) still issue one, capped at the app's scopes.",+ ),+ ),+ ]diff --git a/posthog/migrations/1212_grandfather_stripe_provisioned_pat.py b/posthog/migrations/1212_grandfather_stripe_provisioned_pat.pynew file mode 100644index 000000000000..50120623c189--- /dev/null+++ b/posthog/migrations/1212_grandfather_stripe_provisioned_pat.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.14 on 2026-06-04 21:20++from django.conf import settings+from django.db import migrations+++def grandfather_stripe_provisioned_pat(apps, schema_editor):+ # The legacy Stripe app shipped a published .env contract that includes a provisioned+ # PAT, so it keeps minting one (capped at its scopes) while every other app defaults off.+ client_id = getattr(settings, "STRIPE_POSTHOG_OAUTH_CLIENT_ID", None)+ if not client_id:+ return+ OAuthApplication = apps.get_model("posthog", "OAuthApplication")+ OAuthApplication.objects.filter(client_id=client_id).update(provisioning_issues_personal_api_key=True)+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1211_oauthapplication_provisioning_issues_personal_api_key"),+ ]++ operations = [+ migrations.RunPython(grandfather_stripe_provisioned_pat, migrations.RunPython.noop),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 24789ce43664..728ef8dce72a 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1210_team_ingested_production_event+1212_grandfather_stripe_provisioned_patdiff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex bd9baa279d04..a8456e6e779c 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -156,6 +156,14 @@ class OAuthApplication(AbstractApplication):provisioning_can_provision_resources: models.BooleanField = models.BooleanField(default=True, help_text="Can this app provision projects and API keys")+ provisioning_issues_personal_api_key: models.BooleanField = models.BooleanField(+ default=False,+ db_default=False,+ help_text=(+ "Whether provisioning mints a Personal API Key for this app. Off by default; "+ "only grandfathered apps (the legacy Stripe app) still issue one, capped at the app's scopes."+ ),+ )provisioning_rate_limit_account_requests: models.IntegerField = models.IntegerField(null=True, blank=True, help_text="Override default rate limit for account_requests (per hour)")