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.

fix(cdp): let managed alert destinations be edited through the hog functions API (#113538)

Jimmy Zhu0763f2cf4e29
diff --git a/posthog/cdp/internal_events.py b/posthog/cdp/internal_events.py
index ff5df7064b1e..b2add5ecd302 100644
--- a/posthog/cdp/internal_events.py
+++ b/posthog/cdp/internal_events.py
@@ -45,6 +45,28 @@ def is_managed_alert_internal_event(event_name: object) -> bool:
)
+# Alert products whose destinations stay editable through the generic hog functions API, keyed by
+# the prefix of their alert events and valued by the API scope object their own alert API checks.
+# An edit through the generic API requires that product's write scope and editor access on top of
+# the hog function ones, so a token or member that cannot touch the alert cannot touch its
+# destination either. The other alert products stay read-only there.
+GENERIC_API_EDITABLE_ALERT_EVENT_SCOPES: dict[str, str] = {"$logs_alert_": "logs"}
+
+
+def generic_api_editable_alert_scope(event_name: object) -> str | None:
+ """Return the scope object that guards generic-API edits of a managed alert event's destinations."""
+ if not is_managed_alert_internal_event(event_name):
+ return None
+ return next(
+ (
+ scope
+ for prefix, scope in GENERIC_API_EDITABLE_ALERT_EVENT_SCOPES.items()
+ if str(event_name).startswith(prefix)
+ ),
+ None,
+ )
+
+
@dataclass
class InternalEventEvent:
event: str
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.py
index fb05a9956380..47850e2cbdf0 100644
--- a/products/cdp/backend/api/hog_function.py
+++ b/products/cdp/backend/api/hog_function.py
@@ -2,6 +2,7 @@ import json
from datetime import timedelta
from typing import Any, Optional, cast
+from django.core.exceptions import ValidationError as DjangoValidationError
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import transaction
from django.db.models import Q, QuerySet
@@ -28,7 +29,11 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.utils import action, log_activity_from_viewset
from posthog.cdp.filters import DATA_WAREHOUSE_SOURCES
-from posthog.cdp.internal_events import is_managed_alert_internal_event, is_reserved_internal_event
+from posthog.cdp.internal_events import (
+ generic_api_editable_alert_scope,
+ is_managed_alert_internal_event,
+ is_reserved_internal_event,
+)
from posthog.cdp.services.icons import CDPIconsService
from posthog.cdp.site_functions import get_transpiled_function
from posthog.cdp.validation import (
@@ -54,6 +59,7 @@ from posthog.helpers.trigram_search import (
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.plugins.plugin_server_api import create_hog_invocation_test, rerun_hog_invocations
+from posthog.scopes import APIScopeObject
from products.batch_exports.backend.facade import api as batch_exports_api
from products.batch_exports.backend.facade.contracts import InvalidBatchExportFilters
@@ -341,6 +347,31 @@ class HogFunctionMaskingSerializer(serializers.Serializer):
return super().validate(attrs)
+_AlertMarkers = tuple[frozenset[tuple[object, object]], frozenset[str]]
+
+
+def _managed_alert_markers(filters: Optional[dict]) -> Optional[_AlertMarkers]:
+ """The parts of a filter set that make a destination alert-owned: the managed alert events it
+ follows and the alert_id properties that pin it to an alert. None when it follows no managed
+ alert event. The alert layer finds a destination by its event ids and alert_id values, so a
+ change to those strands the row; the rest of the alert_id entry counts too, since another
+ operator or property type would make the row fire for other alerts."""
+ filters = filters or {}
+ events = frozenset(
+ (event_filter.get("id"), event_filter.get("type"))
+ for event_filter in filters.get("events") or []
+ if isinstance(event_filter, dict) and is_managed_alert_internal_event(event_filter.get("id"))
+ )
+ if not events:
+ return None
+ alert_ids = frozenset(
+ json.dumps(property_filter, sort_keys=True)
+ for property_filter in filters.get("properties") or []
+ if isinstance(property_filter, dict) and property_filter.get("key") == "alert_id"
+ )
+ return events, alert_ids
+
+
class HogFunctionSerializer(HogFunctionMinimalSerializer):
template = HogFunctionTemplateSerializer(read_only=True)
base_updated_at = serializers.DateTimeField(
@@ -630,25 +661,41 @@ class HogFunctionSerializer(HogFunctionMinimalSerializer):
self.context.get("view") and self.context["view"].action == "create"
)
+ instance = cast(Optional[HogFunction], self.context.get("instance", self.instance))
+ current_filters = instance.filters if isinstance(instance, HogFunction) else {}
+ proposed_filters = attrs.get("filters", current_filters)
+
if not self.context.get("allow_managed_alert_destination"):
- current_filters = self.instance.filters if isinstance(self.instance, HogFunction) else {}
- proposed_filters = attrs.get("filters", current_filters)
- current_is_managed = any(
- is_managed_alert_internal_event(event_filter.get("id"))
- for event_filter in (current_filters or {}).get("events", [])
- if isinstance(event_filter, dict)
- )
- proposed_is_managed = any(
- is_managed_alert_internal_event(event_filter.get("id"))
- for event_filter in (proposed_filters or {}).get("events", [])
- if isinstance(event_filter, dict)
- )
- if current_is_managed or proposed_is_managed:
+ # The alert API owns which alert a destination belongs to and removes a destination group
+ # as a whole; a removed one is added back there, not restored here. Everything else about
+ # the function stays editable here.
+ current_markers = _managed_alert_markers(current_filters)
+ if current_markers is not None and not all(
+ generic_api_editable_alert_scope(event_id) for event_id, _ in current_markers[0]
+ ):
raise serializers.ValidationError(
{"filters": "Alert notification destinations are managed through the alert API."}
)
+ if _managed_alert_markers(proposed_filters) != current_markers:
+ message = (
+ "Alert notification destinations are managed through the alert API."
+ if current_markers is None
+ else "The alert this destination belongs to cannot be changed. "
+ "Manage it from the alert's notification settings."
+ )
+ raise serializers.ValidationError({"filters": message})
+ if (
+ isinstance(instance, HogFunction)
+ and current_markers is not None
+ and attrs.get("deleted", instance.deleted) != instance.deleted
+ ):
+ raise serializers.ValidationError(
+ {
+ "deleted": "Remove this destination from the alert's notification settings instead. "
+ "A removed destination is added back from there, not restored here."
+ }
+ )
- proposed_filters = attrs.get("filters", self.instance.filters if isinstance(self.instance, HogFunction) else {})
reserved = sorted(
{
event_filter["id"]
@@ -1024,7 +1071,46 @@ class HogFunctionViewSet(
log_source = "hog_function"
app_source = "hog_function"
+ def _editable_alert_scope(self) -> Optional[str]:
+ """The owning product's scope object when this request writes to an alert destination."""
+ # The draft actions (restore_revision, then publish) and rerun also change or replay what the
+ # destination delivers, so every write action needs the scope.
+ hog_function_id = self.kwargs.get("pk")
+ if self.action not in self.scope_object_write_actions or not hog_function_id:
+ return None
+ if not hasattr(self, "_cached_editable_alert_scope"):
+ try:
+ filters = (
+ HogFunction.objects.filter(team_id=self.team_id, id=str(hog_function_id))
+ .values_list("filters", flat=True)
+ .first()
+ )
+ except (ValueError, DjangoValidationError):
+ filters = None
+ scopes = {
+ generic_api_editable_alert_scope(event_filter.get("id"))
+ for event_filter in (filters or {}).get("events") or []
+ if isinstance(event_filter, dict)
+ }
+ scopes.discard(None)
+ self._cached_editable_alert_scope = next(iter(scopes), None) if len(scopes) == 1 else None
+ return self._cached_editable_alert_scope
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ alert_scope = self._editable_alert_scope()
+ if alert_scope and not self.user_access_control.check_access_level_for_resource(
+ cast(APIScopeObject, alert_scope), required_level="editor"
+ ):
+ raise PermissionDenied(f"Editing this alert destination requires {alert_scope} write access.")
+
def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:
+ # A managed alert destination is also gated by the owning product's write scope, so a
+ # token that cannot configure the alert cannot redirect its notifications either.
+ required_scopes = ["hog_function:write"]
+ alert_scope = self._editable_alert_scope()
+ if alert_scope:
+ required_scopes.append(f"{alert_scope}:write")
# Rerun re-executes stored invocations — it replays up to 30 days of
# persisted event/person/group data through the current (possibly
# reconfigured) function. A `hog_function:write`-only token could use
@@ -1033,8 +1119,8 @@ class HogFunctionViewSet(
# — the same data-read scopes the invocation-inspection paths require.
# (`hog_function:read` would be a no-op since :write already satisfies it.)
if self.action == "rerun":
- return ["hog_function:write", "person:read", "group:read"]
- return None
+ required_scopes += ["person:read", "group:read"]
+ return required_scopes if len(required_scopes) > 1 else None
def get_serializer_class(self) -> type[BaseSerializer]:
if self.action == "list":
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index f9fe31b31469..ea3202358521 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -89,6 +89,14 @@ def get_db_field_value(field, model_id):
return cursor.fetchone()[0]
+def _alert_filters(event_id: str = "$logs_alert_firing", alert_id: str = "alert-1", **overrides: Any) -> dict:
+ return {
+ "events": [{"id": event_id, "type": "events"}],
+ "properties": [{"key": "alert_id", "value": alert_id, "operator": "exact", "type": "event"}],
+ **overrides,
+ }
+
+
class TestHogFunctionAPIWithoutAvailableFeature(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def setUp(self):
super().setUp()
@@ -249,33 +257,200 @@ class TestHogFunctionAPIWithoutAvailableFeature(ClickhouseTestMixin, APIBaseTest
listed_ids = {item["id"] for item in list_response.json()["results"]}
self.assertIn(function_id, listed_ids)
- def test_generic_api_lists_but_cannot_patch_managed_alert_destinations(self):
- managed = HogFunction.objects.create(
+ def _create_internal_destination(self, filters: dict, deleted: bool = False) -> HogFunction:
+ return HogFunction.objects.create(
team=self.team,
- name="Billing alert destination",
+ name="Alert destination",
hog="return event",
type="internal_destination",
enabled=True,
- inputs_schema=[],
- inputs={},
- filters={
- "events": [{"id": "$billing_alert_firing", "type": "events"}],
- "properties": [{"key": "alert_id", "value": "alert-1"}],
- },
+ deleted=deleted,
+ inputs_schema=[{"key": "channel", "type": "string", "required": True}],
+ inputs={"channel": {"value": "#alerts"}},
+ filters=filters,
)
+ def test_generic_api_lists_and_retrieves_managed_alert_destinations(self):
+ managed = self._create_internal_destination(_alert_filters())
+
list_response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/?full=true")
retrieve_response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{managed.id}/")
- patch_response = self.client.patch(
- f"/api/projects/{self.team.id}/hog_functions/{managed.id}/",
- data={"name": "Renamed alert destination"},
- )
self.assertEqual(list_response.status_code, status.HTTP_200_OK)
listed_ids = {item["id"] for item in list_response.json()["results"]}
self.assertIn(str(managed.id), listed_ids)
self.assertEqual(retrieve_response.status_code, status.HTTP_200_OK, retrieve_response.json())
+
+ @parameterized.expand([("$logs_alert_firing",), ("$logs_alert_incident_opened",)])
+ def test_generic_api_can_edit_a_logs_alert_destination(self, event_id):
+ managed = self._create_internal_destination(_alert_filters(event_id))
+
+ # The editor echoes the stored filters back unchanged alongside the edited fields
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/",
+ data={
+ "name": "Renamed alert destination",
+ "enabled": False,
+ "inputs": {"channel": {"value": "#oncall"}},
+ "filters": managed.filters,
+ },
+ )
+
+ self.assertEqual(patch_response.status_code, status.HTTP_200_OK, patch_response.json())
+ managed.refresh_from_db()
+ self.assertEqual(managed.name, "Renamed alert destination")
+ self.assertFalse(managed.enabled)
+ self.assertEqual((managed.inputs or {})["channel"]["value"], "#oncall")
+ self.assertEqual((managed.filters or {})["events"], [{"id": event_id, "type": "events"}])
+
+ @parameterized.expand(
+ [
+ ("another managed event", {"filters": _alert_filters("$logs_alert_resolved")}, "filters"),
+ ("another alert", {"filters": _alert_filters(alert_id="alert-2")}, "filters"),
+ ("no alert id", {"filters": _alert_filters(properties=[])}, "filters"),
+ (
+ "another operator",
+ {
+ "filters": _alert_filters(
+ properties=[{"key": "alert_id", "value": "alert-1", "operator": "is_not", "type": "event"}]
+ )
+ },
+ "filters",
+ ),
+ (
+ "another property type",
+ {
+ "filters": _alert_filters(
+ properties=[{"key": "alert_id", "value": "alert-1", "operator": "exact", "type": "person"}]
+ )
+ },
+ "filters",
+ ),
+ ("no managed event", {"filters": _alert_filters("$pageview")}, "filters"),
+ ("soft delete", {"deleted": True}, "deleted"),
+ ]
+ )
+ def test_generic_api_cannot_change_which_alert_owns_a_managed_destination(self, _name, data, attr):
+ managed = self._create_internal_destination(_alert_filters())
+
+ patch_response = self.client.patch(f"/api/projects/{self.team.id}/hog_functions/{managed.id}/", data=data)
+
+ self.assertEqual(patch_response.status_code, status.HTTP_400_BAD_REQUEST, patch_response.json())
+ self.assertEqual(patch_response.json()["attr"], attr)
+ managed.refresh_from_db()
+ self.assertFalse(managed.deleted)
+ self.assertEqual({key: (managed.filters or {})[key] for key in ("events", "properties")}, _alert_filters())
+
+ @parameterized.expand([("$billing_alert_firing",), ("$replay_vision_alert_match",)])
+ def test_generic_api_cannot_edit_another_alert_products_destination(self, event_id):
+ managed = self._create_internal_destination(_alert_filters(event_id))
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/",
+ data={"name": "Renamed alert destination", "inputs": {"channel": {"value": "#oncall"}}},
+ )
+
+ self.assertEqual(patch_response.status_code, status.HTTP_400_BAD_REQUEST, patch_response.json())
+ self.assertIn("managed through the alert API", patch_response.json()["detail"])
+ managed.refresh_from_db()
+ self.assertEqual((managed.inputs or {})["channel"]["value"], "#alerts")
+
+ @parameterized.expand(
+ [
+ ("edit with both write scopes", "patch", "", ["hog_function:write", "logs:write"], status.HTTP_200_OK),
+ ("edit with hog function write only", "patch", "", ["hog_function:write"], status.HTTP_403_FORBIDDEN),
+ ("edit with logs write only", "patch", "", ["logs:write"], status.HTTP_403_FORBIDDEN),
+ ("restore revision", "post", "revisions/1/restore", ["hog_function:write"], status.HTTP_403_FORBIDDEN),
+ ("publish", "post", "publish/", ["hog_function:write"], status.HTTP_403_FORBIDDEN),
+ ("discard draft", "post", "discard_draft/", ["hog_function:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "rerun without logs write",
+ "post",
+ "rerun/",
+ ["hog_function:write", "person:read", "group:read"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ (
+ "rerun without the data read scopes",
+ "post",
+ "rerun/",
+ ["hog_function:write", "logs:write"],
+ status.HTTP_403_FORBIDDEN,
+ ),
+ ]
+ )
+ def test_writing_to_a_logs_alert_destination_needs_the_logs_write_scope_too(
+ self, _name, method, path, scopes, expected_status
+ ):
+ managed = self._create_internal_destination(_alert_filters())
+ key = self.create_personal_api_key_with_scopes(scopes)
+ self.client.logout()
+
+ response = getattr(self.client, method)(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/{path}",
+ data={"name": "Renamed alert destination"},
+ HTTP_AUTHORIZATION=f"Bearer {key}",
+ )
+
+ self.assertEqual(response.status_code, expected_status, response.json())
+ managed.refresh_from_db()
+ self.assertEqual(managed.name == "Renamed alert destination", expected_status == status.HTTP_200_OK)
+
+ def test_editing_a_logs_alert_destination_needs_logs_editor_access(self):
+ managed = self._create_internal_destination(_alert_filters())
+
+ with patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_resource",
+ side_effect=lambda resource, required_level=None, **_: resource != "logs",
+ ):
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/",
+ data={"name": "Renamed alert destination"},
+ )
+
+ self.assertEqual(patch_response.status_code, status.HTTP_403_FORBIDDEN, patch_response.json())
+ managed.refresh_from_db()
+ self.assertEqual(managed.name, "Alert destination")
+
+ def test_generic_api_cannot_restore_a_managed_alert_destination(self):
+ managed = self._create_internal_destination(_alert_filters(), deleted=True)
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/", data={"deleted": False}
+ )
+
+ self.assertEqual(patch_response.status_code, status.HTTP_400_BAD_REQUEST, patch_response.json())
+ self.assertEqual(patch_response.json()["attr"], "deleted")
+ managed.refresh_from_db()
+ self.assertTrue(managed.deleted)
+
+ def test_generic_api_can_test_invoke_a_managed_alert_destination(self):
+ managed = self._create_internal_destination(_alert_filters())
+ stored = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{managed.id}/").json()
+ configuration = {key: stored[key] for key in ("name", "hog", "inputs_schema", "inputs", "filters")}
+
+ with patch("products.cdp.backend.api.hog_function.create_hog_invocation_test") as mock_invocation:
+ mock_invocation.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_functions/{managed.id}/invocations/",
+ data={"configuration": configuration},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(mock_invocation.call_args.kwargs["hog_function_id"], str(managed.id))
+
+ def test_generic_api_cannot_turn_a_destination_into_a_managed_alert_destination(self):
+ destination = self._create_internal_destination(
+ {"events": [{"id": "$error_tracking_issue_created", "type": "events"}]}
+ )
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_functions/{destination.id}/",
+ data={"filters": _alert_filters()},
+ )
+
self.assertEqual(patch_response.status_code, status.HTTP_400_BAD_REQUEST, patch_response.json())
+ self.assertEqual(patch_response.json()["attr"], "filters")
self.assertIn("managed through the alert API", patch_response.json()["detail"])
def test_functions_filtered_on_all_events_are_listed_and_retrievable(self):