: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(alerts): deliver platform alerts to generic webhooks natively (#112138)
Jimmy Zhu1cdcac033e84
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex 471d2855d5c7..4854b13c771a 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -18,6 +18,7 @@ from products.alerts_platform.backend.delivery.dispatch import deliverfrom products.alerts_platform.backend.delivery.slack import SlackTransportfrom products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusyfrom products.alerts_platform.backend.delivery.transport import DeliveryError, DeliveryTransport+from products.alerts_platform.backend.delivery.webhook import WebhookTransportfrom products.alerts_platform.backend.facade.contracts import (AlertDeliveryRequest,AlertDestinationData,@@ -39,7 +40,10 @@ LIVE_DELIVERY_FLAG: Final = "alert-platform-live-delivery"# team live only when its alerts use no such type. Nothing checks this in code, and one alert# delivering natively to Slack and through a HogFunction to Discord would send two differently# worded messages for one event.-_TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.SLACK: SlackTransport}+_TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {+ DestinationType.SLACK: SlackTransport,+ DestinationType.WEBHOOK: WebhookTransport,+}@frozendiff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.pyindex fe52e14d2e09..965a14c284e9 100644--- a/products/alerts_platform/backend/delivery/message.py+++ b/products/alerts_platform/backend/delivery/message.py@@ -35,10 +35,17 @@ class MessageDetail:@frozenclass AlertMessage:- """One notification, before a provider formats it."""+ """One notification, before a provider formats it.++ `headline` and `details` are the copy, and a provider that renders text uses only those. The+ other fields are the facts the copy was written from, for a provider whose body is data.+ """headline: strdetails: tuple[MessageDetail, ...]+ configuration_id: str+ alert_name: str+ transition: AnnouncedTransitiondef _number(value: float) -> str:@@ -95,4 +102,10 @@ def build_message(announcement: EvaluationAnnouncement, transition: AnnouncedTraif transition.kind in failure_kindselse _breach_details(transition))- return AlertMessage(headline=headline.format(name=announcement.alert_name), details=tuple(details))+ return AlertMessage(+ headline=headline.format(name=announcement.alert_name),+ details=tuple(details),+ configuration_id=announcement.configuration_id,+ alert_name=announcement.alert_name,+ transition=transition,+ )diff --git a/products/alerts_platform/backend/delivery/webhook.py b/products/alerts_platform/backend/delivery/webhook.pynew file mode 100644index 000000000000..d2be69bd1840--- /dev/null+++ b/products/alerts_platform/backend/delivery/webhook.py@@ -0,0 +1,104 @@+"""Generic webhook delivery, as an Alertmanager webhook body (version 4).++Incident and on-call tools accept that body without a custom parser, which is why it replaces+the per-source bodies the HogFunction path sends. One message carries one alert, because one+transition is one message.+"""++import hashlib+from datetime import UTC, datetime+from typing import Any, ClassVar, Final+from urllib.parse import urlsplit++from django.conf import settings++from products.alerts_platform.backend.delivery.message import AlertMessage+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport+from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition++PROVIDER: Final = "webhook"++# The HogFunction path sends version 1, which is a different body. A receiver that gets both+# while a team is on the pilot tells them apart by this header.+WEBHOOK_VERSION: Final = "2"++# What Alertmanager sends as the end of an alert that has not resolved.+_NOT_ENDED: Final = "0001-01-01T00:00:00Z"++_BREACH_KINDS: Final = (AlertEventKind.FIRING, AlertEventKind.RESOLVED)+++def _rfc3339(moment: datetime) -> str:+ # The ClickHouse HTTP client returns naive datetimes. The history columns hold UTC, and+ # Alertmanager receivers reject a timestamp with no offset.+ aware = moment.replace(tzinfo=UTC) if moment.tzinfo is None else moment.astimezone(UTC)+ return aware.isoformat()+++def _fingerprint(configuration_id: str, transition: AnnouncedTransition) -> str:+ # A failed or a turned-off check is a separate alert to a receiver. With the breach's+ # fingerprint, the breach's resolve would close it, and a later breach would read as an+ # alert that is already open.+ series = "breach" if transition.kind in _BREACH_KINDS else transition.kind.value+ return hashlib.sha256(f"{configuration_id}|{transition.grouping_key}|{series}".encode()).hexdigest()[:16]+++def _annotations(message: AlertMessage) -> dict[str, str]:+ annotations = {"summary": message.headline}+ if message.details:+ annotations["description"] = "\n".join(f"{detail.label}: {detail.value}" for detail in message.details)+ if message.transition.value is not None:+ annotations["value"] = f"{message.transition.value:g}"+ if message.transition.error_message:+ annotations["error"] = message.transition.error_message+ return annotations+++def alertmanager_body(message: AlertMessage) -> dict[str, Any]:+ transition = message.transition+ configuration_id = message.configuration_id+ # Alertmanager has only these two statuses. A failed or a turned-off check goes out as+ # firing, and `posthog_event_kind` is what tells it apart from a breach.+ status = "resolved" if transition.kind == AlertEventKind.RESOLVED else "firing"+ group_labels = {"alertname": message.alert_name, "posthog_configuration_id": configuration_id}+ # The platform's own labels come last, so a source label with the same name cannot replace them.+ labels = {**transition.labels, **group_labels, "posthog_event_kind": transition.kind.value}+ annotations = _annotations(message)+ return {+ "version": "4",+ "groupKey": f"{configuration_id}:{transition.grouping_key}",+ "truncatedAlerts": 0,+ "status": status,+ "receiver": "posthog",+ "groupLabels": group_labels,+ "commonLabels": labels,+ "commonAnnotations": annotations,+ "externalURL": settings.SITE_URL,+ "alerts": [+ {+ "status": status,+ "labels": labels,+ "annotations": annotations,+ "startsAt": _rfc3339(transition.episode_started_at or transition.occurred_at),+ "endsAt": _rfc3339(transition.occurred_at) if status == "resolved" else _NOT_ENDED,+ "generatorURL": "",+ "fingerprint": _fingerprint(configuration_id, transition),+ }+ ],+ }+++class WebhookTransport(WebhookUrlTransport):+ provider = PROVIDER+ display_name = "webhook"+ headers: ClassVar[dict[str, str]] = {"X-PostHog-Webhook-Version": WEBHOOK_VERSION}++ def check_url(self, url: str) -> None:+ # Plain HTTP would expose the URL, which is the credential, and the alert body to anyone on+ # the path. Teams and Discord URLs are always HTTPS, so only the generic webhook needs this.+ if urlsplit(url).scheme != "https":+ raise DeliveryError("This webhook destination's URL must use https.")++ def body_for(self, message: AlertMessage) -> dict[str, Any]:+ return alertmanager_body(message)diff --git a/products/alerts_platform/backend/delivery/webhook_url.py b/products/alerts_platform/backend/delivery/webhook_url.pynew file mode 100644index 000000000000..770f62a6c42f--- /dev/null+++ b/products/alerts_platform/backend/delivery/webhook_url.py@@ -0,0 +1,108 @@+"""What the destinations configured as one webhook URL share: generic webhook, Teams and Discord.++The URL is the credential, because whoever holds it can post into the channel. So it never+reaches an error message, a log line or a metric label, and the thread store keys on a digest+of it. That is also why these sends do not go through `posthog/egress`: an egress scope built+from the URL becomes a metric label.++None of these providers returns a handle to reply to, so a send returns None and a resolve+posts as a new message.+"""++import json+import hashlib+from abc import ABC, abstractmethod+from typing import Any, ClassVar, Final++import requests++from posthog.security.pinned_requests import SSRFBlockedError, pinned_session++from products.alerts_platform.backend.delivery.message import AlertMessage+from products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandle+from products.alerts_platform.backend.facade.contracts import AlertDestinationData++# Both fit inside the deliver activity's 10-second start_to_close, so a stalled destination fails+# this attempt instead of outliving it. A send still in flight when Temporal starts the next+# attempt posts a second copy, because no webhook provider takes an idempotency key.+CONNECT_TIMEOUT_SECONDS: Final = 3.0+READ_TIMEOUT_SECONDS: Final = 5.0+++class WebhookUrlTransport(ABC):+ provider: str+ display_name: str+ headers: ClassVar[dict[str, str]] = {}++ def channel_target(self, target: AlertDestinationData) -> str:+ # A digest rather than the URL: the thread row would otherwise store the credential, and+ # some Teams URLs are longer than the column. A changed URL gives a new digest, so a+ # repointed destination starts a new thread.+ return hashlib.sha256(target.get("webhook_url", "").encode()).hexdigest()++ def deliver(+ self,+ *,+ team_id: int,+ target: AlertDestinationData,+ message: AlertMessage,+ in_reply_to: MessageHandle | None = None,+ ) -> MessageHandle | None:+ url = target.get("webhook_url")+ if not url:+ raise DeliveryError(f"This {self.display_name} destination has no webhook URL.")+ self.check_url(url)+ self._post(url, self.body_for(message))+ return None++ def check_url(self, url: str) -> None:+ """Refuses a URL this provider never issues. The SSRF check runs on every send regardless."""+ return None++ @abstractmethod+ def body_for(self, message: AlertMessage) -> dict[str, Any]: ...++ def _post(self, url: str, body: dict[str, Any]) -> None:+ try:+ # `pinned_session` validates the URL and connects to the IPs it validated, which+ # closes the window where DNS changes between the check and the connection.+ with pinned_session(url) as session:+ request = session.prepare_request(+ requests.Request(+ "POST",+ url,+ # UTF-8 rather than `json=`, which escapes every non-ASCII character to six+ # bytes or more. A provider limits the bytes it receives, so a body sized by+ # its UTF-8 length must be sent as UTF-8.+ data=json.dumps(body, ensure_ascii=False).encode(),+ headers={"Content-Type": "application/json", **self.headers},+ )+ )+ settings = session.merge_environment_settings(request.url, {}, True, None, None)+ # The adapter rather than `session.send`, and `stream=True` with no read. Even with+ # redirects off, the session reads a redirect's whole body to work out where it+ # points, so a destination answering 3xx with an unbounded body would fill the+ # worker's memory. The adapter returns the response unread and follows nothing.+ response = session.get_adapter(request.url or url).send(+ request,+ stream=True,+ timeout=(CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS),+ # Typed as optional, but it falls back to the session's own setting, which is True.+ verify=True if settings["verify"] is None else settings["verify"],+ cert=settings["cert"],+ proxies=settings["proxies"],+ )+ status = response.status_code+ response.close()+ except SSRFBlockedError:+ raise DeliveryError(+ f"The {self.display_name} destination URL points to an address PostHog does not send to."+ ) from None+ except requests.RequestException as error:+ # Only the class name, and `from None` to keep the original out of the failure chain:+ # the text of a `requests` error carries the whole URL.+ raise DeliveryError(+ f"The {self.display_name} destination could not be reached: {type(error).__name__}"+ ) from None+ if not 200 <= status < 300:+ raise DeliveryError(f"The {self.display_name} destination refused the message with status {status}.")diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex e8f2e60a0151..f101a6bf76b6 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -269,6 +269,8 @@ class AnnouncedTransition:condition: dict[str, Any]source_config: dict[str, Any]error_message: str | None+ # A resolve states this as the time its firing ended.+ occurred_at: datetime@frozen@@ -280,6 +282,7 @@ class EvaluationAnnouncement:to hold. It arrives with fan-in rather than waiting here empty."""+ configuration_id: stralert_name: str# Evaluation-level, so it sits here rather than on a transition: a failed check fails the# whole evaluation, and every group in one announcement saw the same count.diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.pyindex 59b1a6ddb436..25469e788036 100644--- a/products/alerts_platform/backend/logic/platform_alert_events.py+++ b/products/alerts_platform/backend/logic/platform_alert_events.py@@ -145,7 +145,7 @@ def insert_events(team_id: int, rows: Sequence[PlatformAlertEventRow]) -> int:_ANNOUNCEMENT_SQL = f"""SELECT grouping_key, kind, episode_started_at, value, labels, condition_snapshot,- source_config_snapshot, error_message, alert_name, consecutive_failures+ source_config_snapshot, error_message, occurred_at, alert_name, consecutive_failuresFROM {PLATFORM_ALERT_EVENTS_TABLE}WHERE team_id = %(team_id)sAND configuration_id = %(configuration_id)s@@ -191,13 +191,17 @@ def announcement(team_id: int, configuration_id: str, evaluation_key: str) -> Evcondition=_snapshot(condition_snapshot),source_config=_snapshot(source_config_snapshot),error_message=error_message or None,+ occurred_at=occurred_at,)- for grouping_key, kind, episode_started_at, value, labels, condition_snapshot, source_config_snapshot, error_message, _, _ in rows+ for grouping_key, kind, episode_started_at, value, labels, condition_snapshot, source_config_snapshot, error_message, occurred_at, _, _ in rows)# Evaluation-level, and the same on every row of one evaluation, so the first row carries it.- alert_name, consecutive_failures = rows[0][8], rows[0][9]+ *_, alert_name, consecutive_failures = rows[0]return EvaluationAnnouncement(- alert_name=alert_name, consecutive_failures=consecutive_failures, transitions=transitions+ configuration_id=configuration_id,+ alert_name=alert_name,+ consecutive_failures=consecutive_failures,+ transitions=transitions,)diff --git a/products/alerts_platform/backend/tests/delivery_messages.py b/products/alerts_platform/backend/tests/delivery_messages.pynew file mode 100644index 000000000000..0372d1e6bc9e--- /dev/null+++ b/products/alerts_platform/backend/tests/delivery_messages.py@@ -0,0 +1,97 @@+import io+from collections.abc import Iterator+from contextlib import contextmanager+from datetime import UTC, datetime+from typing import Any++from unittest.mock import patch++from requests import PreparedRequest, Response, Session+from requests.adapters import BaseAdapter+from requests.structures import CaseInsensitiveDict++from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail+from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition++EPISODE_STARTED = datetime(2026, 9, 30, 9, tzinfo=UTC)+OCCURRED = datetime(2026, 9, 30, 10, tzinfo=UTC)+++def announced_transition(kind: AlertEventKind = AlertEventKind.FIRING, **overrides: Any) -> AnnouncedTransition:+ fields: dict[str, Any] = {+ "grouping_key": "",+ "kind": kind,+ "episode_started_at": EPISODE_STARTED,+ "value": 300.0,+ "labels": {},+ "condition": {},+ "source_config": {},+ "error_message": None,+ "occurred_at": OCCURRED,+ }+ fields.update(overrides)+ return AnnouncedTransition(**fields)+++def alert_message(+ headline: str = "API errors is firing",+ details: tuple[MessageDetail, ...] = (),+ transition: AnnouncedTransition | None = None,+ alert_name: str = "API errors",+) -> AlertMessage:+ return AlertMessage(+ headline=headline,+ details=details,+ configuration_id="cfg-1",+ alert_name=alert_name,+ transition=transition or announced_transition(),+ )+++class UnreadBody(io.BytesIO):+ def __init__(self, content: bytes) -> None:+ super().__init__(content)+ self.bytes_read = 0++ def read(self, size: int | None = -1) -> bytes:+ chunk = super().read(size)+ self.bytes_read += len(chunk)+ return chunk+++class RecordingAdapter(BaseAdapter):+ def __init__(self, status: int, error: Exception | None, headers: dict[str, str], body: bytes) -> None:+ super().__init__()+ self.status = status+ self.error = error+ self.headers = headers+ self.body = UnreadBody(body)+ self.sent: list[PreparedRequest] = []++ def send(self, request: PreparedRequest, *args: Any, **kwargs: Any) -> Response:+ self.sent.append(request)+ if self.error:+ raise self.error+ response = Response()+ response.status_code = self.status+ response.headers = CaseInsensitiveDict(self.headers)+ response.raw = self.body+ response.url = request.url or ""+ response.request = request+ return response++ def close(self) -> None:+ return None+++@contextmanager+def pinned_post(+ status: int = 200, error: Exception | None = None, headers: dict[str, str] | None = None, body: bytes = b""+) -> Iterator[RecordingAdapter]:+ adapter = RecordingAdapter(status, error, headers or {}, body)+ session = Session()+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ with patch("products.alerts_platform.backend.delivery.webhook_url.pinned_session") as pinned_session:+ pinned_session.return_value.__enter__.return_value = session+ yield adapterdiff --git a/products/alerts_platform/backend/tests/test_delivery_dispatch.py b/products/alerts_platform/backend/tests/test_delivery_dispatch.pyindex 2e4d4c98840c..8bb3574910a0 100644--- a/products/alerts_platform/backend/tests/test_delivery_dispatch.py+++ b/products/alerts_platform/backend/tests/test_delivery_dispatch.py@@ -38,6 +38,7 @@ def _transition(condition={"threshold_count": 100, "threshold_operator": "above"},source_config={},error_message=None,+ occurred_at=FIRST_FIRING,)@@ -45,6 +46,7 @@ def _announcement(kind: AlertEventKind = AlertEventKind.FIRING, episode_started_at: datetime | None = FIRST_FIRING) -> EvaluationAnnouncement:return EvaluationAnnouncement(+ configuration_id="cfg-1",alert_name="API errors",consecutive_failures=0,transitions=(_transition(kind, episode_started_at),),@@ -161,6 +163,7 @@ class TestDeliveryDispatch(SimpleTestCase):store = RecordingThreadStore()transport = FakeTransport()announcement = EvaluationAnnouncement(+ configuration_id="cfg-1",alert_name="API errors",consecutive_failures=0,transitions=(_transition(grouping_key="checkout"), _transition(grouping_key="search")),diff --git a/products/alerts_platform/backend/tests/test_delivery_evaluation.py b/products/alerts_platform/backend/tests/test_delivery_evaluation.pyindex d80716a2372f..41448408fe23 100644--- a/products/alerts_platform/backend/tests/test_delivery_evaluation.py+++ b/products/alerts_platform/backend/tests/test_delivery_evaluation.py@@ -32,6 +32,7 @@ RESOLVED_EVENT = "$logs_alert_resolved"SLACK = cast(AlertDestinationData, {"type": DestinationType.SLACK, "slack_workspace_id": 1, "slack_channel_id": "C-1"})WEBHOOK = cast(AlertDestinationData, {"type": DestinationType.WEBHOOK, "webhook_url": "https://example.com/hook"})TEAMS = cast(AlertDestinationData, {"type": DestinationType.TEAMS, "webhook_url": "https://example.com/teams"})+UNSUPPORTED = cast(AlertDestinationData, {"type": "pagerduty"})class RecordingTransport:@@ -85,11 +86,14 @@ def _transition(kind: AlertEventKind, grouping_key: str = "") -> AnnouncedTransicondition={},source_config={},error_message=None,+ occurred_at=FIRING,)def _announcement(*transitions: AnnouncedTransition) -> EvaluationAnnouncement:- return EvaluationAnnouncement(alert_name="API errors", consecutive_failures=0, transitions=transitions)+ return EvaluationAnnouncement(+ configuration_id="cfg-1", alert_name="API errors", consecutive_failures=0, transitions=transitions+ )def _group(data: AlertDestinationData, fully_enabled: bool = True) -> AlertDestinationGroup:@@ -153,7 +157,7 @@ class TestDeliverEvaluation(APIBaseTest):def test_a_destination_with_no_transport_is_skipped_rather_than_failing_the_send(self) -> None:outcome = self._run(_announcement(_transition(AlertEventKind.FIRING)),- {FIRING_EVENT: [_group(SLACK), _group(WEBHOOK)]},+ {FIRING_EVENT: [_group(SLACK), _group(UNSUPPORTED)]},)assert [channel for channel, _ in RecordingTransport.sends] == ["C-1"]diff --git a/products/alerts_platform/backend/tests/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.pyindex 12be6660afdf..7d04fd26fb52 100644--- a/products/alerts_platform/backend/tests/test_delivery_message.py+++ b/products/alerts_platform/backend/tests/test_delivery_message.py@@ -1,3 +1,4 @@+from datetime import UTC, datetimefrom typing import Anyimport pytest@@ -22,13 +23,16 @@ def _transition(kind: AlertEventKind, **overrides: Any) -> AnnouncedTransition:"condition": CONDITION,"source_config": {},"error_message": None,+ "occurred_at": datetime(2026, 9, 30, 10, tzinfo=UTC),}fields.update(overrides)return AnnouncedTransition(**fields)def _announcement(consecutive_failures: int = 0) -> EvaluationAnnouncement:- return EvaluationAnnouncement(alert_name="API errors", consecutive_failures=consecutive_failures, transitions=())+ return EvaluationAnnouncement(+ configuration_id="cfg-1", alert_name="API errors", consecutive_failures=consecutive_failures, transitions=()+ )class TestAlertMessage:diff --git a/products/alerts_platform/backend/tests/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.pyindex dc79d6d8ee43..f9cc748369c8 100644--- a/products/alerts_platform/backend/tests/test_delivery_slack.py+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py@@ -11,12 +11,13 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integrationfrom posthog.slack.channels import MAX_HEADER_CHARS, MAX_SECTION_CHARS-from products.alerts_platform.backend.delivery.message import AlertMessage, MessageDetail+from products.alerts_platform.backend.delivery.message import MessageDetailfrom products.alerts_platform.backend.delivery.slack import SlackTransport, blocks_forfrom products.alerts_platform.backend.delivery.transport import DeliveryError, MessageHandlefrom products.alerts_platform.backend.facade.contracts import AlertDestinationData+from products.alerts_platform.backend.tests.delivery_messages import alert_message-MESSAGE = AlertMessage(+MESSAGE = alert_message(headline="API errors is firing",details=(MessageDetail(label="Value", value="300"), MessageDetail(label="Threshold", value="above 100")),)@@ -24,7 +25,7 @@ MESSAGE = AlertMessage(class TestSlackBlocks(SimpleTestCase):def test_the_headline_is_clipped_to_what_slack_accepts(self) -> None:- message = AlertMessage(headline="x" * 400, details=())+ message = alert_message(headline="x" * 400, details=())header = blocks_for(message)[0]assert len(header["text"]["text"]) <= MAX_HEADER_CHARS@@ -35,7 +36,7 @@ class TestSlackBlocks(SimpleTestCase):assert section["text"]["text"] == "*Value:* 300\n*Threshold:* above 100"def test_a_long_detail_keeps_the_body_inside_what_slack_accepts(self) -> None:- message = AlertMessage(+ message = alert_message(headline="API errors could not be checked",details=(MessageDetail(label="Error", value="x" * 5000),@@ -51,7 +52,7 @@ class TestSlackBlocks(SimpleTestCase):assert "*Failed checks:* 3" in section["text"]["text"]def test_a_query_error_cannot_speak_as_slack_markup(self) -> None:- message = AlertMessage(+ message = alert_message(headline="API errors could not be checked",details=(MessageDetail(label="Error", value="no column <!channel> in <http://x|table>"),),)@@ -62,7 +63,7 @@ class TestSlackBlocks(SimpleTestCase):assert "<!channel>" in bodydef test_a_message_without_details_carries_no_empty_section(self) -> None:- blocks = blocks_for(AlertMessage(headline="API errors is resolved", details=()))+ blocks = blocks_for(alert_message(headline="API errors is resolved", details=()))assert [block["type"] for block in blocks] == ["header"]diff --git a/products/alerts_platform/backend/tests/test_delivery_webhook.py b/products/alerts_platform/backend/tests/test_delivery_webhook.pynew file mode 100644index 000000000000..7026bace562a--- /dev/null+++ b/products/alerts_platform/backend/tests/test_delivery_webhook.py@@ -0,0 +1,208 @@+from datetime import datetime+from typing import Any, cast++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++import requests+from parameterized import parameterized++from posthog.models.scoping import team_scope+from posthog.security.pinned_requests import SSRFBlockedError++from products.alerts_platform.backend.delivery.dispatch import deliver+from products.alerts_platform.backend.delivery.message import MessageDetail+from products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.delivery.webhook import WebhookTransport, alertmanager_body+from products.alerts_platform.backend.facade.contracts import (+ AlertDestinationData,+ AlertEventKind,+ EvaluationAnnouncement,+)+from products.alerts_platform.backend.models import PlatformAlertConfiguration, PlatformAlertThread+from products.alerts_platform.backend.tests.delivery_messages import alert_message, announced_transition, pinned_post++SECRET_URL = "https://hooks.example.com/services/T000/B000/not-a-real-token"+TARGET = cast(AlertDestinationData, {"type": "webhook", "webhook_url": SECRET_URL})+++class TestAlertmanagerBody(SimpleTestCase):+ @override_settings(SITE_URL="https://us.posthog.com")+ def test_a_firing_is_one_alertmanager_alert(self) -> None:+ message = alert_message(+ headline="API errors is firing",+ details=(MessageDetail(label="Value", value="312"), MessageDetail(label="Threshold", value="> 300")),+ transition=announced_transition(+ value=312.0, grouping_key="checkout", labels={"service": "checkout", "alertname": "spoofed"}+ ),+ )++ body = alertmanager_body(message)++ labels = {+ "service": "checkout",+ "alertname": "API errors",+ "posthog_configuration_id": "cfg-1",+ "posthog_event_kind": "firing",+ }+ annotations = {"summary": "API errors is firing", "description": "Value: 312\nThreshold: > 300", "value": "312"}+ assert body == {+ "version": "4",+ "groupKey": "cfg-1:checkout",+ "truncatedAlerts": 0,+ "status": "firing",+ "receiver": "posthog",+ "groupLabels": {"alertname": "API errors", "posthog_configuration_id": "cfg-1"},+ "commonLabels": labels,+ "commonAnnotations": annotations,+ "externalURL": "https://us.posthog.com",+ "alerts": [+ {+ "status": "firing",+ "labels": labels,+ "annotations": annotations,+ "startsAt": "2026-09-30T09:00:00+00:00",+ "endsAt": "0001-01-01T00:00:00Z",+ "generatorURL": "",+ "fingerprint": body["alerts"][0]["fingerprint"],+ }+ ],+ }++ @parameterized.expand(+ [+ ("resolved", AlertEventKind.RESOLVED, "resolved", "2026-09-30T09:00:00+00:00", "2026-09-30T10:00:00+00:00"),+ ("errored", AlertEventKind.ERRORED, "firing", "2026-09-30T10:00:00+00:00", "0001-01-01T00:00:00Z"),+ ("broken", AlertEventKind.BROKEN, "firing", "2026-09-30T10:00:00+00:00", "0001-01-01T00:00:00Z"),+ ]+ )+ def test_each_kind_maps_onto_an_alertmanager_status(+ self, _name: str, kind: AlertEventKind, status: str, starts_at: str, ends_at: str+ ) -> None:+ episode = (+ None+ if kind in (AlertEventKind.ERRORED, AlertEventKind.BROKEN)+ else announced_transition().episode_started_at+ )+ body = alertmanager_body(alert_message(transition=announced_transition(kind, episode_started_at=episode)))++ alert = body["alerts"][0]+ assert (body["status"], alert["status"]) == (status, status)+ assert (alert["startsAt"], alert["endsAt"]) == (starts_at, ends_at)+ assert alert["labels"]["posthog_event_kind"] == kind.value++ def test_a_naive_timestamp_from_clickhouse_is_sent_as_utc(self) -> None:+ naive = announced_transition(+ AlertEventKind.RESOLVED,+ episode_started_at=datetime(2026, 9, 30, 9),+ occurred_at=datetime(2026, 9, 30, 10),+ )++ alert = alertmanager_body(alert_message(transition=naive))["alerts"][0]++ assert (alert["startsAt"], alert["endsAt"]) == ("2026-09-30T09:00:00+00:00", "2026-09-30T10:00:00+00:00")++ def test_a_resolve_closes_its_own_firing_and_nothing_else(self) -> None:+ def fingerprint(kind: AlertEventKind, grouping_key: str = "checkout") -> str:+ transition = announced_transition(kind, grouping_key=grouping_key)+ return alertmanager_body(alert_message(transition=transition))["alerts"][0]["fingerprint"]++ # A receiver pairs a resolve with its firing by fingerprint, so the two must match.+ assert fingerprint(AlertEventKind.FIRING) == fingerprint(AlertEventKind.RESOLVED)+ # A failed check sent as firing would otherwise be closed by the breach's resolve.+ assert fingerprint(AlertEventKind.ERRORED) != fingerprint(AlertEventKind.FIRING)+ assert fingerprint(AlertEventKind.FIRING, "search") != fingerprint(AlertEventKind.FIRING)+++class TestWebhookTransport(SimpleTestCase):+ @parameterized.expand([("ok", 200), ("accepted", 202)])+ def test_any_success_status_is_a_delivery(self, _name: str, status: int) -> None:+ with pinned_post(status) as adapter:+ handle = WebhookTransport().deliver(team_id=2, target=TARGET, message=alert_message())++ assert handle is None+ assert adapter.sent[-1].headers["X-PostHog-Webhook-Version"] == "2"++ def test_a_redirect_is_refused_without_reading_its_body(self) -> None:+ with pinned_post(302, headers={"Location": "https://elsewhere.example.com/"}, body=b"x" * 1_000_000) as adapter:+ with pytest.raises(DeliveryError):+ WebhookTransport().deliver(team_id=2, target=TARGET, message=alert_message())++ assert len(adapter.sent) == 1+ assert adapter.body.bytes_read == 0++ def test_a_plain_http_url_is_refused_before_anything_is_sent(self) -> None:+ target = cast(AlertDestinationData, {"type": "webhook", "webhook_url": "http://hooks.example.com/alerts"})++ with pinned_post() as adapter:+ with pytest.raises(DeliveryError):+ WebhookTransport().deliver(team_id=2, target=target, message=alert_message())++ assert adapter.sent == []++ @parameterized.expand(+ [+ ("refused", 410, None),+ ("redirected", 302, None),+ ("unreachable", 0, requests.ConnectionError(f"Max retries exceeded with url: {SECRET_URL}")),+ ("blocked", 0, SSRFBlockedError(f"{SECRET_URL} resolves to a private address")),+ ]+ )+ def test_a_failed_send_never_repeats_the_url(self, _name: str, status: int, error: Exception | None) -> None:+ with pinned_post(status, error):+ with pytest.raises(DeliveryError) as raised:+ WebhookTransport().deliver(team_id=2, target=TARGET, message=alert_message())++ # The URL is the credential. Temporal records the error and its cause chain.+ assert "not-a-real-token" not in str(raised.value)+ assert raised.value.__cause__ is None+++class TestWebhookThreads(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ with team_scope(self.team.id):+ self.configuration = PlatformAlertConfiguration.objects.create(+ team=self.team,+ name="API errors",+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,+ source_config={},+ threshold_count=10,+ threshold_operator="above",+ window_minutes=5,+ check_interval_minutes=10,+ )++ def _deliver(self, kind: AlertEventKind, evaluation_key: str) -> Any:+ announcement = EvaluationAnnouncement(+ configuration_id=str(self.configuration.id),+ alert_name="API errors",+ consecutive_failures=0,+ transitions=(announced_transition(kind),),+ )+ with pinned_post() as adapter, patch("products.alerts_platform.backend.delivery.dispatch.record_delivery"):+ deliver(+ transport=WebhookTransport(),+ thread_store=DatabaseThreadStore(self.team.id),+ team_id=self.team.id,+ configuration_id=str(self.configuration.id),+ evaluation_key=evaluation_key,+ target=TARGET,+ announcement=announcement,+ )+ return adapter++ def test_a_retry_posts_once_although_the_webhook_returns_nothing_to_reply_to(self) -> None:+ assert len(self._deliver(AlertEventKind.FIRING, "eval-1").sent) == 1+ assert len(self._deliver(AlertEventKind.FIRING, "eval-1").sent) == 0+ assert len(self._deliver(AlertEventKind.RESOLVED, "eval-2").sent) == 1++ with team_scope(self.team.id):+ thread = PlatformAlertThread.objects.get(configuration_id=self.configuration.id)+ assert thread.delivered_evaluation_keys == ["eval-1", "eval-2"]+ assert thread.external_ref == {}+ assert "not-a-real-token" not in thread.channel_targetdiff --git a/products/alerts_platform/backend/tests/test_platform_announcement.py b/products/alerts_platform/backend/tests/test_platform_announcement.pyindex 72908a9fb531..f7367f3e2029 100644--- a/products/alerts_platform/backend/tests/test_platform_announcement.py+++ b/products/alerts_platform/backend/tests/test_platform_announcement.py@@ -68,10 +68,12 @@ class TestAnnouncement(ClickhouseTestMixin, APIBaseTest):result = self._announcement()assert result is not None+ assert result.configuration_id == str(self.configuration.id)assert result.alert_name == "API errors"assert [t.kind for t in result.transitions] == [AlertEventKind.FIRING]transition = result.transitions[0]assert transition.episode_started_at == FIRING+ assert transition.occurred_at == OCCURREDassert transition.value == 300.0# The snapshots are what let a message state what its own check measured, however long# after the check it is rendered.