: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 microsoft teams natively (#112139)
Jimmy Zhu9b4082efaeb9
diff --git a/products/alerts_platform/backend/delivery/evaluation.py b/products/alerts_platform/backend/delivery/evaluation.pyindex 4854b13c771a..d117975cf5e7 100644--- a/products/alerts_platform/backend/delivery/evaluation.py+++ b/products/alerts_platform/backend/delivery/evaluation.py@@ -16,6 +16,7 @@ from posthog.models import Teamfrom products.alerts_platform.backend.delivery.destinations import list_alert_destination_groupsfrom products.alerts_platform.backend.delivery.dispatch import deliverfrom products.alerts_platform.backend.delivery.slack import SlackTransport+from products.alerts_platform.backend.delivery.teams import TeamsTransportfrom products.alerts_platform.backend.delivery.thread_store import DatabaseThreadStore, ThreadBusyfrom products.alerts_platform.backend.delivery.transport import DeliveryError, DeliveryTransportfrom products.alerts_platform.backend.delivery.webhook import WebhookTransport@@ -43,6 +44,7 @@ LIVE_DELIVERY_FLAG: Final = "alert-platform-live-delivery"_TRANSPORTS: Final[dict[DestinationType, type[DeliveryTransport]]] = {DestinationType.SLACK: SlackTransport,DestinationType.WEBHOOK: WebhookTransport,+ DestinationType.TEAMS: TeamsTransport,}diff --git a/products/alerts_platform/backend/delivery/teams.py b/products/alerts_platform/backend/delivery/teams.pynew file mode 100644index 000000000000..24b37c940014--- /dev/null+++ b/products/alerts_platform/backend/delivery/teams.py@@ -0,0 +1,94 @@+"""Microsoft Teams delivery, as an Adaptive Card posted to a Teams workflow URL.++The card is version 1.2, the same envelope the HogFunction template posts, so every URL shape+that template accepts takes this one too.+"""++import re+import json+from typing import Any, Final++from posthog.security.url_validation import is_microsoft_teams_webhook_url++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++PROVIDER: Final = "teams"++# Teams rejects a payload over about 28 KB, so the card's text stays under this as sent and leaves+# room for the JSON envelope. Counting characters instead would let emoji or non-Latin text past.+TEXT_BUDGET_BYTES: Final = 20_000++# The alert name and a query error are user-written, and a TextBlock or a fact renders markdown.+# Escaping links, emphasis and code stops `[x](https://...)` hiding where it goes, and a bare URL+# shows itself. Each extra character is one more stray backslash if a client shows them literally.+_MARKDOWN_SPECIALS: Final = re.compile(r"([\\`*_\[\]])")+++def escape_markdown(text: str) -> str:+ return _MARKDOWN_SPECIALS.sub(r"\\\1", text)+++def _wire_size(text: str) -> int:+ # The bytes this string costs in the request body. JSON doubles every backslash the markdown+ # escaping added, so the text's own UTF-8 length undercounts.+ return len(json.dumps(text, ensure_ascii=False).encode())+++def _clip(text: str, budget: int) -> str:+ if _wire_size(text) <= budget:+ return text+ low, high = 0, len(text)+ while low < high:+ middle = (low + high + 1) // 2+ if _wire_size(text[:middle] + "…") <= budget:+ low = middle+ else:+ high = middle - 1+ return text[:low] + "…"+++def card_for(message: AlertMessage) -> dict[str, Any]:+ headline = escape_markdown(message.headline)+ body: list[dict[str, Any]] = [{"type": "TextBlock", "text": headline, "weight": "Bolder", "wrap": True}]+ if message.details:+ # An error message can carry a whole query, so it is a detail that overflows. Each detail+ # gets an equal share, so clipping the error cannot drop the failure count after it.+ share = (TEXT_BUDGET_BYTES - _wire_size(headline)) // len(message.details)+ body.append(+ {+ "type": "FactSet",+ "facts": [+ {"title": detail.label, "value": _clip(escape_markdown(detail.value), share)}+ for detail in message.details+ ],+ }+ )+ return {+ "type": "message",+ "attachments": [+ {+ "contentType": "application/vnd.microsoft.card.adaptive",+ "contentUrl": None,+ "content": {+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",+ "type": "AdaptiveCard",+ "version": "1.2",+ "body": body,+ },+ }+ ],+ }+++class TeamsTransport(WebhookUrlTransport):+ provider = PROVIDER+ display_name = "Microsoft Teams"++ def check_url(self, url: str) -> None:+ if not is_microsoft_teams_webhook_url(url):+ raise DeliveryError("This Microsoft Teams destination's URL is not a Teams workflow URL.")++ def body_for(self, message: AlertMessage) -> dict[str, Any]:+ return card_for(message)diff --git a/products/alerts_platform/backend/tests/test_delivery_teams.py b/products/alerts_platform/backend/tests/test_delivery_teams.pynew file mode 100644index 000000000000..07226beb1be5--- /dev/null+++ b/products/alerts_platform/backend/tests/test_delivery_teams.py@@ -0,0 +1,97 @@+import json+from typing import cast++import pytest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.alerts_platform.backend.delivery.message import MessageDetail+from products.alerts_platform.backend.delivery.teams import TeamsTransport, card_for+from products.alerts_platform.backend.delivery.transport import DeliveryError+from products.alerts_platform.backend.facade.contracts import AlertDestinationData+from products.alerts_platform.backend.tests.delivery_messages import alert_message, pinned_post++TEAMS_URL = "https://prod-00.westus.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke?sig=fake"+++class TestTeamsCard(SimpleTestCase):+ def test_a_message_is_an_adaptive_card_with_a_fact_per_detail(self) -> None:+ message = alert_message(+ headline="[Checkout](https://evil.example) is firing",+ details=(MessageDetail(label="Value", value="312"), MessageDetail(label="Error", value="no *column*")),+ )++ assert card_for(message) == {+ "type": "message",+ "attachments": [+ {+ "contentType": "application/vnd.microsoft.card.adaptive",+ "contentUrl": None,+ "content": {+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",+ "type": "AdaptiveCard",+ "version": "1.2",+ "body": [+ {+ "type": "TextBlock",+ "text": r"\[Checkout\](https://evil.example) is firing",+ "weight": "Bolder",+ "wrap": True,+ },+ {+ "type": "FactSet",+ "facts": [+ {"title": "Value", "value": "312"},+ {"title": "Error", "value": r"no \*column\*"},+ ],+ },+ ],+ },+ }+ ],+ }++ def test_a_query_error_cannot_push_the_card_past_what_teams_accepts(self) -> None:+ message = alert_message(+ details=(+ MessageDetail(label="Error", value="\x01" * 50_000),+ MessageDetail(label="Query", value="\x01" * 50_000),+ MessageDetail(label="Failed checks", value="3"),+ )+ )+ target = cast(AlertDestinationData, {"type": "teams", "webhook_url": TEAMS_URL})++ with pinned_post(202) as adapter:+ TeamsTransport().deliver(team_id=2, target=target, message=message)++ sent = adapter.sent[-1].body+ assert isinstance(sent, bytes)+ facts = json.loads(sent)["attachments"][0]["content"]["body"][1]["facts"]+ assert len(sent) < 28_000+ assert facts[2] == {"title": "Failed checks", "value": "3"}+++class TestTeamsTransport(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "teams_workflow",+ TEAMS_URL,+ True,+ ),+ ("elsewhere", "https://example.com/hook", False),+ ]+ )+ def test_only_a_url_teams_issues_is_posted_to(self, _name: str, url: str, posted: bool) -> None:+ target = cast(AlertDestinationData, {"type": "teams", "webhook_url": url})++ with pinned_post(202) as adapter:+ if posted:+ TeamsTransport().deliver(team_id=2, target=target, message=alert_message())+ else:+ with pytest.raises(DeliveryError):+ TeamsTransport().deliver(team_id=2, target=target, message=alert_message())++ assert bool(adapter.sent) is posted