: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
import hashlib
from abc import ABC, abstractmethod
from datetime import UTC, datetime
import asyncpg
from llm_gateway.auth.models import AuthenticatedUser, has_required_scope
from llm_gateway.config import get_settings
from llm_gateway.db.postgres import acquire_connection
class Authenticator(ABC):
"""Abstract base class for token authenticators - pure DB lookup, no side effects."""
@property
@abstractmethod
def auth_type(self) -> str:
"""Identifier for this auth type (used in metrics)."""
...
@property
@abstractmethod
def cache_ttl(self) -> int:
"""How long successful auth results should be cached (seconds)."""
...
@abstractmethod
def matches(self, token: str) -> bool:
"""Check if this authenticator handles this token format."""
...
@abstractmethod
def hash_token(self, token: str) -> str:
"""Hash the token for DB lookup and cache key."""
...
@abstractmethod
async def authenticate(self, token_hash: str, pool: asyncpg.Pool) -> AuthenticatedUser | None:
"""Perform DB lookup. Returns None if invalid."""
...
class PersonalApiKeyAuthenticator(Authenticator):
"""Authenticator for personal API keys (phx_ prefix)."""
@property
def auth_type(self) -> str:
return "personal_api_key"
@property
def cache_ttl(self) -> int:
return get_settings().auth_cache_ttl
def matches(self, token: str) -> bool:
return token.startswith("phx_")
def hash_token(self, token: str) -> str:
hashed = hashlib.sha256(token.encode()).hexdigest()
return f"sha256${hashed}"
async def authenticate(self, token_hash: str, pool: asyncpg.Pool) -> AuthenticatedUser | None:
async with acquire_connection(pool) as conn:
row = await conn.fetchrow(
"""
SELECT pak.id, pak.user_id, pak.scopes, pak.expires_at,
u.current_team_id, u.distinct_id, u.is_staff
FROM posthog_personalapikey pak
JOIN posthog_user u ON pak.user_id = u.id
WHERE pak.secure_value = $1 AND u.is_active = true
-- Legacy accounts predate the column and store NULL; they must pass like true.
AND u.is_email_verified IS DISTINCT FROM false
""",
token_hash,
)
if not row:
return None
# Same boundary as Django's PersonalAPIKey.is_expired: the expiry instant itself is expired.
expires_at: datetime | None = row.get("expires_at")
if expires_at and expires_at <= datetime.now(UTC):
return None
scopes = row["scopes"] or []
if not has_required_scope(scopes):
return None
return AuthenticatedUser(
user_id=row["user_id"],
team_id=row["current_team_id"],
auth_method=self.auth_type,
distinct_id=row["distinct_id"],
scopes=scopes,
# AuthCache caps the entry's TTL at token_expires_at, so a cached hit cannot outlive the key.
token_expires_at=expires_at,
is_staff=row["is_staff"],
)
class OAuthAccessTokenAuthenticator(Authenticator):
"""Authenticator for OAuth access tokens (pha_ prefix)."""
@property
def auth_type(self) -> str:
return "oauth_access_token"
@property
def cache_ttl(self) -> int:
return get_settings().auth_cache_ttl_oauth
def matches(self, token: str) -> bool:
return token.startswith("pha_")
def hash_token(self, token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
async def authenticate(self, token_hash: str, pool: asyncpg.Pool) -> AuthenticatedUser | None:
async with acquire_connection(pool) as conn:
row = await conn.fetchrow(
"""
SELECT oat.id, oat.user_id, oat.scope, oat.expires,
oat.application_id, oat.scoped_teams, oat.scoped_organizations,
oat.sandbox_task_id, oat.impersonated_by_id,
u.current_team_id, u.distinct_id, u.is_staff
FROM posthog_oauthaccesstoken oat
JOIN posthog_user u ON oat.user_id = u.id
WHERE oat.token_checksum = $1 AND u.is_active = true
AND u.is_email_verified IS DISTINCT FROM false
""",
token_hash,
)
if not row:
return None
expires: datetime | None = row["expires"]
if expires and expires < datetime.now(UTC):
return None
if not row["application_id"]:
return None
# Staff impersonation mints tokens as the customer. Gateway spend must not go to that user.
if row.get("impersonated_by_id") is not None:
return None
scopes = row["scope"].split() if row["scope"] else []
if not has_required_scope(scopes, allow_wildcard=True):
return None
return AuthenticatedUser(
user_id=row["user_id"],
team_id=row["current_team_id"],
auth_method=self.auth_type,
distinct_id=row["distinct_id"],
scopes=scopes,
token_expires_at=expires,
application_id=str(row["application_id"]),
is_staff=row["is_staff"],
scoped_teams=row.get("scoped_teams"),
scoped_organizations=row.get("scoped_organizations"),
sandbox_task_id=str(row["sandbox_task_id"]) if row.get("sandbox_task_id") else None,
)