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.

12.1 KB
Raw Blame
import uuid
from collections.abc import Iterable
from typing import NamedTuple
from urllib.parse import urlparse

import structlog

from posthog.hogql.errors import TableAccessDeniedError

from posthog.email import EmailMessage
from posthog.exceptions_capture import capture_exception
from posthog.models import User
from posthog.query_creator_access import CreatorLeftOrganizationError

from products.access_control.backend.facade.contracts import UserNotOrganizationMemberError
from products.access_control.backend.facade.user_access_control import UserAccessControlError
from products.notifications.backend.facade.api import (
    NotificationData,
    NotificationType,
    Priority,
    TargetType,
    create_notification,
)
from products.notifications.backend.facade.enums import NotificationOnlyResourceType
from products.subscriptions.backend.logic import SUPPORTED_TARGET_TYPES
from products.subscriptions.backend.models.subscription import Subscription


class DisableReason(NamedTuple):
    # Stable identity used for analytics (`error_type`) and activity comparisons.
    key: str
    # Shown in the disabled-subscription email body and the activity's recipient_results.
    description: str
    # Re-enable rejection message surfaced by the API serializer; `{target_type}` is interpolated
    # with the channel's display label, so it reads "Microsoft Teams" rather than "teams".
    user_message: str


SLACK_DISCONNECTED_DISABLE_REASON = DisableReason(
    key="missing_integration",
    description="Slack integration disconnected",
    user_message="Cannot re-enable Slack subscription: no integration configured. Reconnect Slack first.",
)
UNSUPPORTED_TARGET_DISABLE_REASON = DisableReason(
    key="unsupported_target",
    description="Unsupported delivery channel",
    user_message="Cannot re-enable {target_type} subscription: this delivery channel is not currently supported.",
)
SLACK_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(
    key="slack_permission_revoked",
    description="PostHog can no longer post to this Slack channel",
    user_message="Cannot re-enable {target_type} subscription: PostHog can't post to this Slack channel. Reconnect Slack or re-add the bot to the channel, then try again.",
)
WEBHOOK_REJECTED_DISABLE_REASON = DisableReason(
    key="webhook_rejected",
    description="Microsoft Teams stopped accepting messages",
    user_message="Cannot re-enable {target_type} subscription: Microsoft Teams stopped accepting messages. Create a new webhook URL in your Teams channel with the Workflows app, update this subscription with it, then try again.",
)
SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(
    key="slack_file_upload_permission_revoked",
    description="PostHog can no longer upload files to Slack",
    user_message=(
        "Cannot re-enable {target_type} subscription: the Slack app needs the files:write permission. "
        "Add files:write to a custom Slack app, or reconnect PostHog's Slack app, then try again."
    ),
)
CREATOR_LEFT_DISABLE_REASON = DisableReason(
    key="creator_left_organization",
    description="The owner of this subscription is no longer in the organization",
    user_message=(
        "Cannot re-enable {target_type} subscription: its owner is no longer in the organization. "
        "Create a new subscription to keep receiving this report."
    ),
)
CREATOR_LOST_ACCESS_DISABLE_REASON = DisableReason(
    key="creator_lost_access",
    description="The owner of this subscription no longer has access to some of its data",
    user_message=(
        "Cannot re-enable {target_type} subscription until its owner has access to all of its data again. "
        "Ask a project admin for access, or create a new subscription."
    ),
)
AI_PROMPT_INVALID_DISABLE_REASON = DisableReason(
    key="ai_prompt_invalid",
    description="AI subscription prompt or creator is invalid",
    user_message="Cannot re-enable AI subscription: the original creator is unavailable or the prompt is invalid. Edit the subscription with a valid prompt to re-enable.",
)
AI_CONSENT_REVOKED_DISABLE_REASON = DisableReason(
    key="ai_consent_revoked",
    description="Organization has not approved AI data processing",
    user_message="Cannot re-enable AI subscription: your organization has not approved AI data processing. Approve it in your organization settings, then re-enable this subscription.",
)

logger = structlog.get_logger(__name__)


def get_subscription_disable_reason(target_type: str | None, integration_id: int | None) -> DisableReason | None:
    """Single source of truth for "what target configuration is permanently broken"."""
    if not target_type:
        return None
    if target_type not in SUPPORTED_TARGET_TYPES:
        return UNSUPPORTED_TARGET_DISABLE_REASON
    if target_type == Subscription.SubscriptionTarget.SLACK and not integration_id:
        return SLACK_DISCONNECTED_DISABLE_REASON
    return None


# Export failures that mean the owner can no longer run the query, not that the export broke.
# Matched by name because delivery only sees the `exception_type` stored on the asset.
_CREATOR_LEFT_ERROR_NAMES = frozenset({CreatorLeftOrganizationError.__name__, UserNotOrganizationMemberError.__name__})
_CREATOR_LOST_ACCESS_ERROR_NAMES = frozenset({TableAccessDeniedError.__name__, UserAccessControlError.__name__})


def get_assets_owner_disable_reason(exception_types: Iterable[str | None]) -> DisableReason | None:
    """The reason to disable a subscription after a delivery whose exports failed for its owner.

    An owner who left fails every export, so one such failure is enough. Lost access is judged on the
    whole delivery: a dashboard with one denied tile is still delivered, with that tile showing why.
    """
    names = list(exception_types)
    if not names:
        return None
    if any(name in _CREATOR_LEFT_ERROR_NAMES for name in names):
        return CREATOR_LEFT_DISABLE_REASON
    if all(name in _CREATOR_LOST_ACCESS_ERROR_NAMES for name in names):
        return CREATOR_LOST_ACCESS_DISABLE_REASON
    return None


