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.

feat(security): require consent for silent re-mint from new partners post-review (#60359)

Matt Brookerdce0a15f896a
diff --git a/ee/api/agentic_provisioning/test/test_account_requests.py b/ee/api/agentic_provisioning/test/test_account_requests.py
index c603973a4e57..86ee9f2ae0b5 100644
--- a/ee/api/agentic_provisioning/test/test_account_requests.py
+++ b/ee/api/agentic_provisioning/test/test_account_requests.py
@@ -1,4 +1,5 @@
import json
+import time
from datetime import timedelta
from urllib.parse import parse_qs, urlparse
@@ -12,14 +13,17 @@ from django.utils import timezone
from parameterized import parameterized
from rest_framework.response import Response
-from posthog.models.oauth import OAuthApplication
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken
from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
from ee.api.agentic_provisioning import AUTH_CODE_CACHE_PREFIX, PENDING_AUTH_CACHE_PREFIX
+from ee.api.agentic_provisioning.signature import compute_signature
from ee.api.agentic_provisioning.test.base import HMAC_SECRET, ProvisioningTestBase
+HMAC_PARTNER_SECRET = "test_hmac_partner_secret"
+
@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
class TestAccountRequests(ProvisioningTestBase):
@@ -400,3 +404,279 @@ class TestPKCEPartnerExistingUserConsent(ProvisioningTestBase):
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_request"
assert "code_challenge" in res.json()["error"]["message"]
+
+
+@override_settings(STRIPE_SIGNING_SECRET=HMAC_SECRET)
+class TestSilentRemintBlockedAfterReview(ProvisioningTestBase):
+ """Once a user has reviewed their credentials, a partner with
+ skip_existing_user_consent=True can only re-mint silently when it already
+ holds live OAuth credentials on that user — otherwise the consent screen
+ is required. Closes the server-side half of the pre-hijacking defense."""
+
+ def setUp(self):
+ super().setUp()
+ self.partner = OAuthApplication.objects.create(
+ client_id="silent-partner",
+ name="Silent Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://partner.example.com/callback",
+ algorithm="RS256",
+ is_first_party=True,
+ provisioning_auth_method="pkce",
+ provisioning_partner_type="test_partner",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ provisioning_skip_existing_user_consent=True,
+ )
+ self.other_partner = OAuthApplication.objects.create(
+ client_id="other-partner",
+ name="Other Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_PUBLIC,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://other.example.com/callback",
+ algorithm="RS256",
+ is_first_party=True,
+ provisioning_auth_method="pkce",
+ provisioning_partner_type="test_partner",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ provisioning_skip_existing_user_consent=True,
+ )
+ self.hmac_partner = OAuthApplication.objects.create(
+ client_id="hmac-partner",
+ name="HMAC Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://hmac.example.com/callback",
+ algorithm="RS256",
+ is_first_party=True,
+ provisioning_auth_method="hmac",
+ provisioning_signing_secret=HMAC_PARTNER_SECRET,
+ provisioning_partner_type="test_partner",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ provisioning_skip_existing_user_consent=True,
+ )
+ self.bearer_partner = OAuthApplication.objects.create(
+ client_id="bearer-partner",
+ name="Bearer Partner",
+ client_secret="",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://bearer.example.com/callback",
+ algorithm="RS256",
+ is_first_party=True,
+ provisioning_auth_method="bearer",
+ provisioning_partner_type="test_partner",
+ provisioning_active=True,
+ provisioning_can_create_accounts=True,
+ provisioning_can_provision_resources=True,
+ provisioning_skip_existing_user_consent=True,
+ )
+
+ def _post_as_partner(self, data: dict, client_id: str = "silent-partner"):
+ payload = {**data, "client_id": client_id}
+ body = json.dumps(payload).encode()
+ return self.client.post(
+ "/api/agentic/provisioning/account_requests",
+ data=body,
+ content_type="application/json",
+ HTTP_API_VERSION="0.1d",
+ )
+
+ def _post_as_hmac_partner(self, data: dict):
+ body = json.dumps(data).encode()
+ ts = int(time.time())
+ sig = compute_signature(HMAC_PARTNER_SECRET, ts, body)
+ return self.client.post(
+ "/api/agentic/provisioning/account_requests",
+ data=body,
+ content_type="application/json",
+ HTTP_STRIPE_SIGNATURE=f"t={ts},v1={sig}",
+ HTTP_API_VERSION="0.1d",
+ )
+
+ def _post_as_bearer_partner(self, data: dict, token: str):
+ body = json.dumps(data).encode()
+ return self.client.post(
+ "/api/agentic/provisioning/account_requests",
+ data=body,
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ HTTP_API_VERSION="0.1d",
+ )
+
+ def _account_request_payload(self, **overrides):
+ payload = {
+ "id": "acctreq_silent_test",
+ "email": "[email protected]",
+ "scopes": ["query:read"],
+ "confirmation_secret": "cs_test",
+ "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ "code_challenge_method": "S256",
+ "expires_at": (timezone.now() + timedelta(minutes=10)).isoformat(),
+ "orchestrator": {"type": "test", "account": "acct_123"},
+ }
+ payload.update(overrides)
+ return payload
+
+ def _make_user(self, *, credentials_reviewed: bool) -> User:
+ user = User.objects.create_and_join(
+ organization=self.organization,
+ password="testpass",
+ first_name="Existing",
+ )
+ user.credentials_reviewed_at = timezone.now() if credentials_reviewed else None
+ user.save(update_fields=["credentials_reviewed_at"])
+ return user
+
+ def _make_live_access_token(self, user: User, partner: OAuthApplication) -> OAuthAccessToken:
+ return OAuthAccessToken.objects.create(
+ user=user,
+ application=partner,
+ token=f"tok_{user.id}_{partner.id}",
+ expires=timezone.now() + timedelta(hours=1),
+ scope="query:read",
+ )
+
+ def _make_live_refresh_token(self, user: User, partner: OAuthApplication) -> OAuthRefreshToken:
+ return OAuthRefreshToken.objects.create(
+ user=user,
+ application=partner,
+ token=f"rtok_{user.id}_{partner.id}",
+ revoked=None,
+ )
+
+ def _make_revoked_refresh_token(self, user: User, partner: OAuthApplication) -> OAuthRefreshToken:
+ return OAuthRefreshToken.objects.create(
+ user=user,
+ application=partner,
+ token=f"rtok_{user.id}_{partner.id}",
+ revoked=timezone.now(),
+ )
+
+ def test_unreviewed_user_silent_path_still_works(self):
+ self._make_user(credentials_reviewed=False)
+ res = self._post_as_partner(self._account_request_payload())
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "oauth"
+ assert "code" in data["oauth"]
+
+ @parameterized.expand(
+ [
+ ("live_access_token", lambda self, user: self._make_live_access_token(user, self.hmac_partner)),
+ ("live_refresh_token", lambda self, user: self._make_live_refresh_token(user, self.hmac_partner)),
+ ]
+ )
+ def test_reviewed_user_with_live_credential_from_authenticated_caller_silent_still_works(
+ self, _name, setup_credential
+ ):
+ user = self._make_user(credentials_reviewed=True)
+ setup_credential(self, user)
+ res = self._post_as_hmac_partner(self._account_request_payload())
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "oauth"
+ assert "code" in data["oauth"]
+
+ def test_pkce_caller_with_live_credential_is_blocked_post_review(self):
+ # A public PKCE caller is unauthenticated, so an existing live credential
+ # for the claimed client_id is not proof the caller controls the partner.
+ # It must not unlock the silent path once the user has reviewed credentials.
+ user = self._make_user(credentials_reviewed=True)
+ self._make_live_access_token(user, self.partner)
+ res = self._post_as_partner(self._account_request_payload())
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "requires_auth"
+ assert "oauth" not in data
+
+ def test_pkce_caller_with_live_credential_unreviewed_silent_still_works(self):
+ # The public-client lockout only applies after review; the legitimate
+ # Connect re-link flow on an unreviewed user must stay silent.
+ user = self._make_user(credentials_reviewed=False)
+ self._make_live_access_token(user, self.partner)
+ res = self._post_as_partner(self._account_request_payload())
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "oauth"
+ assert "code" in data["oauth"]
+
+ @parameterized.expand(
+ [
+ ("no_credentials", lambda self, user: None),
+ (
+ "different_partner_credential",
+ lambda self, user: self._make_live_access_token(user, self.other_partner),
+ ),
+ ("only_revoked_token", lambda self, user: self._make_revoked_refresh_token(user, self.partner)),
+ ]
+ )
+ def test_reviewed_user_without_live_caller_credential_falls_through_to_consent(self, _name, setup_credential):
+ user = self._make_user(credentials_reviewed=True)
+ setup_credential(self, user)
+ res = self._post_as_partner(self._account_request_payload())
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "requires_auth"
+ assert "url" in data["requires_auth"]
+ assert "/api/agentic/authorize" in data["requires_auth"]["url"]
+ assert "oauth" not in data
+
+ url = data["requires_auth"]["url"]
+ state = parse_qs(urlparse(url).query)["state"][0]
+ pending = cache.get(f"{PENDING_AUTH_CACHE_PREFIX}{state}")
+ assert pending is not None
+ assert pending["partner_id"] == str(self.partner.id)
+
+ def _mint_bearer_token(self, user: User, partner: OAuthApplication, raw_token: str) -> None:
+ OAuthAccessToken.objects.create(
+ user=user,
+ application=partner,
+ token=raw_token,
+ expires=timezone.now() + timedelta(hours=1),
+ scope="query:read",
+ )
+
+ def test_bearer_caller_cannot_remint_for_other_user_post_review(self):
+ # A bearer token only proves the caller holds *some* user's token under the
+ # partner's client, not that they control the partner. An attacker holding their
+ # own token must not ride a reviewed victim's existing credential to mint a code
+ # for the victim's account.
+ victim = self._make_user(credentials_reviewed=True)
+ self._make_live_access_token(victim, self.bearer_partner)
+
+ attacker = User.objects.create_and_join(
+ organization=self.organization,
+ password="testpass",
+ first_name="Attacker",
+ )
+ self._mint_bearer_token(attacker, self.bearer_partner, "attacker_bearer_token")
+
+ res = self._post_as_bearer_partner(self._account_request_payload(), token="attacker_bearer_token")
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "requires_auth"
+ assert "oauth" not in data
+
+ def test_bearer_caller_can_remint_for_own_user_post_review(self):
+ # The legitimate bearer re-link path: the caller presents the very user's own
+ # token, which is genuine proof of an existing trust relationship.
+ user = self._make_user(credentials_reviewed=True)
+ self._mint_bearer_token(user, self.bearer_partner, "owner_bearer_token")
+
+ res = self._post_as_bearer_partner(self._account_request_payload(), token="owner_bearer_token")
+ assert res.status_code == 200
+ data = res.json()
+ assert data["type"] == "oauth"
+ assert "code" in data["oauth"]
diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.py
index 6396eba9e664..53a27b303fa3 100644
--- a/ee/api/agentic_provisioning/views.py
+++ b/ee/api/agentic_provisioning/views.py
@@ -292,10 +292,11 @@ def account_requests(request: Request) -> Response:
# --- Identify partner ---
auth = ProvisioningAuthentication()
partner = None
+ authenticated_user = None
try:
result = auth.authenticate(request)
if result:
- _, partner = result
+ authenticated_user, partner = result
except AuthenticationFailed:
return Response(
{"type": "error", "error": {"code": "unauthorized", "message": "Authentication failed"}},
@@ -434,13 +435,61 @@ def account_requests(request: Request) -> Response:
partner,
code_challenge,
code_challenge_method,
+ authenticated_user,
)
return _handle_new_user(
- request_id, data, email, scopes, partner_account_id, region, partner, code_challenge, code_challenge_method
+ request_id,
+ data,
+ email,
+ scopes,
+ partner_account_id,
+ region,
+ partner,
+ code_challenge,
+ code_challenge_method,
+ authenticated_user,
)
+def _user_has_existing_credentials_from_partner(user: User, partner: OAuthApplication) -> bool:
+ """True if the user has any live OAuth credential issued to this partner.
+
+ "Live" = unexpired access token or non-revoked refresh token. PersonalAPIKey has no
+ partner attribution today, so it's excluded from this check; in practice PATs are
+ minted alongside OAuth tokens at provisioning time, so the OAuth-only check matches.
+ """
+ now = timezone.now()
+ if OAuthAccessToken.objects.filter(user=user, application=partner, expires__gt=now).exists():
+ return True
+ if OAuthRefreshToken.objects.filter(user=user, application=partner, revoked__isnull=True).exists():
+ return True
+ return False
+
+
+def _caller_proved_existing_trust(partner: OAuthApplication, user: User, authenticated_user: User | None) -> bool:
+ """True only when the caller proved a prior trust relationship with this user.
+
+ This is what lets a skip-consent partner re-mint silently after the user has reviewed
+ their credentials. The proof differs by auth method:
+
+ - HMAC callers authenticate with a partner-level secret, so the partner already holding
+ a live OAuth credential for the user is sufficient proof of an existing relationship.
+ - Bearer callers present a single user-scoped access token. That token proves a
+ relationship only with its own user, so it qualifies only when it belongs to the user
+ being re-linked — otherwise any user of the partner could ride another user's live
+ credential to mint a code for that account.
+ - PKCE callers are public: the partner is identified solely by a client_id that anyone
+ can send, so the request carries no proof the caller controls the partner. The "user
+ already holds a live credential" signal proves nothing, so these never qualify.
+ """
+ if partner.provisioning_auth_method == "hmac":
+ return _user_has_existing_credentials_from_partner(user, partner)
+ if partner.provisioning_auth_method == "bearer":
+ return authenticated_user is not None and authenticated_user.id == user.id
+ return False
+
+
def _handle_existing_user(
request_id: str,
user: User,
@@ -452,8 +501,28 @@ def _handle_existing_user(
partner: OAuthApplication | None = None,
code_challenge: str = "",
code_challenge_method: str = "S256",
+ authenticated_user: User | None = None,
) -> Response:
- if partner and not partner.provisioning_skip_existing_user_consent:
+ # Pre-hijacking defense: once a user has reviewed their credentials, a partner with
+ # skip_existing_user_consent=True can only mint silently when the caller proved a prior
+ # trust relationship with this user (see _caller_proved_existing_trust). Otherwise we
+ # fall through to consent.
+ silent_blocked_post_review = (
+ partner is not None
+ and partner.provisioning_skip_existing_user_consent
+ and user.credentials_reviewed_at is not None
+ and not _caller_proved_existing_trust(partner, user, authenticated_user)
+ )
+
+ if silent_blocked_post_review:
+ assert partner is not None # implied by silent_blocked_post_review
+ _capture_provisioning_event(
+ "account_request",
+ "silent_blocked_post_review",
+ partner_id=str(partner.id),
+ )
+
+ if partner and (not partner.provisioning_skip_existing_user_consent or silent_blocked_post_review):
if not code_challenge:
return Response(
{
@@ -608,6 +677,7 @@ def _handle_new_user(
partner: OAuthApplication | None = None,
code_challenge: str = "",
code_challenge_method: str = "S256",
+ authenticated_user: User | None = None,
) -> Response:
name = data.get("name", "")
first_name = name.split(" ")[0] if name else ""
@@ -641,6 +711,7 @@ def _handle_new_user(
partner,
code_challenge,
code_challenge_method,
+ authenticated_user,
)
_capture_provisioning_event("account_request", "creation_failed", region=region)
return Response(