: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
chore(oauth): mint direct access tokens through one core helper (#110579)
Julian Bez1aa0dd4bd327
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.pyindex d698c01af7cf..696aad334c61 100644--- a/posthog/models/oauth.py+++ b/posthog/models/oauth.py@@ -1,5 +1,6 @@import enumimport uuid+from datetime import timedeltafrom typing import TYPE_CHECKING, castfrom urllib.parse import urlparse@@ -27,7 +28,13 @@ from oauth2_provider.validators import AllowedURIValidatorfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.user import User-from posthog.models.utils import UUIDT, generate_random_token, hash_key_value, mask_key_value+from posthog.models.utils import (+ UUIDT,+ generate_random_oauth_access_token,+ generate_random_token,+ hash_key_value,+ mask_key_value,+)if TYPE_CHECKING:from posthog.models import Organization, User@@ -647,6 +654,31 @@ class OAuthGrant(AbstractGrant):)+def mint_oauth_access_token(+ *,+ application: OAuthApplication,+ user: "User | None",+ scope: str,+ lifetime: timedelta,+ scoped_teams: list[int],+ sandbox_task_id: uuid.UUID | None = None,+) -> OAuthAccessToken:+ """Mint a fresh access token directly, outside the OAuth grant flow.++ The caller owns the scope and lifetime decision. Callers that also issue a refresh token+ or rotate an existing one create their rows by hand, inside their own transaction.+ """+ return OAuthAccessToken.objects.create(+ application=application,+ user=user,+ token=generate_random_oauth_access_token(None),+ expires=timezone.now() + lifetime,+ scope=scope,+ scoped_teams=scoped_teams,+ sandbox_task_id=sandbox_task_id,+ )++def find_oauth_access_token(token: str) -> OAuthAccessToken | None:"""Find an OAuth access token by its value using the token_checksum index."""from hashlib import sha256diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex 32eeafa177a5..11bcd3001f00 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -4,14 +4,13 @@ from typing import Any, Literal, TypedDict, castfrom uuid import UUIDfrom django.conf import settings-from django.utils import timezoneimport structlogfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blocked-from posthog.models import OAuthAccessToken, OAuthApplication+from posthog.models import OAuthApplication+from posthog.models.oauth import mint_oauth_access_tokenfrom posthog.models.team.team import Team-from posthog.models.utils import generate_random_oauth_access_tokenfrom posthog.scopes import (API_SCOPE_OBJECTS,INTERNAL_API_SCOPE_OBJECTS,@@ -582,22 +581,18 @@ def get_sandbox_oauth_app(application: SandboxOAuthApplication = "array") -> OAureturn get_array_app()-def _mint_oauth_access_token(+def _mint_run_access_token(user, team_id: int, *, app: OAuthApplication, scopes: list[str], sandbox_task_id: UUID | None = None) -> str:- token_value = generate_random_oauth_access_token(None)-- OAuthAccessToken.objects.create(- user=user,+ access_token = mint_oauth_access_token(application=app,- token=token_value,- expires=timezone.now() + timedelta(seconds=TOKEN_EXPIRATION_SECONDS),+ user=user,scope=" ".join(dict.fromkeys(scopes)),+ lifetime=timedelta(seconds=TOKEN_EXPIRATION_SECONDS),scoped_teams=[team_id],sandbox_task_id=sandbox_task_id,)-- return token_value+ return access_token.tokendef create_oauth_access_token_for_user(@@ -630,7 +625,7 @@ def create_oauth_access_token_for_user(if include_slack_run_scope:resolved.append(SLACK_RUN_SCOPE)app = get_sandbox_oauth_app(application)- return _mint_oauth_access_token(user, team_id, app=app, scopes=list(resolved), sandbox_task_id=sandbox_task_id)+ return _mint_run_access_token(user, team_id, app=app, scopes=list(resolved), sandbox_task_id=sandbox_task_id)def get_wizard_app() -> OAuthApplication:@@ -691,4 +686,4 @@ def create_wizard_oauth_access_token_for_user(user, team_id: int) -> str:if ceiling is None or len(ceiling) == 0:raise RuntimeError("Wizard app has no scope ceiling. Must be configured in the database.")- return _mint_oauth_access_token(user, team_id, app=app, scopes=sorted(ceiling))+ return _mint_run_access_token(user, team_id, app=app, scopes=sorted(ceiling))diff --git a/products/streamlit_apps/backend/logic/oauth.py b/products/streamlit_apps/backend/logic/oauth.pyindex e18ab691ba79..9ffc6154df05 100644--- a/products/streamlit_apps/backend/logic/oauth.py+++ b/products/streamlit_apps/backend/logic/oauth.py@@ -7,9 +7,8 @@ from django.utils import timezoneimport structlog-from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.oauth import OAuthAccessToken, OAuthApplication, mint_oauth_access_tokenfrom posthog.models.user import User-from posthog.models.utils import generate_random_oauth_access_tokenlogger = structlog.get_logger(__name__)@@ -58,15 +57,11 @@ def create_streamlit_access_token(user: User, team_id: int) -> OAuthAccessToken:Returns the ORM object so callers can read the real `expires` timestampinstead of reporting the minting TTL."""- oauth_app = get_streamlit_oauth_app()- token_value = generate_random_oauth_access_token(None)-- return OAuthAccessToken.objects.create(- application=oauth_app,- token=token_value,+ return mint_oauth_access_token(+ application=get_streamlit_oauth_app(),user=user,- expires=timezone.now() + timedelta(seconds=ACCESS_TOKEN_EXPIRY_SECONDS),scope=IFRAME_TOKEN_SCOPE,+ lifetime=timedelta(seconds=ACCESS_TOKEN_EXPIRY_SECONDS),scoped_teams=[team_id],)@@ -100,15 +95,11 @@ def create_sandbox_bridge_token(user: User | None, team_id: int) -> str:`user`, which the bridge's org-membership re-check relies on to revoke accesswhen the minting user leaves the org. A PSAK is user-less and couldn't gate that."""- oauth_app = get_streamlit_oauth_app()- token_value = generate_random_oauth_access_token(None)-- OAuthAccessToken.objects.create(- application=oauth_app,- token=token_value,+ access_token = mint_oauth_access_token(+ application=get_streamlit_oauth_app(),user=user,- expires=timezone.now() + timedelta(seconds=BRIDGE_TOKEN_EXPIRY_SECONDS),scope=BRIDGE_TOKEN_SCOPE,+ lifetime=timedelta(seconds=BRIDGE_TOKEN_EXPIRY_SECONDS),scoped_teams=[team_id],)- return token_value+ return access_token.token