def target_type_label(target_type: str | None) -> str:
    if not target_type:
        return ""
    try:
        return str(Subscription.SubscriptionTarget(target_type).label)
    except ValueError:
        return target_type


def validate_re_enable(target_type: str | None, integration_id: int | None) -> str | None:
    """API-serializer wrapper — returns the user-facing rejection message, or None if re-enable is OK."""
    reason = get_subscription_disable_reason(target_type, integration_id)
    if reason is None:
        return None
    return reason.user_message.format(target_type=target_type_label(target_type))


def _get_notification_creator(subscription: Subscription) -> User | None:
    creator = subscription.created_by
    creator_id = subscription.created_by_id
    if creator is None or creator_id is None:
        return None
    if not subscription.team.all_users_with_access().filter(id=creator_id).exists():
        return None
    return creator


def disable_invalid_subscription(
    subscription: Subscription, reason: DisableReason, *, notify_owner: bool = True
) -> None:
    """Disable the subscription once. Pass `notify_owner=False` when the delivery itself already told the recipients why."""
    # Compare-and-swap so only one racing caller sends the disabled-notification
    # email (UUID4 campaign keys mean MessagingRecord can't dedup the duplicate).
    rowcount = Subscription.objects.filter(pk=subscription.pk, enabled=True).update(enabled=False)
    if rowcount == 0:
        # A concurrent caller already disabled the row — no-op, no side effects.
        # The in-memory `subscription.enabled` is intentionally NOT touched here so
        # callers can distinguish "we just disabled it" from "it was already disabled";
        # the activity site re-fetches via select_related when it needs fresh state.
        logger.info(
            "subscription.auto_disable_already_disabled",
            subscription_id=subscription.id,
            team_id=subscription.team_id,
            reason=reason.key,
        )
        return

    logger.warning(
        "subscription.auto_disabling",
        subscription_id=subscription.id,
        team_id=subscription.team_id,
        reason=reason.key,
    )
    # Mirror the UPDATE in memory so callers see the new state without a fresh
    # SELECT — refresh_from_db() would also drop the eagerly-loaded created_by
    # relation (loaded via select_related at the activity site).
    subscription.enabled = False
    if not notify_owner:
        return

    try:
        create_subscription_auto_disabled_notification(subscription, reason)
    except Exception as e:
        capture_exception(e)
        logger.warning(
            "subscription.create_auto_disabled_notification_failed",
            subscription_id=subscription.id,
            error=str(e),
            exc_info=True,
        )

    creator = _get_notification_creator(subscription)
    if creator and creator.email:
        try:
            send_notifications_for_disabled_subscription(subscription, reason, [creator.email])
        except Exception as e:
            # Disabling is the durable side effect; email is best-effort. If the email
            # fails (SMTP outage, ImproperlyConfigured on self-hosted, Customer.io 5xx)
            # the SLO outcome must stay `success` — we successfully prevented the
            # subscription from re-firing, which is the contract this code provides.
            capture_exception(e)
            logger.warning(
                "subscription.send_disabled_notification_failed",
                subscription_id=subscription.id,
                error=str(e),
                exc_info=True,
            )


def create_subscription_auto_disabled_notification(subscription: Subscription, reason: DisableReason) -> None:
    creator = _get_notification_creator(subscription)
    if creator is None:
        return

    title = subscription.title or "Subscription"
    source_url = urlparse(subscription.url).path if subscription.url else ""
    create_notification(
        NotificationData(
            team_id=subscription.team_id,
            notification_type=NotificationType.PIPELINE_FAILURE,
            priority=Priority.NORMAL,
            title=f"{title[:75]} was automatically disabled",
            # Every description is a sentence-case fragment, and most open on a brand name
            # ("Microsoft Teams stopped accepting messages"), so it stands as its own sentence.
            # Folding it into a "because ..." clause needs it lowercased, which mangles the brand.
            body=(
                f"PostHog automatically disabled this subscription. {reason.description}. "
                f"{reason.user_message.format(target_type=target_type_label(subscription.target_type))}"
            ),
            target_type=TargetType.USER,
            target_id=str(creator.id),
            resource_type=NotificationOnlyResourceType.PIPELINE,
            resource_id=str(subscription.id),
            source_url=source_url,
            source_id=str(uuid.uuid4()),
        )
    )


def send_notifications_for_disabled_subscription(
    subscription: Subscription, reason: DisableReason, targets: list[str]
) -> None:
    logger.info(
        "subscription.send_disabled_notification",
        subscription_id=subscription.id,
        recipient_count=len(targets),
    )

    display_name = subscription.title or "your subscription"
    subject = (
        f'PostHog subscription "{subscription.title}" has been automatically disabled'
        if subscription.title
        else "Your PostHog subscription has been automatically disabled"
    )
    campaign_key = f"subscription-disabled-notification-{subscription.id}-{uuid.uuid4()}"

    message = EmailMessage(
        campaign_key=campaign_key,
        subject=subject,
        template_name="subscription_disabled",
        template_context={
            "subscription_url": subscription.url,
            "subscription_title": display_name,
            "reason": reason.description,
            "action_message": reason.user_message.format(target_type=target_type_label(subscription.target_type)),
        },
    )
    for target in targets:
        message.add_recipient(email=target)

    message.send()