: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(oauth): extend first-party access token TTL to 7 days (#66919)
Charles Vien7eb62559c9ec
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 6305a9d5e984..08a8dace507d 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -3840,6 +3840,86 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(data["scoped_organizations"], [str(self.organization.id)])self.assertEqual(data["scoped_teams"], [self.team.pk])+ @freeze_time("2025-01-01 00:00:00")+ def test_first_party_app_gets_extended_token_expiry(self):+ app = self._create_first_party_app(slug="first-party-ttl")+ grant = OAuthGrant.objects.create(+ application=app,+ user=self.user,+ code="first_party_ttl_code",+ code_challenge=self.code_challenge,+ code_challenge_method="S256",+ redirect_uri="https://example.com/callback",+ expires=timezone.now() + timedelta(minutes=5),+ scoped_organizations=[str(self.organization.id)],+ scoped_teams=[],+ )++ response = self.post(+ "/oauth/token/",+ {+ **self.base_token_body,+ "client_id": app.client_id,+ "client_secret": "first_party_first-party-ttl_client_secret",+ "code": grant.code,+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["expires_in"], 60 * 60 * 24 * 7)++ access_token = OAuthAccessToken.objects.get(token=data["access_token"])+ expected_expiry = timezone.now() + timedelta(days=7)+ self.assertLess(abs((access_token.expires - expected_expiry).total_seconds()), 60)++ @freeze_time("2025-01-01 00:00:00")+ def test_first_party_app_refreshed_token_keeps_extended_expiry_and_rotates(self):+ app = self._create_first_party_app(slug="first-party-refresh-ttl")+ client_secret = "first_party_first-party-refresh-ttl_client_secret"+ grant = OAuthGrant.objects.create(+ application=app,+ user=self.user,+ code="first_party_refresh_ttl_code",+ code_challenge=self.code_challenge,+ code_challenge_method="S256",+ redirect_uri="https://example.com/callback",+ expires=timezone.now() + timedelta(minutes=5),+ scoped_organizations=[str(self.organization.id)],+ scoped_teams=[],+ )++ token_response = self.post(+ "/oauth/token/",+ {+ **self.base_token_body,+ "client_id": app.client_id,+ "client_secret": client_secret,+ "code": grant.code,+ },+ )+ self.assertEqual(token_response.status_code, status.HTTP_200_OK)+ original = token_response.json()++ refresh_response = self.post(+ "/oauth/token/",+ {+ "grant_type": "refresh_token",+ "refresh_token": original["refresh_token"],+ "client_id": app.client_id,+ "client_secret": client_secret,+ },+ )++ self.assertEqual(refresh_response.status_code, status.HTTP_200_OK)+ refreshed = refresh_response.json()+ self.assertNotEqual(refreshed["refresh_token"], original["refresh_token"])+ self.assertEqual(refreshed["expires_in"], 60 * 60 * 24 * 7)++ refreshed_access_token = OAuthAccessToken.objects.get(token=refreshed["access_token"])+ expected_expiry = timezone.now() + timedelta(days=7)+ self.assertLess(abs((refreshed_access_token.expires - expected_expiry).total_seconds()), 60)+class TestLocalhostLoopbackRedirectUri(APIBaseTest):"""diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 28d1e88fae1b..ca9604c9d8e3 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -69,6 +69,14 @@ from posthog.views import login_requiredlogger = structlog.get_logger(__name__)+# Extended access-token TTL for clients that rarely re-authorize: dynamically+# registered (DCR/CIMD) clients that don't reliably refresh, and first-party+# PostHog apps. Safe to extend because these tokens stay opaque and DB-backed:+# every request revalidates the token against the DB, so revoking an app's+# sessions deletes its token rows and takes effect immediately regardless of TTL.+EXTENDED_ACCESS_TOKEN_EXPIRE_SECONDS = 60 * 60 * 24 * 7 # 7 days++# Clients for which we must NOT issue refresh tokens. The token response will omit# "refresh_token" and no OAuthRefreshToken row will be created. Entries are matched# against the app's cimd_metadata_url for CIMD clients, and against client_id otherwise.@@ -282,6 +290,12 @@ class OAuthValidator(OAuth2Validator):return getattr(request.client, "is_dcr_client", False) or getattr(request.client, "is_cimd_client", False)return False+ def _is_first_party_client(self, request) -> bool:+ """Check if the client is a first-party PostHog application."""+ if hasattr(request, "client") and request.client:+ return bool(getattr(request.client, "is_first_party", False))+ return False+def _should_skip_refresh_token(self, request) -> bool:# No refresh tokens for impersonation-minted tokens.if self._get_impersonator_id(request) is not None:@@ -496,14 +510,17 @@ class OAuthValidator(OAuth2Validator):def _get_token_expires_in(self, request) -> int:"""Returns access token expiry in seconds.- Dynamically registered (DCR/CIMD) clients get extended TTL since they- don't reliably refresh. Impersonation-minted tokens are capped to the- impersonation idle timeout so they can't outlive the admin's session.++ Dynamically registered (DCR/CIMD) clients get an extended TTL since they+ don't reliably refresh; first-party PostHog apps get the same extended TTL.+ Impersonation-minted tokens are capped to the impersonation idle timeout so+ they can't outlive the admin's session. That check comes first so an+ impersonated first-party app can't inherit the longer window."""if self._get_impersonator_id(request) is not None:return settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS- if self._is_dynamic_client(request):- return 60 * 60 * 24 * 7 # 7 days+ if self._is_dynamic_client(request) or self._is_first_party_client(request):+ return EXTENDED_ACCESS_TOKEN_EXPIRE_SECONDSreturn oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDSdef save_bearer_token(self, token, request, *args, **kwargs):@@ -525,7 +542,8 @@ class OAuthValidator(OAuth2Validator):logger.info("oauth_save_bearer_token",client_id_prefix=str(client_id)[:8] if client_id else "unknown",- is_dcr_client=expires_in != oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS,+ is_dynamic_client=self._is_dynamic_client(request),+ is_first_party=self._is_first_party_client(request),expires_in=expires_in,refresh_token_suppressed=skip_refresh,grant_type=getattr(request, "grant_type", "unknown"),diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.pyindex dbc2aa956a38..bfbf5490721e 100644--- a/posthog/test/test_oauth_impersonation.py+++ b/posthog/test/test_oauth_impersonation.py@@ -109,14 +109,22 @@ class TestImpersonationOAuthTokenIssuance(APIBaseTest):`/oauth/authorize` for both read-only and read-write impersonation — so thistest implicitly covers both modes."""- def test_code_exchange_caps_expiry_and_suppresses_refresh_for_impersonation_grants(self) -> None:+ @parameterized.expand(+ [+ ("third_party", False),+ ("first_party", True),+ ]+ )+ def test_code_exchange_caps_expiry_and_suppresses_refresh_for_impersonation_grants(+ self, _name: str, is_first_party: bool+ ) -> None:admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")admin.is_staff = Trueadmin.save()app = OAuthApplication.objects.create(name="App",- client_id="impersonation-test-client",+ client_id=f"impersonation-test-client-{_name}",client_secret="impersonation-test-secret",client_type=OAuthApplication.CLIENT_CONFIDENTIAL,authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,@@ -124,6 +132,7 @@ class TestImpersonationOAuthTokenIssuance(APIBaseTest):user=self.user,hash_client_secret=True,algorithm="RS256",+ is_first_party=is_first_party,)# PKCE bits — `S256` over a fixed verifier. The validator only checks the