: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(auth): stop desktop oauth attribution recursing into authentication (#101845)
Paul D'Ambra3cfcde92745c
diff --git a/posthog/auth.py b/posthog/auth.pyindex fe98ac963a42..89f39514aaf5 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -19,6 +19,7 @@ from django.utils import timezoneimport jwtimport structlog+import posthoganalyticsfrom opentelemetry import tracefrom prometheus_client import Counterfrom rest_framework import authentication@@ -943,7 +944,13 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):except AuthenticationFailed:raise- except Exception:+ except Exception as e:+ # _validate_token converts its own failures, so anything reaching here is a+ # bug in the authentication path, not a bad token. Record it before it is+ # reported to the caller as one.+ with posthoganalytics.new_context():+ posthoganalytics.set_capture_exception_code_variables_context(False)+ capture_exception(e)raise AuthenticationFailed(detail="Invalid access token.")def _authenticate_access_token(diff --git a/posthog/oauth_provenance.py b/posthog/oauth_provenance.pyindex 2e0f979ea899..ce857f1214cb 100644--- a/posthog/oauth_provenance.py+++ b/posthog/oauth_provenance.py@@ -47,7 +47,11 @@ def get_oauth_access_token(request) -> object | None:def get_oauth_client_id(request) -> str | None:- application = getattr(get_oauth_access_token(request), "application", None)+ return _get_client_id(get_oauth_access_token(request))+++def _get_client_id(access_token: object | None) -> str | None:+ application = getattr(access_token, "application", None)return getattr(application, "client_id", None)@@ -58,7 +62,11 @@ def is_first_party_oauth_client(request) -> bool:or `posthog_ai`. Requiring one of our own applications is what makes that headertrustworthy enough to attribute a surface from."""- return get_oauth_client_id(request) in POSTHOG_DESKTOP_OAUTH_CLIENT_IDS+ return _is_first_party_oauth_token(get_oauth_access_token(request))+++def _is_first_party_oauth_token(access_token: object | None) -> bool:+ return _get_client_id(access_token) in POSTHOG_DESKTOP_OAUTH_CLIENT_IDSdef is_interactive_desktop_grant(request, access_token: object | None = None) -> bool:@@ -68,10 +76,14 @@ def is_interactive_desktop_grant(request, access_token: object | None = None) ->same OAuth application, so three things have to line up: that application, the absence ofthe server-minted `internal_run:read` marker, and refresh-token lineage proving a consentflow happened. Sandbox tokens fail the second check before the third does any query.++ An authenticator must pass `access_token`. Until DRF finishes authenticating,+ `request.successful_authenticator` re-runs `Request._authenticate()`, so reading it from+ inside an authenticator re-enters authentication and recurses until `RecursionError`."""if access_token is None:access_token = get_oauth_access_token(request)- if access_token is None or not is_first_party_oauth_client(request):+ if access_token is None or not _is_first_party_oauth_token(access_token):return Falsescopes = set((getattr(access_token, "scope", "") or "").split())if INTERNAL_RUN_SCOPE in scopes:diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex bbda8bef5cd6..1604b9b95772 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom parameterized import parameterized+from posthog.auth import OAuthAccessTokenAuthenticationfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity@@ -703,13 +704,24 @@ class TestAgentAttributionOnApiWrites(APIBaseTest):scoped_organizations=[],)- response = self.client.post(- f"/api/projects/{self.team.id}/dashboards/",- {"name": "Weekly signups"},- HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",- )+ with (+ patch.object(+ OAuthAccessTokenAuthentication,+ "_validate_token",+ autospec=True,+ side_effect=OAuthAccessTokenAuthentication._validate_token,+ ) as validate_token,+ patch("posthog.auth.capture_exception") as capture_exception,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/",+ {"name": "Weekly signups"},+ HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",+ )self.assertEqual(response.status_code, 201, response.content)+ self.assertEqual(validate_token.call_count, 1)+ capture_exception.assert_not_called()log = ActivityLog.objects.filter(scope="Dashboard").latest("id")assert log.detail is not Noneself.assertEqual(