: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(oauth): validate token user status on bearer auth paths (#93870)
Tom Piccirello64493e76d823
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.pyindex 32ee2719dadf..3b7bb7a28816 100644--- a/ee/api/agentic_provisioning/authentication.py+++ b/ee/api/agentic_provisioning/authentication.py@@ -205,7 +205,7 @@ class ProvisioningBearerAuthentication(BaseAuthentication):Raises :class:`ProvisioningError` (rendered in the view's envelope) on failure."""- def authenticate(self, request: Request) -> tuple[User | None, OAuthAccessToken]:+ def authenticate(self, request: Request) -> tuple[User, OAuthAccessToken]:try:access_token = resolve_bearer_access_token(request)except BearerTokenError as exc:@@ -223,7 +223,15 @@ class ProvisioningBearerAuthentication(BaseAuthentication):if not app.provisioning.can_provision_resources:raise ProvisioningError("forbidden", "Resource provisioning not enabled for this partner", status=403)- return access_token.user, access_token+ # Deactivating a user drops their login sessions but leaves OAuth tokens intact, so the+ # token has to fail closed here the way `posthog.auth._validate_token` does for the main+ # API. A token with no user cannot identify a caller at all, and the views downstream+ # read `request.user` as a User, so it fails closed too.+ user = access_token.user+ if user is None or not user.is_active:+ raise ProvisioningError("unauthorized", "Authentication failed", status=401)++ return user, access_tokendef authenticate_header(self, request: Request) -> str:return "Bearer"diff --git a/ee/api/agentic_provisioning/test/test_oauth_token.py b/ee/api/agentic_provisioning/test/test_oauth_token.pyindex 1f961e3dcc5a..7aa2d42a45a1 100644--- a/ee/api/agentic_provisioning/test/test_oauth_token.py+++ b/ee/api/agentic_provisioning/test/test_oauth_token.py@@ -295,6 +295,16 @@ class TestOAuthTokenExchange(ProvisioningTestBase):assert "revoked" in body["error_description"]assert OAuthAccessToken.objects.count() == tokens_before+ def test_refresh_rejected_when_user_deactivated(self):+ first = self._request_bearer_token().json()++ self.user.is_active = False+ self.user.save()++ res = self._refresh(first["refresh_token"])+ assert res.status_code == 400+ assert res.json()["error"] == "invalid_grant"+def test_refresh_allowed_when_token_postdates_session_revoke(self):self._stamp_session_revoke(timezone.now() - timedelta(hours=1))first = self._request_bearer_token()diff --git a/ee/api/agentic_provisioning/test/test_provisioning_auth.py b/ee/api/agentic_provisioning/test/test_provisioning_auth.pyindex adfec083db71..57579fa2f1cc 100644--- a/ee/api/agentic_provisioning/test/test_provisioning_auth.py+++ b/ee/api/agentic_provisioning/test/test_provisioning_auth.py@@ -273,6 +273,15 @@ class TestProvisioningAuthentication(ProvisioningTestBase):res = self._wizard_account_request("req_inactive_pkce", "[email protected]", challenge)assert res.status_code == 401+ def test_deactivated_user_bearer_token_rejected(self):+ token = self._get_bearer_token()++ self.user.is_active = False+ self.user.save()++ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)+ assert res.status_code == 401+# --- can_provision_resources enforcement ---def test_partner_without_can_provision_resources_rejected(self):diff --git a/ee/api/agentic_provisioning/test/test_resources.py b/ee/api/agentic_provisioning/test/test_resources.pyindex 89baaf6e4220..62e1739bd24d 100644--- a/ee/api/agentic_provisioning/test/test_resources.py+++ b/ee/api/agentic_provisioning/test/test_resources.py@@ -78,6 +78,29 @@ class TestProvisioningResources(ProvisioningTestBase):)assert res.status_code == 403+ @parameterized.expand(+ [+ ("read_access_control_revoked", "read", "access_control"),+ ("read_org_membership_removed", "read", "membership"),+ ("create_access_control_revoked", "create", "access_control"),+ ("create_org_membership_removed", "create", "membership"),+ ]+ )+ def test_resource_endpoints_rejected_after_team_access_lost(self, _name: str, endpoint: str, revocation: str):+ token = self._get_bearer_token()++ if revocation == "access_control":+ self._restrict_team_access(self.team)+ else:+ self.organization_membership.delete()++ if endpoint == "read":+ res = self._get_with_bearer(f"/api/agentic/provisioning/resources/{self.team.id}", token=token)+ else:+ res = self._post_with_bearer("/api/agentic/provisioning/resources", {}, token=token)++ assert res.status_code == 403+def test_get_resource_invalid_id_returns_400(self):token = self._get_bearer_token()res = self._get_with_bearer(diff --git a/ee/api/agentic_provisioning/views/base.py b/ee/api/agentic_provisioning/views/base.pyindex 419bfa9bd22d..bc7fe5d49898 100644--- a/ee/api/agentic_provisioning/views/base.py+++ b/ee/api/agentic_provisioning/views/base.py@@ -34,6 +34,7 @@ from ee.api.agentic_provisioning.ratelimits import ()from ee.api.agentic_provisioning.region_proxy import RegionProxyMixinfrom ee.api.agentic_provisioning.serializers import first_error_message+from ee.api.agentic_provisioning.tokens import user_can_access_teamclass ProvisioningAPIView(RegionProxyMixin, APIView):@@ -197,7 +198,17 @@ class BearerResourceAPIView(ProvisioningAPIView):region_proxy_strategy = "bearer_lookup"authentication_classes = [ProvisioningBearerAuthentication]- def parse_resource_team_id(self, resource_id: str, access_token: OAuthAccessToken) -> int:+ def _resolve_scoped_team(self, resource_id: str, access_token: OAuthAccessToken) -> tuple[int, Team | None]:+ """Resolve the resource id to its team, enforcing the token's scope and live access.++ ``scoped_teams`` is a snapshot taken when the token was minted, so it outlives the+ access it records. Re-run the check the scope was built from (see+ ``compute_partner_scoped_teams``), so an org removal or an access-control change+ applies to the next request instead of waiting for the token to be refreshed.++ Returns the team id even when the team is gone, so the caller decides whether a+ missing team is a 404 or a no-op.+ """try:team_id = int(resource_id)except (ValueError, TypeError):@@ -207,14 +218,31 @@ class BearerResourceAPIView(ProvisioningAPIView):raise ProvisioningError("forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403)- return team_id- def get_team(self, team_id: int, resource_id: str) -> Team:- try:- return Team.objects.get(id=team_id)- except Team.DoesNotExist:- raise ProvisioningError("not_found", "Resource not found", resource_id=resource_id, status=404)+ team = Team.objects.select_related("organization").filter(id=team_id).first()+ # A team that no longer exists has no access left to re-check.+ if team is not None:+ self.assert_team_access(team, access_token, resource_id=resource_id)+ return team_id, team++ def assert_team_access(self, team: Team, access_token: OAuthAccessToken, *, resource_id: str = "") -> None:+ """Re-check that the token's user can still reach the team.++ Every bearer endpoint that acts on a team calls this, whether it found the team through+ the request's resource id or through the token's own scope. The scope alone does not+ answer the question: it records the access the user had when the token was minted.+ """+ if access_token.user is None or not user_can_access_team(access_token.user, team):+ raise ProvisioningError(+ "forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403+ )++ def parse_resource_team_id(self, resource_id: str, access_token: OAuthAccessToken) -> int:+ return self._resolve_scoped_team(resource_id, access_token)[0]def get_scoped_team(self, resource_id: str, access_token: OAuthAccessToken) -> Team:"""Resolve the resource id to its team, enforcing the token's team scope."""- return self.get_team(self.parse_resource_team_id(resource_id, access_token), resource_id)+ _, team = self._resolve_scoped_team(resource_id, access_token)+ if team is None:+ raise ProvisioningError("not_found", "Resource not found", resource_id=resource_id, status=404)+ return teamdiff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.pyindex 1d5f277f9bde..55230801a97b 100644--- a/ee/api/agentic_provisioning/views/oauth_token.py+++ b/ee/api/agentic_provisioning/views/oauth_token.py@@ -330,6 +330,15 @@ class OAuthTokenView(ProvisioningAPIView):user = old_refresh.userold_scoped_teams = old_refresh.scoped_teams or []+ # 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 a+ # deactivated user still passes it. Without this gate the partner rotates into a+ # fresh token pair for as long as it keeps refreshing. Checked before any token+ # row is mutated, like the other fail-closed gates here.+ if not user.is_active:+ 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 idsdiff --git a/ee/api/agentic_provisioning/views/resources.py b/ee/api/agentic_provisioning/views/resources.pyindex c8cf7619956c..7663e83c3dcb 100644--- a/ee/api/agentic_provisioning/views/resources.py+++ b/ee/api/agentic_provisioning/views/resources.py@@ -114,6 +114,9 @@ class ResourcesCreateView(BearerResourceAPIView):"resource_created", "error", partner=app, error_code="team_not_found", team_id=team_id)raise ProvisioningError("team_not_found", "Team not found", resource_id=str(team_id), status=404)+ # The project_id branch above re-checks access inside resolve_or_create_project_team;+ # this branch takes the team straight off the token's scope, so it checks here.+ self.assert_team_access(team, access_token, resource_id=str(team_id))capture_provisioning_event("resource_created",diff --git a/ee/partners/stripe/api/provisioning/authentication.py b/ee/partners/stripe/api/provisioning/authentication.pyindex 137ca43cc7f7..d7f636fb294a 100644--- a/ee/partners/stripe/api/provisioning/authentication.py+++ b/ee/partners/stripe/api/provisioning/authentication.py@@ -31,7 +31,7 @@ class StripeBearerAuthentication(BaseAuthentication):Raises :class:`SpecError` (rendered in the view's envelope) on failure."""- def authenticate(self, request: Request) -> tuple[User | None, OAuthAccessToken]:+ def authenticate(self, request: Request) -> tuple[User, OAuthAccessToken]:auth_header = request.headers.get("authorization", "")if not auth_header.startswith("Bearer "):raise SpecError("unauthorized", "Missing bearer token", status=401)@@ -55,7 +55,15 @@ class StripeBearerAuthentication(BaseAuthentication):if app is None or not is_stripe_oauth_app(app):raise SpecError("unauthorized", "Authentication failed", status=401)- return access_token.user, access_token+ # Deactivating a user drops their login sessions but leaves OAuth tokens intact, so the+ # token has to fail closed here the way `posthog.auth._validate_token` does for the main+ # API. A token with no user cannot identify a caller at all, and the views downstream+ # read `request.user` as a User, so it fails closed too.+ user = access_token.user+ if user is None or not user.is_active:+ raise SpecError("unauthorized", "Authentication failed", status=401)++ return user, access_tokendef authenticate_header(self, request: Request) -> str:return "Bearer"diff --git a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py b/ee/partners/stripe/api/provisioning/test/test_oauth_token.pyindex 51760dca8dea..6190dd92ac98 100644--- a/ee/partners/stripe/api/provisioning/test/test_oauth_token.py+++ b/ee/partners/stripe/api/provisioning/test/test_oauth_token.py@@ -164,6 +164,16 @@ class TestOAuthToken(StripeProvisioningTestBase):"error_description": "Authorization code was not issued for the Stripe Projects app",}+ def test_refresh_rejected_when_user_deactivated(self):+ first = self._request_bearer_token().json()++ self.user.is_active = False+ self.user.save()++ res = self._post_token({"grant_type": "refresh_token", "refresh_token": first["refresh_token"]})+ assert res.status_code == 400+ assert res.json()["error"] == "invalid_grant"+def test_refresh_token_from_non_stripe_app_not_rotatable(self):other_app = self._create_other_partner_app()refresh_value = generate_random_oauth_refresh_token(None)diff --git a/ee/partners/stripe/api/provisioning/test/test_resources.py b/ee/partners/stripe/api/provisioning/test/test_resources.pyindex 6b008c730380..dbf81bfeed54 100644--- a/ee/partners/stripe/api/provisioning/test/test_resources.py+++ b/ee/partners/stripe/api/provisioning/test/test_resources.py@@ -6,11 +6,15 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken+from posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.utils import generate_random_oauth_access_token+from products.access_control.backend.models.access_control import AccessControl+from ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBaseRESOURCES_URL = f"{BASE_PATH}/provisioning/resources"@@ -48,6 +52,49 @@ class TestResources(StripeProvisioningTestBase):# A project_id provisions a dedicated team, distinct from the consent team.assert first.json()["id"] != str(self.team.id)+ def test_deactivated_user_bearer_token_rejected(self):+ token = self._get_bearer_token()++ self.user.is_active = False+ self.user.save()++ res = self._post_signed_with_bearer(RESOURCES_URL, data={}, token=token)+ assert res.status_code == 401++ @parameterized.expand(+ [+ ("read_access_control_revoked", "read", "access_control"),+ ("read_org_membership_removed", "read", "membership"),+ ("create_access_control_revoked", "create", "access_control"),+ ("create_org_membership_removed", "create", "membership"),+ ]+ )+ def test_resource_endpoints_rejected_after_team_access_lost(self, _name: str, endpoint: str, revocation: str):+ token = self._get_bearer_token()++ if revocation == "access_control":+ 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),+ )+ else:+ self.organization_membership.delete()++ if endpoint == "read":+ res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)+ else:+ res = self._post_signed_with_bearer(RESOURCES_URL, data={}, token=token)++ assert res.status_code == 403+def test_unknown_service_rejected(self):token = self._get_bearer_token()res = self._post_signed_with_bearer(RESOURCES_URL, data={"service_id": "nonsense"}, token=token)diff --git a/ee/partners/stripe/api/provisioning/views.py b/ee/partners/stripe/api/provisioning/views.pyindex 0865fce94154..df2eed4e206a 100644--- a/ee/partners/stripe/api/provisioning/views.py+++ b/ee/partners/stripe/api/provisioning/views.py@@ -71,6 +71,7 @@ from ee.partners.stripe.api.provisioning.core import (remove_team_from_token_scopes,resolve_or_create_project_team,set_provisioning_service_id,+ user_can_access_team,)from ee.partners.stripe.api.provisioning.exceptions import Envelope, PreRenderedError, SpecError, render_spec_errorfrom ee.partners.stripe.api.provisioning.region_proxy import RegionProxyMixin@@ -485,6 +486,16 @@ class OAuthTokenView(StripeProvisioningAPIView):# 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++ # 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 a+ # deactivated user still passes it. Without this gate the partner rotates into a+ # fresh token pair for as long as it keeps refreshing. Checked before any token+ # row is mutated, like the other fail-closed gates here.+ if not user.is_active:+ capture_provisioning_event("token_exchange", "user_inactive", grant_type="refresh_token")+ raise SpecError("invalid_grant", "User is not active; re-authorize.")+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@@ -575,15 +586,29 @@ class StripeResourceAPIView(SignatureCheckedMixin, StripeProvisioningAPIView):except (ValueError, TypeError):raise SpecError("invalid_resource_id", "Invalid resource ID", resource_id=resource_id)- # TODO: latent bug - this checks only the token's issuance-time scoped_teams,- # not the user's current team-level access. If the user is later removed from- # the team/org, the (long-lived) bearer can still read/rotate/update/remove- # the resource until it is refreshed (refresh re-derives scope via- # compute_partner_scoped_teams). Revalidate live access here to close it.if team_id not in (access_token.scoped_teams or []):raise SpecError("forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403)++ # A team that no longer exists has no access left to re-check; `get_team` decides what+ # a missing team means for each endpoint.+ team = Team.objects.select_related("organization").filter(id=team_id).first()+ if team is not None:+ self.assert_team_access(team, access_token, resource_id=resource_id)return team_id+ def assert_team_access(self, team: Team, access_token: OAuthAccessToken, *, resource_id: str = "") -> None:+ """Re-check that the token's user can still reach the team.++ Every bearer endpoint that acts on a team calls this, whether it found the team through+ the request's resource id or through the token's own scope. `scoped_teams` is a snapshot+ taken when the token was minted, and tokens here last a year, so it outlives the access+ it records by a long way. Re-running the check the scope was built from (see+ `compute_partner_scoped_teams`) makes an org removal or an access-control change apply+ to the next request instead of waiting for a refresh.+ """+ if access_token.user is None or not user_can_access_team(access_token.user, team):+ raise SpecError("forbidden", "Resource not accessible with this token", resource_id=resource_id, status=403)+def get_team(self, team_id: int, resource_id: str) -> Team:try:return Team.objects.get(id=team_id)@@ -646,6 +671,9 @@ class ResourcesCreateView(StripeResourceAPIView):"resource_created", "error", partner=app, error_code="team_not_found", team_id=team_id)raise SpecError("team_not_found", "Team not found", resource_id=str(team_id), status=404)+ # The project_id branch above re-checks access inside resolve_or_create_project_team;+ # this branch takes the team straight off the token's scope, so it checks here.+ self.assert_team_access(team, access_token, resource_id=str(team_id))# TODO: latent bug - this runs on every call, so a repeated create for# an existing team overwrites its service_id (not idempotent), and thediff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 9fab40b24df6..4a4a54dc3411 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -3975,6 +3975,41 @@ class TestOAuthAPI(APIBaseTest):data = response.json()self.assertFalse(data["active"])+ @parameterized.expand(+ [+ ("access_token_deactivated_user", "access_token", "deactivated", False),+ ("refresh_token_deactivated_user", "refresh_token", "deactivated", False),+ # Client-credentials grants have no resource owner, so a userless access+ # token must stay introspectable. OAuthRefreshToken.user is not nullable.+ ("access_token_without_user", "access_token", "userless", True),+ ]+ )+ def test_introspection_reflects_token_user_status(+ self, _name: str, token_type: str, user_state: str, expected_active: bool+ ):+ access_token, refresh_token = self._create_access_and_refresh_tokens()+ token = access_token if token_type == "access_token" else refresh_token++ if user_state == "deactivated":+ self.user.is_active = False+ self.user.save()+ else:+ access_token.user = None+ access_token.save()++ response = self.post(+ "/oauth/introspect/",+ {"token": token.token},+ headers={+ "Authorization": self.get_basic_auth_header(+ "test_confidential_client_id", "test_confidential_client_secret"+ )+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["active"], expected_active)+def test_self_introspection_with_revoked_token_fails(self):"""A revoked (deleted) token cannot self-introspect."""access_token, _ = self._create_access_and_refresh_tokens(scopes="openid")diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 110dc327a203..de439a50ca99 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -2124,6 +2124,12 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):# RFC 7662 Section 2.2: expired tokens MUST return {"active": false}if not access_token.is_valid():return JsonResponse({"active": False}, status=200)+ # Deactivating a user drops their login sessions but leaves their OAuth tokens+ # intact, and callers that authorize on this response rather than merely describe a+ # token (the Streamlit proxy is one) would keep letting them in until it expires.+ # `user` is null for a client-credentials grant, which has no resource owner.+ if access_token.user is not None and not access_token.user.is_active:+ return JsonResponse({"active": False}, status=200)data = {"active": True,"token_type": "access_token",@@ -2147,6 +2153,8 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):if refresh_token:if credential_client_id and getattr(refresh_token.application, "client_id", None) != credential_client_id:return JsonResponse({"active": False}, status=200)+ if not refresh_token.user.is_active:+ return JsonResponse({"active": False}, status=200)# Refresh tokens lack scope and exp fields on AbstractRefreshToken,# so we only return the fields that are availabledata = {