: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
from __future__ import annotations
import secrets
from datetime import timedelta
from django.utils import timezone
import structlog
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, mint_oauth_access_token
from posthog.models.user import User
logger = structlog.get_logger(__name__)
STREAMLIT_OAUTH_APP_NAME = "PostHog Streamlit Apps"
STREAMLIT_OAUTH_CLIENT_ID = "posthog-streamlit-apps-first-party"
ACCESS_TOKEN_EXPIRY_SECONDS = 60 * 60 # 1 hour
BRIDGE_TOKEN_EXPIRY_SECONDS = 60 * 20 # sandbox TTL + buffer
# streamlit:iframe and streamlit:bridge are deliberately internal first-party
# discriminators, not registered API scopes: they never reach APIScopePermission
# or a user-facing scope picker. They exist so the proxy and the bridge can refuse
# tokens of the opposite type even if one leaks between contexts.
IFRAME_TOKEN_SCOPE = "streamlit:iframe"
BRIDGE_TOKEN_SCOPE = "query:read streamlit:bridge"
def get_streamlit_oauth_app() -> OAuthApplication:
"""Return the Streamlit OAuth application, creating it if the seed row is missing.
Migration `0002_seed_streamlit_oauth_app` seeds the row, but
`TransactionTestCase`-style truncation in tests can wipe it without
re-running data migrations. Self-healing via get_or_create keeps the
helper robust without depending on a particular test-DB lifecycle.
The client_secret is regenerated on insert because the OAuth client
flow isn't actually used (is_first_party=True skips consent), so the
secret has no consumers to break.
"""
app, _ = OAuthApplication.objects.get_or_create(
client_id=STREAMLIT_OAUTH_CLIENT_ID,
defaults={
"name": STREAMLIT_OAUTH_APP_NAME,
"client_secret": secrets.token_urlsafe(48),
"client_type": "confidential",
"authorization_grant_type": "authorization-code",
"redirect_uris": "https://localhost",
"algorithm": "RS256",
"is_first_party": True,
},
)
return app
def create_streamlit_access_token(user: User, team_id: int) -> OAuthAccessToken:
"""Mint an iframe OAuth access token scoped to the given team.
Returns the ORM object so callers can read the real `expires` timestamp
instead of reporting the minting TTL.
"""
return mint_oauth_access_token(
application=get_streamlit_oauth_app(),
user=user,
scope=IFRAME_TOKEN_SCOPE,
lifetime=timedelta(seconds=ACCESS_TOKEN_EXPIRY_SECONDS),
scoped_teams=[team_id],
)
def find_reusable_streamlit_access_token(
user: User, team_id: int, min_remaining_seconds: int = 300
) -> OAuthAccessToken | None:
"""Return a non-near-expiry iframe token for (user, team), or None.
Filters on IFRAME_TOKEN_SCOPE so bridge tokens can't be reused here.
"""
oauth_app = get_streamlit_oauth_app()
cutoff = timezone.now() + timedelta(seconds=min_remaining_seconds)
return (
OAuthAccessToken.objects.filter(
application=oauth_app,
user=user,
scoped_teams=[team_id],
scope=IFRAME_TOKEN_SCOPE,
expires__gt=cutoff,
)
.order_by("-expires")
.first()
)
def create_sandbox_bridge_token(user: User | None, team_id: int) -> str:
"""Mint a long-TTL OAuth token for the sandbox→PostHog HogQL bridge hop.
OAuth rather than a project secret API key is deliberate: the token carries a
`user`, which the bridge's org-membership re-check relies on to revoke access
when the minting user leaves the org. A PSAK is user-less and couldn't gate that.
"""
access_token = mint_oauth_access_token(
application=get_streamlit_oauth_app(),
user=user,
scope=BRIDGE_TOKEN_SCOPE,
lifetime=timedelta(seconds=BRIDGE_TOKEN_EXPIRY_SECONDS),
scoped_teams=[team_id],
)
return access_token.token