: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
feat: let a member take ownership of a subscription or alert whose owner left (#125382)
Alex Lider37d27503c95b
diff --git a/posthog/query_creator_access.py b/posthog/query_creator_access.pyindex f921b314a612..0692b1f7c451 100644--- a/posthog/query_creator_access.py+++ b/posthog/query_creator_access.py@@ -13,6 +13,11 @@ from products.access_control.backend.facade.user_access_control import (model_to_resource,)+# The API error codes for a write refused because the owner can no longer run the resource, one per cause.+# Shared by subscriptions and alerts; the frontend offers to take ownership when it sees either.+OWNER_LEFT_ORGANIZATION_CODE = "owner_left_organization"+OWNER_LOST_ACCESS_CODE = "owner_lost_access"+class CreatorLeftOrganizationError(Exception):"""A background query refused to run because its owner is no longer in the organization."""@@ -55,6 +60,23 @@ def assert_creator_can_run(user: Optional[User], team: Team, *objects: Model | Nraise UserAccessControlError(resource, "viewer", str(obj.pk))+def owner_unavailable_code(error: Exception) -> str:+ """The API error code for `error`, as raised by `assert_creator_can_run`. A deleted owner counts as one who left."""+ return OWNER_LEFT_ORGANIZATION_CODE if isinstance(error, CreatorLeftOrganizationError) else OWNER_LOST_ACCESS_CODE+++def describe_owner_unavailable(user: Optional[User], error: Exception) -> str:+ """One sentence on why `user` can no longer run a resource, for the person trying to enable it.++ `error` is what `assert_creator_can_run` raised for them.+ """+ if user is None:+ return "It runs with the access of its creator, whose account was deleted."+ if isinstance(error, CreatorLeftOrganizationError):+ return f"It runs with the access of its creator, {user.email}, who is no longer in the organization."+ return f"It runs with the access of its creator, {user.email}, who no longer has access to the data it reads."++def report_creator_access_revoked(*,user: Optional[User],diff --git a/products/alerts/backend/facade/api.py b/products/alerts/backend/facade/api.pyindex dce4eb044fb5..444149ca51ca 100644--- a/products/alerts/backend/facade/api.py+++ b/products/alerts/backend/facade/api.py@@ -19,6 +19,7 @@ from django.utils import timezoneimport structlogfrom posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.activity_logging.model_activity import ActingUserContextfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -27,6 +28,7 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import relative_date_parsefrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.alerts.backend.activity_logging import AlertConfigurationContextfrom products.alerts.backend.facade import contractsfrom products.alerts.backend.insight_alert_state_machine import apply_snoozefrom products.alerts.backend.judge.contract import (@@ -247,6 +249,43 @@ def list_firing_alerts_created_by(]+def assign_alert_owner(*, team_id: int, alert_id: uuid.UUID, user: User, was_impersonated: bool) -> None:+ """Make `user` the owner of the alert and record the takeover in the activity log.++ `created_by` is excluded from the save diff, so the takeover gets its own activity.+ """+ alert = AlertConfiguration.objects.select_related("insight", "created_by").get(team_id=team_id, id=alert_id)+ previous_owner = alert.created_by+ alert.created_by = user+ alert.save(update_fields=["created_by"])+ log_activity(+ organization_id=alert.team.organization_id,+ team_id=alert.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=alert.id,+ scope="AlertConfiguration",+ activity="took_ownership",+ detail=Detail(+ name=alert.name or f"Alert for {alert.insight.name}",+ changes=[+ Change(+ type="AlertConfiguration",+ action="changed",+ field="created_by",+ before={"id": previous_owner.id, "email": previous_owner.email} if previous_owner else None,+ after={"id": user.id, "email": user.email},+ )+ ],+ context=AlertConfigurationContext(+ insight_id=alert.insight_id,+ insight_short_id=alert.insight.short_id,+ insight_name=alert.insight.name,+ ),+ ),+ )++__all__ = ["LLM_DETECTOR_UNAVAILABLE_ERROR_CODE","LLM_DETECTOR_UNAVAILABLE_MESSAGE",@@ -259,6 +298,7 @@ __all__ = ["LLMDetectorMisconfiguredError","LLMDetectorUnavailableError","admit_llm_alert_write",+ "assign_alert_owner","is_llm_detector_config","llm_detector_access_error",]diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.pyindex bc8025bf0f00..59f4629c8ba5 100644--- a/products/alerts/backend/presentation/views/alert.py+++ b/products/alerts/backend/presentation/views/alert.py@@ -53,9 +53,16 @@ from posthog.helpers.trigram_search import ()from posthog.integrations import IntegrationManagerfrom posthog.models import User+from posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom posthog.permissions import get_authenticator_scopes+from posthog.query_creator_access import (+ CreatorLeftOrganizationError,+ assert_creator_can_run,+ describe_owner_unavailable,+ owner_unavailable_code,+)from posthog.rate_limit import (AlertLLMSimulationBurstThrottle,AlertLLMSimulationDailyThrottle,@@ -75,6 +82,7 @@ from posthog.tasks.alerts.utils import ()from posthog.utils import relative_date_parse+from products.access_control.backend.facade.user_access_control import UserAccessControlErrorfrom products.alerts.backend.evaluation.contract import AlertExtractionErrorfrom products.alerts.backend.evaluation.detector import simulate_detector_on_insightfrom products.alerts.backend.evaluation.validation import (@@ -89,6 +97,7 @@ from products.alerts.backend.facade.api import (LLMDetectorError,LLMDetectorUnavailableError,admit_llm_alert_write,+ assign_alert_owner,is_llm_detector_config,llm_detector_access_error,)@@ -261,10 +270,11 @@ def _enforce_llm_detector_rules(detector_config: Any) -> None:def _enforce_llm_feature_access(context: dict[str, Any], detector_config: Any) -> None:- """Refuse an AI preview the person asking cannot use.+ """Refuse an AI preview or takeover the person asking cannot use.Saved alerts go through ``admit_llm_alert_write`` instead, which checks the alert's- creator: a preview has no alert, so the requester is the principal.+ creator. A preview has no alert, and a takeover makes the requester the creator, so+ both check the requester."""if DetectorType.LLM.value not in _detector_types(detector_config):return@@ -646,6 +656,11 @@ class RelativeDateTimeField(serializers.DateTimeField):return data+def _owner_unavailable_message(owner: User | None, error: Exception) -> str:+ """The refusal for an enable the owner cannot run, naming the owner and the cause."""+ return f"Can't enable this alert. {describe_owner_unavailable(owner, error)}"++class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializer):evaluation_delay_intervals = serializers.IntegerField(min_value=0,@@ -1113,6 +1128,15 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializeinsight = attrs.get("insight") or (self.instance.insight if self.instance else None)if insight is None:raise ValidationError({"insight": ["Insight is required."]})+ # Checks run as the owner, so an owner who cannot run them would only get the alert disabled again.+ if self.instance is not None and attrs.get("enabled") is True and not self.instance.enabled:+ try:+ assert_creator_can_run(self.instance.created_by, self.instance.team, insight)+ except (CreatorLeftOrganizationError, UserAccessControlError) as error:+ raise ValidationError(+ {"enabled": [_owner_unavailable_message(self.instance.created_by, error)]},+ code=owner_unavailable_code(error),+ )# Enforced from the object-level validate() so it runs on every create and update — including# a PATCH that omits `insight` (which skips the field-level validator), so an alert can't be# repointed at a flag-gated insight kind (or a scope-gated one) in an account where the flag@@ -1233,7 +1257,8 @@ class AlertSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerialize})- if self.context["request"].method == "POST":+ # Only a create adds an alert; a takeover is a POST that enables an existing one.+ if self.instance is None:if msg := AlertConfiguration.check_alert_limit(self.context["team_id"], self.context["get_organization"]()):raise ValidationError({"alert": [msg]})@@ -1808,6 +1833,42 @@ class AlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):serializer = self.get_serializer(alerts, many=True)return Response(serializer.data)+ @extend_schema(+ request=None,+ responses={200: AlertSerializer},+ description=(+ "Make the requesting user the owner of this alert and enable it. Checks run with the owner's "+ "access, so this is how an alert continues after its owner left."+ ),+ )+ @action(detail=True, methods=["POST"], required_scopes=["alert:write"])+ def take_ownership(self, request, *args, **kwargs):+ alert = self.get_object()+ user = cast(User, request.user)+ try:+ assert_creator_can_run(user, alert.team, alert.insight)+ except (CreatorLeftOrganizationError, UserAccessControlError):+ raise ValidationError("Can't take ownership: you don't have access to this insight.") from None+ # The scheduled checks run as the owner, so an AI alert needs the requester on the rollout.+ # An already enabled alert does not pass through the admission below, so it is checked here.+ _enforce_llm_feature_access(self.get_serializer_context(), alert.detector_config)+ # One transaction, so a refused enable leaves the owner as it was. The enable below reloads+ # the row, so the owner is saved first.+ with transaction.atomic():+ # Same lock order as update(): insight, then alert row. The owner write below locks the row.+ if not lock_insight_for_evaluation(team_id=alert.team_id, insight_id=alert.insight_id):+ raise ValidationError({"insight": ["The insight no longer exists. Refresh the alert."]})+ assign_alert_owner(+ team_id=alert.team_id, alert_id=alert.id, user=user, was_impersonated=get_was_impersonated()+ )+ # The enable below saves this instance, so it must carry the new owner.+ alert.refresh_from_db(fields=["created_by"])+ # The enable runs the usual update path, so the insight query is validated as the new owner.+ serializer = self.get_serializer(alert, data={"enabled": True}, partial=True)+ serializer.is_valid(raise_exception=True)+ serializer.save()+ return Response(self.get_serializer(serializer.instance).data)+@extend_schema(request=None,responses={202: AlertTestDeliveryResponseSerializer},diff --git a/products/alerts/backend/test/test_alert_take_ownership.py b/products/alerts/backend/test/test_alert_take_ownership.pynew file mode 100644index 000000000000..fde8851da543--- /dev/null+++ b/products/alerts/backend/test/test_alert_take_ownership.py@@ -0,0 +1,64 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from posthog.models import User+from posthog.models.activity_logging.activity_log import ActivityLog++from products.alerts.backend.models.alert import AlertConfiguration+from products.alerts.backend.test.insight_alerts import create_insight_alert+++class TestAlertTakeOwnership(APIBaseTest):+ def _disabled_alert_of_a_former_member(self) -> AlertConfiguration:+ former_member = User.objects.create_user(email="[email protected]", first_name="", password=None)+ return create_insight_alert(self.team, created_by=former_member, enabled=False)++ def test_enabling_is_rejected_when_the_owner_left(self) -> None:+ alert = self._disabled_alert_of_a_former_member()++ response = self.client.patch(f"/api/projects/{self.team.id}/alerts/{alert.id}", {"enabled": True})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"] == "enabled"+ # The frontend keys its "take ownership" offer, and the cause it shows, on this code.+ assert response.json()["code"] == "owner_left_organization"+ assert (+ "its creator, [email protected], who is no longer in the organization" in response.json()["detail"]+ )++ def test_take_ownership_enables_the_alert_as_the_requester(self) -> None:+ alert = self._disabled_alert_of_a_former_member()++ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{alert.id}/take_ownership/")++ assert response.status_code == status.HTTP_200_OK, response.content+ alert.refresh_from_db()+ assert alert.created_by == self.user+ assert alert.enabled is True+ # created_by is excluded from the save diff, so the takeover logs its own activity.+ takeover = ActivityLog.objects.get(scope="AlertConfiguration", item_id=str(alert.id), activity="took_ownership")+ assert takeover.detail is not None+ assert [change["field"] for change in takeover.detail["changes"]] == ["created_by"]+ assert takeover.user == self.user++ def test_take_ownership_is_not_blocked_by_the_alert_limit(self) -> None:+ alert = self._disabled_alert_of_a_former_member()++ with patch.object(AlertConfiguration, "check_alert_limit", return_value="Your team has reached the limit."):+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{alert.id}/take_ownership/")++ assert response.status_code == status.HTTP_200_OK, response.content++ def test_take_ownership_of_an_ai_alert_needs_the_rollout(self) -> None:+ former_member = User.objects.create_user(email="[email protected]", first_name="", password=None)+ # Enabled, so the enable path's admission does not run and only the takeover check applies.+ alert = create_insight_alert(self.team, created_by=former_member, enabled=True, detector_config={"type": "llm"})++ with patch("products.alerts.backend.llm_detector_limits.posthoganalytics.feature_enabled", return_value=False):+ response = self.client.post(f"/api/projects/{self.team.id}/alerts/{alert.id}/take_ownership/")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ alert.refresh_from_db()+ assert alert.created_by == former_memberdiff --git a/products/alerts/frontend/generated/api.ts b/products/alerts/frontend/generated/api.tsindex 0e6ee1dc7ea4..e5c7ad604d42 100644--- a/products/alerts/frontend/generated/api.ts+++ b/products/alerts/frontend/generated/api.ts@@ -203,6 +203,24 @@ export const alertsDestinationsDeleteCreate = async (})}+export const getAlertsTakeOwnershipCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/alerts/${id}/take_ownership/`+}++/**+ * Make the requesting user the owner of this alert and enable it. Checks run with the owner's access, so this is how an alert continues after its owner left.+ */+export const alertsTakeOwnershipCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<AlertApi> => {+ return apiMutator<AlertApi>(getAlertsTakeOwnershipCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getAlertsTestDeliveryCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/alerts/${id}/test-delivery/`}diff --git a/products/subscriptions/backend/facade/api.py b/products/subscriptions/backend/facade/api.pyindex 1c619100f2da..c19e1358a192 100644--- a/products/subscriptions/backend/facade/api.py+++ b/products/subscriptions/backend/facade/api.py@@ -307,6 +307,29 @@ def update_subscription()+def take_subscription_ownership(+ *,+ team: Team,+ organization: Organization,+ user: User,+ viewer: UserAccessControl,+ subscription_id: int,+ analytics_props: AnalyticsProps,+) -> contracts.SubscriptionRecord:+ """Make `user` the owner of the subscription and enable it. Deliveries then run with their access.++ Raises the same errors as `update_subscription`.+ """+ return subscription_writes.take_subscription_ownership(+ team=team,+ organization=organization,+ user=user,+ viewer=viewer,+ subscription_id=subscription_id,+ analytics_props=analytics_props,+ )++def start_test_delivery(*, team_id: int, subscription_id: int) -> contracts.ManualDeliveryResult:"""Start one delivery of the subscription now, outside its schedule."""return subscription_writes.start_test_delivery(team_id=team_id, subscription_id=subscription_id)diff --git a/products/subscriptions/backend/facade/contracts.py b/products/subscriptions/backend/facade/contracts.pyindex 5b4d9a7e4575..36f6757edf14 100644--- a/products/subscriptions/backend/facade/contracts.py+++ b/products/subscriptions/backend/facade/contracts.py@@ -90,12 +90,13 @@ class SubscriptionRequestInvalidError(ValueError):"""The request breaks a subscription rule. The API answers 400 with `detail`.`detail` has the shape a serializer validation error carries: a message, a list of messages, or- a mapping from field name to messages.+ a mapping from field name to messages. `code` names the rule for clients that act on it."""- def __init__(self, detail: str | list[str] | Mapping[str, list[str]]) -> None:+ def __init__(self, detail: str | list[str] | Mapping[str, list[str]], code: str | None = None) -> None:super().__init__(detail)self.detail = detail+ self.code = codeclass SubscriptionPermissionDeniedError(PermissionError):diff --git a/products/subscriptions/backend/logic/subscription_writes.py b/products/subscriptions/backend/logic/subscription_writes.pyindex f9337b372c36..8e8a95bc037a 100644--- a/products/subscriptions/backend/logic/subscription_writes.py+++ b/products/subscriptions/backend/logic/subscription_writes.py@@ -20,10 +20,18 @@ from posthog.constants import SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEYfrom posthog.event_usage import AnalyticsProps, groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.integrations import IntegrationManager, IntegrationNotFound+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.activity_logging.model_activity import get_was_impersonatedfrom posthog.models.integration import SlackIntegrationfrom posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.user import User+from posthog.query_creator_access import (+ CreatorLeftOrganizationError,+ assert_creator_can_run,+ describe_owner_unavailable,+ owner_unavailable_code,+)from posthog.resource_limits import LimitKey, check_count_limitfrom posthog.security.url_validation import is_microsoft_teams_webhook_urlfrom posthog.slo.context import SloSpec, slo_operation@@ -31,7 +39,7 @@ from posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connectfrom posthog.utils import human_list-from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlErrorfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.facade.api import insights_including_soft_deleted_for_teamfrom products.product_analytics.backend.facade.models import Insight@@ -130,6 +138,11 @@ def _write_attrs(write: SubscriptionWrite) -> dict:return attrs+def owner_unavailable_message(owner: User | None, error: Exception) -> str:+ """The refusal for a re-enable the owner cannot run, naming the owner and the cause."""+ return f"Can't re-enable this subscription. {describe_owner_unavailable(owner, error)}"++class _SubscriptionWrite:"""One create or update, checked against the rules that span fields, the team and the plan."""@@ -421,6 +434,18 @@ class _SubscriptionWrite:error_message = validate_re_enable(target_type, integration_id)if error_message:raise SubscriptionRequestInvalidError({"enabled": [error_message]})+ # Deliveries run as the owner, so an owner who cannot run them would only get it disabled again.+ assert existing is not None+ # The owner must be able to run the target this write leaves, not the one it replaces.+ dashboard = attrs.get("dashboard") or existing.dashboard+ insight = attrs.get("insight") or existing.insight+ try:+ assert_creator_can_run(existing.created_by, self.team, dashboard, insight)+ except (CreatorLeftOrganizationError, UserAccessControlError) as error:+ raise SubscriptionRequestInvalidError(+ {"enabled": [owner_unavailable_message(existing.created_by, error)]},+ code=owner_unavailable_code(error),+ ) from None# AI subs auto-disable on PromptRejectedError (deleted creator, prompt now# fails sanitization). The delivery path will just re-disable on the next# tick unless the underlying cause is fixed by this PATCH.@@ -1019,6 +1044,76 @@ def update_subscription(return subscription_record(subscription_write.update(instance, validated_data))+def take_subscription_ownership(+ *,+ team: Team,+ organization: Organization,+ user: User,+ viewer: UserAccessControl,+ subscription_id: int,+ analytics_props: AnalyticsProps,+) -> SubscriptionRecord:+ """Make `user` the owner and enable the subscription, so deliveries run with their access.++ Every refusal comes before the owner changes, so a refused takeover leaves the subscription as+ it was: the new owner must be able to view the dashboard or insight and read every table the+ subscription delivers, and the enable must pass its usual checks as the new owner.+ """+ instance = Subscription.objects.get(pk=subscription_id, team_id=team.id)+ try:+ assert_creator_can_run(user, team, instance.dashboard, instance.insight)+ except (CreatorLeftOrganizationError, UserAccessControlError):+ raise SubscriptionRequestInvalidError("Can't take ownership: you don't have access to this content.") from None+ # The enable below only compiles the queries when it enables a disabled row, so an enabled one is+ # checked here, as the new owner.+ if instance.enabled:+ denied_resources = denied_resources_in_subscription(+ user=user, team=team, user_access_control=viewer, subscription_id=subscription_id, attrs={}+ )+ if denied_resources:+ denied_names = ", ".join(f"`{name}`" for name in denied_resources)+ raise SubscriptionRequestInvalidError(f"Can't take ownership: you don't have access to {denied_names}.")+ # The new owner is set in memory only: the re-enable check reads it off the instance, and the+ # enable's save persists it with `enabled`.+ previous_owner = instance.created_by+ instance.created_by = user+ subscription_write = _SubscriptionWrite(+ team=team,+ organization=organization,+ user=user,+ viewer=viewer,+ instance=instance,+ partial=True,+ is_create_request=False,+ analytics_props=analytics_props,+ )+ validated_data = subscription_write.validate(_write_attrs(SubscriptionWrite(enabled=True)))+ updated = subscription_write.update(instance, validated_data)+ # `created_by` is excluded from the save diff, so the takeover gets its own activity.+ log_activity(+ organization_id=team.organization_id,+ team_id=team.id,+ user=user,+ was_impersonated=get_was_impersonated(),+ item_id=updated.id,+ scope="Subscription",+ activity="took_ownership",+ detail=Detail(+ name=updated.display_name,+ changes=[+ Change(+ type="Subscription",+ action="changed",+ field="created_by",+ before={"id": previous_owner.id, "email": previous_owner.email} if previous_owner else None,+ after={"id": user.id, "email": user.email},+ )+ ],+ ),+ )+ return subscription_record(updated)++def start_test_delivery(*, team_id: int, subscription_id: int) -> ManualDeliveryResult:subscription = Subscription.objects.get(pk=subscription_id, team_id=team_id)temporal = sync_connect()diff --git a/products/subscriptions/backend/presentation/views.py b/products/subscriptions/backend/presentation/views.pyindex 3aa115de6aa5..c126306d5277 100644--- a/products/subscriptions/backend/presentation/views.py+++ b/products/subscriptions/backend/presentation/views.py@@ -625,7 +625,7 @@ def _raise_for_refusal(call: Callable[[], contracts.SubscriptionRecord]) -> conttry:return call()except contracts.SubscriptionRequestInvalidError as refusal:- raise ValidationError(as_serializer_error(ValidationError(refusal.detail)))+ raise ValidationError(as_serializer_error(ValidationError(refusal.detail, code=refusal.code)))except contracts.SubscriptionPermissionDeniedError as refusal:raise exceptions.PermissionDenied(refusal.message)except contracts.SubscriptionQuotaExceededError as refusal:@@ -971,6 +971,35 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Gdef partial_update(self, request: Request, **kwargs: object) -> Response:return self.update(request, partial=True, **kwargs)+ @extend_schema(+ extensions={"x-product": "subscriptions"},+ request=None,+ responses={200: SubscriptionSerializer},+ description=(+ "Make the requesting user the owner of this subscription and enable it. Deliveries run with "+ "the owner's access, so this is how a subscription continues after its owner left."+ ),+ )+ # Scope is resolved dynamically in dangerously_get_required_scopes so an AI subscription also+ # requires query:read (enabling it starts the AI HogQL pipeline). A static required_scopes here+ # would short-circuit that check.+ @action(methods=["POST"], detail=True)+ def take_ownership(self, request: Request, **kwargs: object) -> Response:+ subscription = self._get_subscription()+ if subscription.deleted:+ return Response(status=status.HTTP_404_NOT_FOUND)+ updated = _raise_for_refusal(+ lambda: api.take_subscription_ownership(+ team=self.team,+ organization=self.organization,+ user=cast(User, request.user),+ viewer=self.user_access_control,+ subscription_id=subscription.id,+ analytics_props=get_request_analytics_properties(request),+ )+ )+ return Response(_write_response(updated, partial=True))+@extend_schema(extensions={"x-product": "subscriptions"},request=None,diff --git a/products/subscriptions/backend/tests/test_subscription.py b/products/subscriptions/backend/tests/test_subscription.pyindex 11fe624d0e87..7f3ddecf3ac3 100644--- a/products/subscriptions/backend/tests/test_subscription.py+++ b/products/subscriptions/backend/tests/test_subscription.py@@ -19,7 +19,8 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.constants import SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY, AvailableFeaturefrom posthog.integrations import SOURCE_MARKER_CONFIG_KEY-from posthog.models import Team+from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKey@@ -402,6 +403,7 @@ class TestSubscriptionTemporal(APILicensedTest):def _disabled_email_sub(self) -> int:return Subscription.objects.create(team=self.team,+ created_by=self.user,target_type="email",target_value="[email protected]",frequency="daily",@@ -1097,6 +1099,54 @@ class TestSubscriptionTemporal(APILicensedTest):assert response.json()["attr"] == "enabled"assert "this delivery channel is not currently supported" in response.json()["detail"]+ def _disabled_subscription_of_a_former_member(self) -> Subscription:+ former_member = User.objects.create_user(email="[email protected]", first_name="", password=None)+ return Subscription.objects.create(+ team=self.team,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ start_date=timezone.now(),+ insight=self.insight,+ title="left behind",+ created_by=former_member,+ enabled=False,+ )++ def test_patch_enabled_true_rejected_when_the_owner_left(self):+ subscription = self._disabled_subscription_of_a_former_member()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/",+ {"enabled": True},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "enabled"+ # The frontend keys its "take ownership" offer, and the cause it shows, on this code.+ assert response.json()["code"] == "owner_left_organization"+ assert (+ "its creator, [email protected], who is no longer in the organization" in response.json()["detail"]+ )++ def test_take_ownership_enables_the_subscription_as_the_requester(self):+ subscription = self._disabled_subscription_of_a_former_member()++ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}/take_ownership/")++ assert response.status_code == status.HTTP_200_OK, response.content+ subscription.refresh_from_db()+ assert subscription.created_by == self.user+ assert subscription.enabled is True+ assert response.json()["created_by"]["id"] == self.user.id+ # created_by is excluded from the save diff, so the takeover logs its own activity.+ takeover = ActivityLog.objects.get(+ scope="Subscription", item_id=str(subscription.id), activity="took_ownership"+ )+ assert takeover.detail is not None+ assert [change["field"] for change in takeover.detail["changes"]] == ["created_by"]+ assert takeover.user == self.user+def test_cannot_create_subscription_with_summary_enabled_without_ai_consent(self):self.organization.is_ai_data_processing_approved = Falseself.organization.save()@@ -1992,6 +2042,7 @@ class TestSubscriptionTemporal(APILicensedTest):# after the immediate SUBSCRIPTION_CHANGE confirmation.subscription = Subscription.objects.create(team=self.team,+ created_by=self.user,target_type="email",target_value="[email protected]",frequency="daily",@@ -2037,6 +2088,7 @@ class TestSubscriptionTemporal(APILicensedTest):kwargs["until_date"] = timezone.now() + timedelta(days=kwargs["until_date"])subscription = Subscription.objects.create(team=self.team,+ created_by=self.user,target_type="email",target_value="[email protected]",frequency="daily",@@ -2099,6 +2151,7 @@ class TestSubscriptionTemporal(APILicensedTest):# candidate-rrule check honors the new `until_date` and lets it through.subscription = Subscription.objects.create(team=self.team,+ created_by=self.user,target_type="email",target_value="[email protected]",frequency="daily",@@ -2154,6 +2207,7 @@ class TestSubscriptionTemporal(APILicensedTest):):subscription = Subscription.objects.create(team=self.team,+ created_by=self.user,target_type="email",target_value="[email protected]",frequency="daily",diff --git a/products/subscriptions/frontend/generated/api.ts b/products/subscriptions/frontend/generated/api.tsindex 1afb43cb3883..485023319504 100644--- a/products/subscriptions/frontend/generated/api.ts+++ b/products/subscriptions/frontend/generated/api.ts@@ -148,6 +148,24 @@ export const subscriptionsDestroy = async (projectId: string, id: number, option})}+export const getSubscriptionsTakeOwnershipCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/subscriptions/${id}/take_ownership/`+}++/**+ * Make the requesting user the owner of this subscription and enable it. Deliveries run with the owner's access, so this is how a subscription continues after its owner left.+ */+export const subscriptionsTakeOwnershipCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<SubscriptionApi> => {+ return apiMutator<SubscriptionApi>(getSubscriptionsTakeOwnershipCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getSubscriptionsTestDeliveryCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/subscriptions/${id}/test-delivery/`}