Skip to content

: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.

4.2 KB
Raw Blame
"""Bearer authentication for the Stripe provisioning resource endpoints.

The only accepted identity is the Stripe orchestrator: tokens issued to the
Stripe Projects OAuth app (resolved by
``settings.STRIPE_POSTHOG_OAUTH_CLIENT_ID``). Tokens bound to any other
application are rejected outright.

Identity is most of the check, not all of it: ``DeepLinksView`` additionally
requires ``can_issue_deep_links`` on the application, because a deep link mints
a full web session. Other capability flags are not consulted here.
"""

from __future__ import annotations

from django.utils import timezone

from rest_framework.authentication import BaseAuthentication
from rest_framework.request import Request

from posthog.auth import account_refused
from posthog.models.activity_logging.utils import ActivityCredentialMixin
from posthog.models.oauth import OAuthAccessToken, find_oauth_access_token
from posthog.models.user import User

from products.security.backend.facade.api import REFUSAL_CODE as SECURITY_REFUSAL_CODE

from ee.partners.stripe.api.provisioning.core import is_stripe_oauth_app
from ee.partners.stripe.api.provisioning.exceptions import SpecError

# The response reaches Stripe, not a PostHog page, so the message names PostHog. The code is
# what lets PostHog support trace the refusal to an access rule.
ACCOUNT_BLOCKED_MESSAGE = (
    "PostHog can't give access to this account. If you think this is a mistake, contact PostHog support "
    f"and quote the code {SECURITY_REFUSAL_CODE}."
)


class StripeBearerAuthentication(ActivityCredentialMixin, BaseAuthentication):
    """Authenticate the Stripe orchestrator via an OAuth bearer token.

    Returns ``(user, access_token)`` so views read the token off ``request.auth``.
    Raises :class:`SpecError` (rendered in the view's envelope) on failure.
    """

    activity_credential_type = "oauth"

    def authenticate(self, request: Request) -> tuple[User, OAuthAccessToken]:
        auth_header = request.headers.get("authorization", "")
        if not auth_header.startswith("Bearer "):
            raise SpecError("unauthorized", "Missing bearer token", status=401)

        token_value = auth_header[len("Bearer ") :].strip()
        if not token_value:
            raise SpecError("unauthorized", "Missing bearer token", status=401)

        access_token = find_oauth_access_token(token_value)
        if access_token is None:
            raise SpecError("unauthorized", "Invalid access token", status=401)

        if access_token.expires and access_token.expires < timezone.now():
            raise SpecError("unauthorized", "Access token expired", status=401)

        # This namespace serves exactly one caller. A token minted for any other
        # application - including other provisioning partners - must fail here;
        # partner-generic traffic belongs to the legacy provisioning surface.
        # Being the Stripe app is the entire authorization check.
        app = access_token.application
        if app is None or not is_stripe_oauth_app(app):
            raise SpecError("unauthorized", "Authentication failed", status=401)

        # Deactivating a user drops their login sessions but leaves OAuth tokens intact, so the
        # token has to fail closed here the way `posthog.auth._validate_token` does for the main
        # API. A token with no user cannot identify a caller at all, and the views downstream
        # read `request.user` as a User, so it fails closed too.
        user = access_token.user
        if user is None or not user.is_active:
            raise SpecError("unauthorized", "Authentication failed", status=401)
        if account_refused(
            request,
            user,
            call_site="stripe_provisioning_token",
            impersonated=access_token.impersonated_by_id is not None,
        ):
            # Stripe's provisioning spec defines the error codes, so the refusal uses its `forbidden`.
            raise SpecError("forbidden", ACCOUNT_BLOCKED_MESSAGE, status=403)

        self.record_activity_actor(
            user, str(access_token.application_id), impersonated_by_id=access_token.impersonated_by_id
        )
        return user, access_token

    def authenticate_header(self, request: Request) -> str:
        return "Bearer"