: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
fix(alerts): redact webhook urls from alert destination names (#108864)
posthog[bot]54c04a0f494d
diff --git a/products/alerts/backend/logic/destination_configs.py b/products/alerts/backend/logic/destination_configs.pyindex ae7f4b3c369b..fcf3da842082 100644--- a/products/alerts/backend/logic/destination_configs.py+++ b/products/alerts/backend/logic/destination_configs.py@@ -187,7 +187,7 @@ class WebhookDestination(_WebhookUrlDestination):url_input_key = "url"def build_name(self, data: AlertDestinationData) -> str:- return f"Webhook {data['webhook_url']}"+ return f"Webhook {url_hostname(data['webhook_url'])}"def build_inputs(self,@@ -252,6 +252,14 @@ DESTINATION_SPECS: dict[DestinationType, DestinationSpec] = {SPEC_BY_TEMPLATE_ID: dict[str, DestinationSpec] = {spec.template_id: spec for spec in DESTINATION_SPECS.values()}+def url_hostname(value: str) -> str:+ # hostname, not the raw authority: it drops any user:password@ prefix.+ try:+ return urlsplit(value).hostname or "destination"+ except ValueError:+ return "destination"++def _redact_url(value: str) -> str:"""Keep only the parts a person needs to tell two destinations apart. The path,query and userinfo carry the channel secret for every webhook-style provider."""diff --git a/products/alerts/backend/logic/destinations.py b/products/alerts/backend/logic/destinations.pyindex 7a6a982e3047..ca2cca775054 100644--- a/products/alerts/backend/logic/destinations.py+++ b/products/alerts/backend/logic/destinations.py@@ -6,7 +6,6 @@ import refrom collections.abc import Collectionfrom datetime import datetimefrom typing import Any, NamedTuple, cast-from urllib.parse import urlsplitfrom uuid import UUIDfrom django.db import transaction@@ -29,7 +28,7 @@ from products.alerts.backend.facade.contracts import (AlertDestinationValidationError,OwnedAlertDestination,)-from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID+from products.alerts.backend.logic.destination_configs import SPEC_BY_TEMPLATE_ID, url_hostnamefrom products.cdp.backend.facade.api import create_hog_functionsfrom products.cdp.backend.facade.models import HogFunction@@ -343,19 +342,18 @@ def count_active_alert_destinations(*, team_id: int, alert_id: str, allowed_even# receipt in the API, the History tooltip, or a read surface in another product — must# keep only the host.# No leading word boundary: a scheme glued to a word character (`hook_https://…`) is still-# a URL, and skipping it would leave the credential in the name. The match ends on a-# non-punctuation character, so a bracket or comma after the URL stays in the text.-_URL_IN_NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://[^\s'\"]*[^\s'\".,;:!?)\]}>]")+# a URL, and skipping it would leave the credential in the name. The match runs through an+# apostrophe and a double quote, because both are legal in a URL path and query (RFC 3986+# sub-delims) and stopping at one leaves the rest of the credential behind. It ends on a+# non-punctuation character, so a bracket or comma after the URL stays in the text, and a URL+# written inside real quotes keeps its closing quote.+_URL_IN_NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://\S*[^\s'\".,;:!?)\]}>]")_DESTINATION_NAME_SEPARATOR = " → "def _url_host(match: re.Match[str]) -> str:- # hostname, not the raw authority: it drops any user:password@ prefix.- try:- return urlsplit(match.group(0)).hostname or "destination"- except ValueError:- return "destination"+ return url_hostname(match.group(0))def redact_urls_in_name(name: str) -> str:diff --git a/products/alerts/backend/migrations/0009_redact_webhook_urls_in_destination_names.py b/products/alerts/backend/migrations/0009_redact_webhook_urls_in_destination_names.pynew file mode 100644index 000000000000..a63c2a860eee--- /dev/null+++ b/products/alerts/backend/migrations/0009_redact_webhook_urls_in_destination_names.py@@ -0,0 +1,80 @@+import re+from urllib.parse import urlsplit++from django.db import migrations++# A frozen copy of the alerts naming rule, so later edits to the product code cannot change what+# this migration did.+# An apostrophe and a double quote are both legal in a URL path and query (RFC 3986 sub-delims),+# so neither ends a URL. Both branches run through them.+# The first branch takes the URL the builder appended, which runs to the end of the name, and so+# keeps a credential that ends in a quote. The second covers a URL the alert's own name carried,+# which has text after it. It ends on a non-punctuation character, so a bracket or comma that+# closes the surrounding sentence stays in the text rather than being read as part of the URL.+_URL_IN_NAME_RE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://(?:\S*$|\S*[^\s'\".,;:!?)\]}>])")+_FILE_SYSTEM_TYPE = "hog_function/internal_destination"+++def _host(match: re.Match[str]) -> str:+ # hostname, not the raw authority: it drops any user:password@ prefix.+ try:+ return urlsplit(match.group(0)).hostname or "destination"+ except ValueError:+ return "destination"+++def _escape_path_segment(segment: str) -> str:+ return segment.replace("\\", "\\\\").replace("/", "\\/")+++def redact_webhook_urls_in_destination_names(apps, schema_editor):+ """Alert-managed webhook destinations stored the full webhook URL in their name. The URL+ path and query carry the channel credential, so keep only the host. The project tree keeps+ its own copy of the name, in the FileSystem path and in the path of every shortcut a person+ starred it into, so rewrite those copies too."""+ HogFunction = apps.get_model("cdp", "HogFunction")+ FileSystem = apps.get_model("posthog", "FileSystem")+ FileSystemShortcut = apps.get_model("posthog", "FileSystemShortcut")++ destinations = (+ HogFunction.objects.filter(+ type="internal_destination",+ template_id="template-webhook",+ name__contains="://",+ filters__properties__contains=[{"key": "alert_id"}],+ )+ .only("id", "team_id", "name")+ .order_by("id")+ )++ for destination in destinations.iterator(chunk_size=500):+ old_name = destination.name+ new_name = _URL_IN_NAME_RE.sub(_host, old_name)+ if new_name == old_name:+ continue+ HogFunction.objects.filter(id=destination.id).update(name=new_name)++ old_segment = _escape_path_segment(old_name)+ new_segment = _escape_path_segment(new_name)+ tree_rows = {"team_id": destination.team_id, "type": _FILE_SYSTEM_TYPE, "ref": str(destination.id)}+ for entry in FileSystem.objects.filter(**tree_rows, path__endswith=old_segment).only("id", "path"):+ FileSystem.objects.filter(id=entry.id).update(path=entry.path[: -len(old_segment)] + new_segment)++ # A shortcut stores the name alone rather than the whole path, because the tree builds a+ # starred item's path from its last segment.+ FileSystemShortcut.objects.filter(**tree_rows, path=old_segment).update(path=new_segment)+++class Migration(migrations.Migration):+ dependencies = [+ ("alerts", "0008_platformalert_firing_started_at_and_uuid7_pk"),+ ("cdp", "0005_repair_hogfunction_batch_export_id_index"),+ ]++ operations = [+ migrations.RunPython(+ redact_webhook_urls_in_destination_names,+ migrations.RunPython.noop,+ elidable=True,+ ),+ ]diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txtindex ca67245bba67..4d2167e651cb 100644--- a/products/alerts/backend/migrations/max_migration.txt+++ b/products/alerts/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_platformalert_firing_started_at_and_uuid7_pk+0009_redact_webhook_urls_in_destination_namesdiff --git a/products/alerts/backend/test/test_destination_configs.py b/products/alerts/backend/test/test_destination_configs.pyindex 3c2e5795ba38..ee47ec5b5ddc 100644--- a/products/alerts/backend/test/test_destination_configs.py+++ b/products/alerts/backend/test/test_destination_configs.py@@ -138,6 +138,26 @@ class TestDestinationTemplateContract:assert DESTINATION_SPECS[destination_type].read(stored_inputs) == data+ @pytest.mark.parametrize(+ "webhook_url",+ [+ "https://hooks.example.com/services/T000/B000/s3cr3t",+ "https://user:[email protected]:8443/hook?token=s3cr3t#s3cr3t",+ "not a url s3cr3t",+ ],+ )+ def test_webhook_name_never_stores_the_url_path_query_or_credentials(self, webhook_url: str) -> None:+ config = build_alert_destination_config(+ spec=DEFAULT_SPEC,+ alert_id="alert-1",+ alert_name="Signups",+ data={"type": DestinationType.WEBHOOK, "webhook_url": webhook_url},+ slack_context_elements=(),+ )++ assert "s3cr3t" not in config.payload["name"]+ assert config.payload["inputs"]["url"] == {"value": webhook_url}+def test_slack_channel_name_shapes_the_hog_function_name_and_is_never_stored_in_inputs(self) -> None:data: AlertDestinationData = {"type": DestinationType.SLACK,diff --git a/products/alerts/backend/test/test_destinations.py b/products/alerts/backend/test/test_destinations.pyindex 3586fe164370..b3d12b7f0cd5 100644--- a/products/alerts/backend/test/test_destinations.py+++ b/products/alerts/backend/test/test_destinations.py@@ -776,6 +776,18 @@ class TestRedactUrlsInName:"a https://one.example.com/s, b https://two.example.com/s","a one.example.com, b two.example.com",),+ # An apostrophe and a double quote are legal in a URL query, and stopping at one used+ # to leave the rest of the credential in the name.+ (+ "a_quote_inside_the_url_does_not_end_it",+ "Errors https://hooks.example.com/hook?token='s3cr3t fires",+ "Errors hooks.example.com fires",+ ),+ (+ "a_url_written_inside_quotes_keeps_them",+ 'named "https://example.com/p/s3cr3t" here',+ 'named "example.com" here',+ ),])def test_redacts_a_url_to_its_host(self, _name: str, name: str, expected: str) -> None:diff --git a/products/alerts/backend/test/test_migration_0009_redact_webhook_names.py b/products/alerts/backend/test/test_migration_0009_redact_webhook_names.pynew file mode 100644index 000000000000..0afb067a4636--- /dev/null+++ b/products/alerts/backend/test/test_migration_0009_redact_webhook_names.py@@ -0,0 +1,80 @@+from typing import Any++from posthog.test.base import TestMigrations++ALERT_FILTERS = {+ "source": "internal-events",+ "events": [{"id": "$logs_alert_firing", "type": "events"}],+ "properties": [{"key": "alert_id", "value": "alert-1", "operator": "exact", "type": "event"}],+}+LEAKED_NAME = "Logs — Errors (firing) → Webhook https://hooks.example.com/services/T000/B000/s3cr3t"+LEAKED_SEGMENT = LEAKED_NAME.replace("/", "\\/")+REDACTED_NAME = "Logs — Errors (firing) → Webhook hooks.example.com"+++class TestRedactWebhookUrlsInDestinationNames(TestMigrations):+ app = "alerts"+ migrate_from = "0008_platformalert_firing_started_at_and_uuid7_pk"+ migrate_to = "0009_redact_webhook_urls_in_destination_names"++ def setUpBeforeMigration(self, apps: Any) -> None:+ HogFunction = apps.get_model("cdp", "HogFunction")+ FileSystem = apps.get_model("posthog", "FileSystem")+ FileSystemShortcut = apps.get_model("posthog", "FileSystemShortcut")++ def make(name: str, filters: dict) -> Any:+ return HogFunction.objects.create(+ team_id=self.team.id,+ type="internal_destination",+ template_id="template-webhook",+ name=name,+ filters=filters,+ hog="return",+ )++ self.alert_webhook = make(LEAKED_NAME, ALERT_FILTERS)+ self.file_entry = FileSystem.objects.create(+ team_id=self.team.id,+ path="Unfiled/Destinations/" + LEAKED_SEGMENT,+ depth=3,+ type="hog_function/internal_destination",+ ref=str(self.alert_webhook.id),+ )+ self.shortcut = FileSystemShortcut.objects.create(+ team_id=self.team.id,+ user_id=self.user.id,+ path=LEAKED_SEGMENT,+ type="hog_function/internal_destination",+ ref=str(self.alert_webhook.id),+ )+ self.user_webhook_name = "My webhook https://hooks.example.com/services/T000/B000/mine"+ self.user_webhook = make(self.user_webhook_name, {"source": "internal-events", "events": []})++ self.quoted_webhook = make(+ "Logs — Errors (firing) → Webhook https://hooks.example.com/hook?token='s3cr3t",+ ALERT_FILTERS,+ )+ self.quoted_in_alert_name = make(+ "Logs — https://hooks.example.com/h?t='s3cr3t (firing) → Webhook https://hooks.example.com/other",+ ALERT_FILTERS,+ )++ def test_only_alert_managed_webhook_names_are_redacted(self) -> None:+ assert self.apps is not None+ HogFunction = self.apps.get_model("cdp", "HogFunction")+ FileSystem = self.apps.get_model("posthog", "FileSystem")+ FileSystemShortcut = self.apps.get_model("posthog", "FileSystemShortcut")++ assert HogFunction.objects.get(id=self.alert_webhook.id).name == REDACTED_NAME+ assert FileSystem.objects.get(id=self.file_entry.id).path == "Unfiled/Destinations/" + REDACTED_NAME+ # A starred destination keeps its own copy of the name.+ assert FileSystemShortcut.objects.get(id=self.shortcut.id).path == REDACTED_NAME+ assert HogFunction.objects.get(id=self.user_webhook.id).name == self.user_webhook_name+ # An apostrophe is legal in a URL query, and treating it as the end of the URL used to+ # leave everything after it in the name. That holds for the URL the builder appended and+ # for one the alert's own name carried, which has text after it.+ assert HogFunction.objects.get(id=self.quoted_webhook.id).name == REDACTED_NAME+ assert (+ HogFunction.objects.get(id=self.quoted_in_alert_name.id).name+ == "Logs — hooks.example.com (firing) → Webhook hooks.example.com"+ )diff --git a/products/alerts/frontend/logic/alertNotifications.test.ts b/products/alerts/frontend/logic/alertNotifications.test.tsindex 6777d482cf8e..671e276757ae 100644--- a/products/alerts/frontend/logic/alertNotifications.test.ts+++ b/products/alerts/frontend/logic/alertNotifications.test.ts@@ -82,7 +82,7 @@ describe('alertUtils', () => {webhookUrl: 'https://example.com/hook',},alertName: 'Spike detector',- expectedName: 'Spike detector: Webhook https://example.com/hook',+ expectedName: 'Spike detector: Webhook example.com',expectedTemplateId: 'template-webhook',expectedInputKeys: ['url', 'body'],},diff --git a/products/alerts/frontend/logic/alertNotifications.ts b/products/alerts/frontend/logic/alertNotifications.tsindex bf9429c9eba5..9665f96611ae 100644--- a/products/alerts/frontend/logic/alertNotifications.ts+++ b/products/alerts/frontend/logic/alertNotifications.ts@@ -93,6 +93,17 @@ export const buildAlertFilterConfig = (alertId: string): CyclotronJobFiltersType],})+// A webhook URL's path and query are the channel credential for every webhook-style provider, and a+// destination name reaches surfaces its configuration does not, such as the subject line of the email+// sent when the destination is disabled. The host is all a name needs to tell two destinations apart.+const webhookUrlHost = (url: string): string => {+ try {+ return new URL(url).hostname || 'destination'+ } catch {+ return 'destination'+ }+}+// Default inputs the alert wizard pre-fills for a destination, sourced from the shared sub-template// (single source of truth with the full destination picker).const subTemplateInputs = (templateId: string): NonNullable<HogFunctionType['inputs']> =>@@ -171,7 +182,7 @@ function buildAlertDestination(}case ALERT_NOTIFICATION_TYPE_WEBHOOK:return {- name: `${alertName}: Webhook ${notification.webhookUrl}`,+ name: `${alertName}: Webhook ${webhookUrlHost(notification.webhookUrl)}`,template_id: TEMPLATE_ID_BY_NOTIFICATION_TYPE[ALERT_NOTIFICATION_TYPE_WEBHOOK],inputs: {url: { value: notification.webhookUrl },