: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): send a webhook's added headers on native delivery (#116654)
Jimmy Zhu1231b6043f5b
diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.pyindex 25bc31898dd1..384d2d3fdcdb 100644--- a/products/alerts/backend/logic/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -5,9 +5,12 @@ from __future__ import annotationsimport refrom abc import ABC, abstractmethodfrom collections.abc import Sequence-from typing import Any, ClassVar+from typing import Any, ClassVar, Final, castfrom urllib.parse import urlsplit+from requests.exceptions import InvalidHeader+from requests.utils import check_header_validity+from products.alerts_platform.backend.facade.contracts import (DEFAULT_PAGERDUTY_REGION,DEFAULT_PAGERDUTY_SEVERITY,@@ -116,6 +119,52 @@ def pagerduty_links(spec: EventKindSpec) -> list[dict[str, str]]:return [{"href": action.url, "text": action.label} for action in spec_actions(spec)]+# Headers the native transport sets itself: the stock ones every webhook destination is built+# with, and the ones that frame the request or name the host the connection was pinned to.+_TRANSPORT_HEADER_NAMES: Final = frozenset(+ [*(name.lower() for name in WEBHOOK_HEADERS), "host", "content-length", "transfer-encoding", "connection"]+)+++# The HTTP token grammar (RFC 9110). requests accepts a space or a tab inside a name, which receivers reject.+_HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")+# A field value may hold a tab but no other control character. requests rejects only CR and LF.+_CONTROL_CHARACTER = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]")+++def _added_webhook_headers(headers: Any) -> dict[str, str]:+ """The headers a user added to a webhook destination, such as an auth token.++ A value with a `{` is a Hog template, which only the HogFunction path can render. Sending it+ unrendered would send the template text as the credential, so it is left out. So is a header+ the native client cannot send, which would otherwise fail every delivery to the destination.+ """+ if not isinstance(headers, dict):+ return {}+ added: dict[str, str] = {}+ for raw_name, raw_value in headers.items():+ if not isinstance(raw_name, str) or not isinstance(raw_value, str):+ continue+ name, value = raw_name.strip(), raw_value.strip()+ if (+ name.lower() in _TRANSPORT_HEADER_NAMES+ or "{" in value+ or not _HEADER_NAME.fullmatch(name)+ or _CONTROL_CHARACTER.search(value)+ ):+ continue+ try:+ check_header_validity((name, value))+ # http.client encodes a name as ASCII and a value as latin-1, and raises past the+ # sender's error handling on anything else.+ name.encode("ascii")+ value.encode("latin-1")+ except (InvalidHeader, UnicodeEncodeError):+ continue+ added[name] = value+ return dict(sorted(added.items()))++def _input_value(inputs: dict[str, Any], key: str) -> Any:entry = inputs.get(key)return entry.get("value") if isinstance(entry, dict) else None@@ -228,6 +277,19 @@ class WebhookDestination(_WebhookUrlDestination):template_id = "template-webhook"url_input_key = "url"+ def read(self, inputs: dict[str, Any]) -> AlertDestinationData:+ data = super().read(inputs)+ headers = _added_webhook_headers(_input_value(inputs, "headers"))+ if headers:+ data["webhook_headers"] = headers+ return data++ def redact(self, data: AlertDestinationData) -> AlertDestinationData:+ return cast(+ AlertDestinationData,+ {key: value for key, value in super().redact(data).items() if key != "webhook_headers"},+ )+def build_name(self, data: AlertDestinationData) -> str:return f"Webhook {url_hostname(data['webhook_url'])}"diff --git a/products/alerts/backend/logic/destinations.py b/products/alerts/backend/logic/destinations.pyindex 9c19358b2916..378e0ae4d875 100644--- a/products/alerts/backend/logic/destinations.py+++ b/products/alerts/backend/logic/destinations.py@@ -71,10 +71,22 @@ def alert_destination_group_key(*, template_id: str, inputs: dict[str, Any] | Noif spec is None:return AlertDestinationGroupKey(template_id, None)data = spec.read(inputs or {})- config = {key: value for key, value in data.items() if key != "type"}+ config = {key: _hashable(value) for key, value in data.items() if key != "type"}return AlertDestinationGroupKey(template_id, tuple(sorted(config.items())) if config else None)+class _FrozenMapping(tuple):+ """A dict value, such as added webhook headers, held as sorted pairs so a group key stays hashable."""+++def _hashable(value: Any) -> Any:+ return _FrozenMapping(sorted(value.items())) if isinstance(value, dict) else value+++def _thawed(value: Any) -> Any:+ return dict(value) if isinstance(value, _FrozenMapping) else value++def group_alert_destination_rows(rows: Collection[AlertDestinationRow]) -> dict[AlertDestinationGroupKey, set[UUID]]:keys_by_row = [(row.hog_function_id, alert_destination_group_key(template_id=row.template_id or "", inputs=row.inputs))@@ -113,7 +125,9 @@ def list_alert_destination_groups(spec = SPEC_BY_TEMPLATE_ID.get(key.template_id)if spec is None:continue- data = cast(AlertDestinationData, {"type": spec.type, **dict(key.config or ())})+ data = cast(+ AlertDestinationData, {"type": spec.type, **{name: _thawed(value) for name, value in key.config or ()}}+ )groups.append(AlertDestinationGroup(hog_function_ids=tuple(sorted(ids)),diff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.pyindex 8a1d5d5a127b..11dd2fc37490 100644--- a/products/alerts/backend/test/test_destination_configs.py+++ b/products/alerts/backend/test/test_destination_configs.py@@ -1,5 +1,5 @@from dataclasses import replace-from typing import Any+from typing import Any, castimport pytest@@ -227,6 +227,56 @@ def _pagerduty_config(spec: EventKindSpec, data: AlertDestinationData | None = Nreturn config.payload+class TestWebhookDestination:+ @pytest.mark.parametrize(+ "headers,read",+ [+ ({"Content-Type": "application/json", "X-PostHog-Webhook-Version": "1"}, None),+ (+ {"Content-Type": "application/json", "Authorization": "Bearer not-a-real-token"},+ {"Authorization": "Bearer not-a-real-token"},+ ),+ ({"Authorization": "Bearer {inputs.token}"}, None),+ ({"Authorization": " Bearer not-a-real-token "}, {"Authorization": "Bearer not-a-real-token"}),+ (+ {+ "": "orphaned value",+ "Host": "internal.example.com",+ "X-Note": "caf\u00e9 \u201cquoted\u201d",+ "X-Caf\u00e9": "ok",+ "X Bad": "ok",+ "X-Null": "ok\u0000bad",+ },+ None,+ ),+ ],+ ids=["stock", "added_auth_header", "templated_value", "padded_value", "unsendable"],+ )+ def test_only_headers_a_user_added_as_plain_text_are_read(+ self, headers: dict[str, str], read: dict[str, str] | None+ ) -> None:+ inputs = {"url": {"value": "https://hooks.example.com/hook"}, "headers": {"value": headers}}++ data = DESTINATION_SPECS[DestinationType.WEBHOOK].read(inputs)++ assert data.get("webhook_headers") == read++ def test_a_read_response_never_shows_stored_headers(self) -> None:+ data = cast(+ AlertDestinationData,+ {+ "type": DestinationType.WEBHOOK,+ "webhook_url": "https://hooks.example.com/hook",+ "webhook_headers": {"Authorization": "Bearer not-a-real-token"},+ },+ )++ redacted = DESTINATION_SPECS[DestinationType.WEBHOOK].redact(data)++ assert "webhook_headers" not in redacted+ assert "not-a-real-token" not in str(redacted)++class TestPagerDutyDestination:def test_firing_and_resolved_address_the_same_incident(self) -> None:firing = _pagerduty_config(TRIGGER_SPEC)["inputs"]diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pyindex 900084c2a1a6..d59aad3693e3 100644--- a/products/alerts/backend/test/test_destinations.py+++ b/products/alerts/backend/test/test_destinations.py@@ -211,6 +211,22 @@ class TestGroupAlertDestinationRows:},}+ def test_one_webhook_url_with_and_without_added_headers_is_two_groups(self) -> None:+ plain, authed = uuid4(), uuid4()+ with_header = {+ **webhook_inputs("https://example.com/hook"),+ "headers": {"value": {"Authorization": "Bearer not-a-real-token"}},+ }++ groups = group_alert_destination_rows(+ [+ AlertDestinationRow(plain, "template-webhook", webhook_inputs("https://example.com/hook")),+ AlertDestinationRow(authed, "template-webhook", with_header),+ ]+ )++ assert list(groups.values()) == [{plain}, {authed}]+def test_an_unreadable_row_collapses_its_whole_template_into_one_group(self) -> None:unreadable, readable, webhook = uuid4(), uuid4(), uuid4()diff --git a/products/alerts_platform/backend/delivery/webhook.py b/products/alerts_platform/backend/delivery/webhook.pyindex f2d6d0f2ab25..59ae3bfde8c7 100644--- a/products/alerts_platform/backend/delivery/webhook.py+++ b/products/alerts_platform/backend/delivery/webhook.py@@ -16,8 +16,8 @@ from products.alerts_platform.backend.delivery.legacy_webhook import LEGACY_WEBHfrom products.alerts_platform.backend.delivery.message import AlertMessagefrom products.alerts_platform.backend.delivery.transport import DeliveryErrorfrom products.alerts_platform.backend.delivery.webhook_url import WebhookUrlTransport-from products.alerts_platform.backend.delivery.wire import rfc3339-from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition+from products.alerts_platform.backend.delivery.wire import credential_digest, rfc3339+from products.alerts_platform.backend.facade.contracts import AlertDestinationData, AlertEventKind, AnnouncedTransitionPROVIDER: Final = "webhook"@@ -96,10 +96,18 @@ class WebhookTransport(WebhookUrlTransport):def __init__(self, legacy_body: Callable[[AlertMessage], dict[str, Any]] | None = None) -> None:self._legacy_body = legacy_body- def headers_for(self) -> dict[str, str]:- if self._legacy_body is not None:- return {"X-PostHog-Webhook-Version": LEGACY_WEBHOOK_VERSION}- return self.headers+ def channel_target(self, target: AlertDestinationData) -> str:+ headers = target.get("webhook_headers")+ if not headers:+ return super().channel_target(target)+ # Two destinations on one URL with different headers are two receivers, so each gets its+ # own delivery record. A destination without headers keeps the key it always had.+ return credential_digest(target.get("webhook_url", "") + "\n" + repr(sorted(headers.items())))++ def headers_for(self, target: AlertDestinationData) -> dict[str, str]:+ version = LEGACY_WEBHOOK_VERSION if self._legacy_body is not None else WEBHOOK_VERSION+ # The version header comes last, so a stored header cannot change which body a receiver expects.+ return {**target.get("webhook_headers", {}), "X-PostHog-Webhook-Version": version}def check_url(self, url: str) -> None:# Plain HTTP would expose the URL, which is the credential, and the alert body to anyone ondiff --git a/products/alerts_platform/backend/delivery/webhook_url.py b/products/alerts_platform/backend/delivery/webhook_url.pyindex ba3b576ee45e..f6dfd8a4cdeb 100644--- a/products/alerts_platform/backend/delivery/webhook_url.py+++ b/products/alerts_platform/backend/delivery/webhook_url.py@@ -41,7 +41,7 @@ class WebhookUrlTransport(ABC):raise DeliveryError(f"This {self.display_name} destination has no webhook URL.")self.check_url(url)post_json(- self.send_url(url), self.body_for(message), display_name=self.display_name, headers=self.headers_for()+ self.send_url(url), self.body_for(message), display_name=self.display_name, headers=self.headers_for(target))return None@@ -49,7 +49,7 @@ class WebhookUrlTransport(ABC):"""Refuses a URL this provider never issues. The SSRF check runs on every send regardless."""return None- def headers_for(self) -> dict[str, str]:+ def headers_for(self, target: AlertDestinationData) -> dict[str, str]:return self.headersdef send_url(self, url: str) -> str:diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.pyindex 70853f79ab38..aba6cfd133c6 100644--- a/products/alerts_platform/backend/facade/contracts.py+++ b/products/alerts_platform/backend/facade/contracts.py@@ -504,6 +504,9 @@ class AlertDestinationData(TypedDict):slack_channel_id: NotRequired[str]slack_channel_name: NotRequired[str]webhook_url: NotRequired[str]+ # Request headers a user added to a webhook, such as an auth token, as sorted (name, value)+ # pairs so a destination stays hashable. Secret-bearing, so never shown in a read response.+ webhook_headers: NotRequired[dict[str, str]]pagerduty_routing_key: NotRequired[str]pagerduty_severity: NotRequired[str]pagerduty_region: NotRequired[str]diff --git a/products/alerts_platform/backend/tests/test_delivery_webhook.py b/products/alerts_platform/backend/tests/test_delivery_webhook.pyindex 057aa5c7eeee..77f6398ec3f4 100644--- a/products/alerts_platform/backend/tests/test_delivery_webhook.py+++ b/products/alerts_platform/backend/tests/test_delivery_webhook.py@@ -17,6 +17,7 @@ from products.alerts_platform.backend.delivery.dispatch import deliverfrom products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStorefrom products.alerts_platform.backend.delivery.transport import DeliveryErrorfrom products.alerts_platform.backend.delivery.webhook import WebhookTransport, alertmanager_body+from products.alerts_platform.backend.delivery.wire import credential_digestfrom products.alerts_platform.backend.facade.contracts import (AlertDestinationData,AlertEventKind,@@ -138,6 +139,30 @@ class TestWebhookTransport(SimpleTestCase):assert handle is Noneassert adapter.sent[-1].headers["X-PostHog-Webhook-Version"] == "2"+ def test_a_stored_header_is_sent_but_cannot_change_the_body_version(self) -> None:+ target = cast(+ AlertDestinationData,+ {+ **TARGET,+ "webhook_headers": {"Authorization": "Bearer not-a-real-token", "X-PostHog-Webhook-Version": "9"},+ },+ )++ with pinned_post(200) as adapter:+ WebhookTransport().deliver(team_id=2, target=target, message=alert_message())++ assert adapter.sent[-1].headers["Authorization"] == "Bearer not-a-real-token"+ assert adapter.sent[-1].headers["X-PostHog-Webhook-Version"] == "2"++ def test_destinations_on_one_url_with_different_headers_are_separate_receivers(self) -> None:+ with_auth = cast(AlertDestinationData, {**TARGET, "webhook_headers": {"Authorization": "Bearer a"}})+ other_auth = cast(AlertDestinationData, {**TARGET, "webhook_headers": {"Authorization": "Bearer b"}})+ transport = WebhookTransport()++ assert len({transport.channel_target(t) for t in (TARGET, with_auth, other_auth)}) == 3+ # A destination without added headers keeps the key its existing threads were stored under.+ assert transport.channel_target(TARGET) == credential_digest(SECRET_URL)+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):