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.

chore(conversations): verify Teams Bot Framework activities through ingress (#101558)

Julian Bez0e62def316ff
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 55be3a3e6699..2ae3b140deac 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -30,6 +30,10 @@ Adding a provider is another `<provider>/` folder, not a change to the mechanism
5. **Handshake** — `provider.pre_dispatch_response(request, payload)`, for a challenge the protocol demands.
6. **Dispatch** — `provider.deliveries(request, payload, facts)`, then ownership, the forward and the consumers, all inside one wall-clock budget.
+A provider raises `InvalidPayload` for a body it refuses, from either lane, and the view answers 400 with outcome `invalid_payload`.
+`parse` raises it for a body it cannot decode, and `deliveries` for one it decoded and will not accept: that is where a provider holds a body field to the claim that signs it, which needs the payload and the facts together.
+Neither reaches a consumer.
+
Parse belongs to the provider because not every third party posts JSON: Slack's interactivity payloads and Mailgun's events are form-encoded.
It stays **after** verification, and must: a `parse` that reads `request.POST` consumes the request stream under ASGI, which leaves the signature check without the raw bytes it signs over.
@@ -40,6 +44,8 @@ A provider whose verification is a local HMAC leaves it at `None`.
A `Verification` carries the outcome and `facts`, a mapping of what the check proved on the way.
A scheme that validates a signed token knows who sent the delivery before the body is read, and `facts` is how those claims reach `deliveries`, so an incarnation can cross-check the body against what was actually signed rather than trusting a field of the body that claims the same thing.
+`BearerJwt` puts the key that signed the token there too, under `SIGNING_KEY_FACT`, because a JWKS can say what one key is allowed to sign and the token cannot: Bot Framework endorses each key for a set of channels, and Teams holds the activity's `channelId` to that.
+A body that fails that cross-check is `InvalidPayload` rather than a delivery a consumer has to distrust, because the protocol, not the product, is what says the two must agree.
An HMAC over raw bytes proves only the signature, so its `facts` are empty and `deliveries` ignores the argument.
## Schemes
@@ -63,6 +69,7 @@ Three duties fall on the incarnation rather than on `BearerJwt`, and none is enf
| `github` | `/webhooks/stamphog/github` | `stamphog` | `stamphog_review` | `products/stamphog/backend/webhook_consumers.py` |
| `slack` | `/api/conversations/v1/slack/events` | `supporthog` | `conversations_slack` | `products/conversations/backend/webhook_consumers.py` |
| `slack` | `/api/conversations/v1/slack/interactivity` | `supporthog_interactivity` | `conversations_slack_interactivity` | `products/conversations/backend/webhook_consumers.py` |
+| `teams` | `/api/conversations/v1/teams/events` | `supporthog` | `conversations_teams` | `products/conversations/backend/webhook_consumers.py` |
| `pandadoc` | `/api/legal_documents/pandadoc` | `default` | `legal_documents_signatures` | `products/legal_documents/backend/webhook_consumers.py` |
| `vapi` | `/api/user_interviews/vapi_webhook/` | `default` | `user_interviews_vapi` | `products/user_interviews/backend/webhook_consumers.py` |
| `mailgun` | `/api/conversations/v1/email/inbound` | `inbound` | none yet, the endpoint still runs its own verifier | `products/conversations/backend/services/mailgun_events.py` |
diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.py
index 1e2b14e178ec..f1a7c4b57072 100644
--- a/posthog/ingress/providers.py
+++ b/posthog/ingress/providers.py
@@ -24,6 +24,7 @@ from posthog.ingress.verify.schemes import SignatureScheme, Verification, Verifi
_INCARNATION_MODULES = (
"posthog.ingress.github.provider",
"posthog.ingress.slack.provider",
+ "posthog.ingress.teams.provider",
"posthog.ingress.pandadoc.provider",
"posthog.ingress.mailgun.provider",
"posthog.ingress.vapi.provider",
@@ -32,10 +33,17 @@ _INCARNATION_MODULES = (
class InvalidPayload(Exception):
- """A body the provider could not decode.
+ """A body the provider refuses, raised from `parse` or from `deliveries`.
- Carries the decoder's own message, which the view logs and never answers with: what the
- parser tripped over is a hint to an unauthenticated caller about how PostHog reads a body.
+ `parse` raises it for a body it cannot decode. `deliveries` raises it for a body it decoded
+ and will not accept, which is where a provider holds the body to what the signature proved:
+ Teams refuses an activity whose `serviceUrl` the token did not sign. Either way the view
+ answers 400 and no consumer runs.
+
+ Carries the provider's own message, which the view logs and never answers with: what the
+ provider tripped over is a hint to an unauthenticated caller about how PostHog reads a body.
+ A message that quotes a value the caller sent, or one the token carried, writes that value
+ into the log of an endpoint a stranger can drive, so name the field instead of either value.
"""
@@ -95,6 +103,10 @@ class WebhookProvider(ABC):
`facts` is what the signature scheme proved on the way, such as a signed token's
verified claims. It is empty for a scheme that only checks an HMAC.
+
+ Raise `InvalidPayload` for a body this provider will not accept, and the view answers
+ 400 before any consumer runs. That is how a provider holds a body field to the claim
+ that signs it, rather than handing a consumer a delivery it has to distrust.
"""
def verify(self, request: HttpRequest) -> Verification:
diff --git a/posthog/ingress/teams/README.md b/posthog/ingress/teams/README.md
new file mode 100644
index 000000000000..31b8612bd1cb
--- /dev/null
+++ b/posthog/ingress/teams/README.md
@@ -0,0 +1,83 @@
+# Microsoft Teams
+
+Bot Framework activities from Azure Bot Service, for the SupportHog Teams bot.
+
+## Headers
+
+- `Authorization` carries the bearer token, as `Bearer <jwt>`. There is no signature header.
+
+## Signature scheme
+
+`BearerJwt`, against the signing keys Bot Framework publishes.
+The accepted algorithms are RS256, RS384 and RS512, which is what the Bot Framework OpenID metadata document lists.
+A token must carry `exp`, and the clock leeway is 300 seconds.
+
+The three values the scheme needs are getters the product supplies, because the bot registration is the product's:
+
+- **The signing-key URI.** Bot Framework publishes `jwks_uri` inside its OpenID metadata document rather than at a fixed path, so the getter fetches that document, caches the result for an hour, and passes the discovered URI through `is_url_allowed` before returning it. The URI is a third party's value rather than an operator's, so it is guarded the way `posthog/api/id_jag.py` guards its own discovered JWKS URI.
+- **The audience**, which is the bot's app id from instance settings.
+- **The issuers**, which is `https://api.botframework.com` alone. The Azure AD issuer variants sign with keys that live in another JWKS, so a token carrying one of them could never verify here anyway.
+
+A JWKS fetch that fails on transport answers `UNAVAILABLE` and the view answers 503, so Bot Framework redelivers rather than losing the activity to a 403.
+
+The endpoint sits behind `TeamsEventWebhookThrottle`, a per-IP cap from `posthog.rate_limit`.
+It runs in front of verification, because the first thing an unsigned request would otherwise buy is a signing-key lookup.
+
+## Delivery id and event type
+
+The delivery id is the activity's `id`, which Bot Framework repeats across every retry of one activity, so dedup keys on it.
+The event type is the activity's `type`, so a consumer registers for `message` or `conversationUpdate`.
+
+The context carries the two verified claims: `claim_service_url` (the `serviceurl` claim) and `claim_tenant_id` (the `tid` claim).
+Both already equal the activity body, because an activity where they do not never becomes a delivery, so a consumer may read either.
+The token never reaches the context, because a consumer's context travels into its logs and its receipts.
+`tid` is absent on Bot Framework channels other than Teams, so it is an empty string there.
+
+## Apps and secrets
+
+One app, `supporthog`.
+This incarnation holds no secret: everything about the bot registration arrives through the three getters `build_teams_provider()` takes.
+Nothing under `posthog/ingress/` reads instance settings for it.
+
+## Quirks
+
+**The body repeats what the token signs, and `deliveries()` refuses the activity when the two disagree.**
+`serviceUrl` and `channelData.tenant.id` are plain JSON, so a caller holding any valid Bot Framework token could otherwise attribute an activity to another tenant, or steer the bot's outbound bearer token at a host of its choosing.
+
+Microsoft's connector authentication requires the `serviceurl` claim to be present and to equal the activity's `serviceUrl`, and its own SDKs compare the two as strings without regard to case.
+So a token that carries no `serviceurl` claim, and an activity whose `serviceUrl` the claim does not equal, are both `InvalidPayload`: 400, before ownership and before any consumer runs.
+The comparison ignores case and a trailing slash, which Teams sends in the body and not in the claim.
+`tid` is not one of Microsoft's validation rules, so it is checked when both sides carry it rather than required.
+
+**The signing key has to be endorsed for the channel the activity names.**
+One JWKS signs every Bot Framework channel, and each key lists the channels it may sign for in an `endorsements` member that `BearerJwt` carries into the facts.
+Microsoft's rule is that a bot holds an activity's `channelId` to an endorsement on the key that signed it, and rejects the activity when that endorsement is absent.
+This app serves Teams alone, so `deliveries()` refuses anything but an activity whose `channelId` is `msteams`, signed by a key whose endorsements include `msteams`.
+A key with no `endorsements` member is refused for the same reason, and no key Bot Framework publishes omits it.
+
+Without that, a token minted for another channel of the same bot registration carries the audience and the issuer the scheme requires, and the activity body alone would decide which tenant the message is attributed to.
+Microsoft answers this one with 403 and ingress answers it with the 400 it gives any refused body, which has the same effect: no consumer runs, and Bot Framework does not retry a 4xx.
+
+The `InvalidPayload` message names the field and never either value, because it lands in the log of an endpoint a stranger can drive.
+
+What stays with the consumer is the host allowlist: the claim proves Microsoft signed that URL, not that the URL is one of Microsoft's Bot Framework endpoints, and the consumer is what sends the bot's token to it.
+
+**Two certification paths must run in this region and must never be forwarded.**
+The Teams Store certification requires a reply to a command message such as "help" even from a tenant that never finished OAuth, and a proactive welcome when the bot is added to a conversation.
+Neither needs a tenant that PostHog knows, so the consumer answers `UNDECIDED` for both and the delivery runs here exactly once.
+A regular message from a tenant the other region holds answers `ELSEWHERE`, and the local run of that delivery is a no-op.
+
+**The tenant lookup runs under a bounded statement timeout, and a lookup that spends it raises rather than answering.**
+The dispatcher records that as `FAILED`, so the view answers 503 before the forward and before any consumer runs, and Bot Framework sends the activity again.
+Answering `ELSEWHERE` through a timeout would be a guess, because a lookup that never finished rules no region out, and the forward would carry the customer's message content into a region that may not hold the tenant.
+This is also what the handler before ingress did: it proxied to the other region only when the local lookup found no team, and a lookup that raised cost the request its receipt.
+
+**Bot Framework retries an activity for about ten minutes on a 5xx or a timeout, with the same activity id.**
+So `retry_status` is 503: a forward that never landed, an ownership lookup that did not answer, or a handoff that raised, must not be receipted.
+Every other status code is the default.
+
+## Consumers
+
+`conversations_teams`, on the `supporthog` app, for `message` and `conversationUpdate`.
+It declares `ownership`, so a regular message about a tenant the other region holds is forwarded there.
+See the [Endpoints table](../README.md#endpoints).
diff --git a/posthog/ingress/teams/__init__.py b/posthog/ingress/teams/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ingress/teams/provider.py b/posthog/ingress/teams/provider.py
new file mode 100644
index 000000000000..be8a394a5f83
--- /dev/null
+++ b/posthog/ingress/teams/provider.py
@@ -0,0 +1,171 @@
+"""Microsoft Teams Bot Framework activities.
+
+Bot Framework authenticates every activity with a signed bearer token rather than a shared
+secret, so this incarnation carries no secret at all: the signing-key URI, the audience and the
+issuer allowlist arrive as getters from the product that owns the bot registration.
+
+The activity body repeats in plain JSON what the token signs, and Bot Framework's connector
+authentication says the two must agree. This incarnation enforces that before a consumer sees
+the delivery, so a consumer can read `serviceUrl` off the body and act on it.
+"""
+
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
+from django.http import HttpRequest
+from django.utils import timezone
+
+from posthog.ingress.contracts import ProviderSpec, WebhookDelivery
+from posthog.ingress.providers import InvalidPayload, WebhookProvider
+from posthog.ingress.verify.jwt import SIGNING_KEY_FACT, BearerJwt
+from posthog.ingress.verify.schemes import SignatureScheme
+from posthog.rate_limit import TeamsEventWebhookThrottle
+
+# The activity types a consumer may register for. Bot Framework has no subscription model, so
+# it sends every activity type the channel produces; one this app does not act on finds no
+# consumer and is answered with the receipt.
+TEAMS_ACTIVITY_TYPES = frozenset({"message", "conversationUpdate"})
+
+SPECS = (ProviderSpec(provider="teams", app="supporthog", event_types=TEAMS_ACTIVITY_TYPES),)
+
+# The three RSA algorithms the Bot Framework OpenID metadata document publishes.
+_SIGNING_ALGORITHMS = ("RS256", "RS384", "RS512")
+
+TEAMS_CHANNEL_ID = "msteams"
+
+
+def _check_channel_endorsement(payload: Mapping[str, Any], facts: Mapping[str, Any]) -> None:
+ """Refuse an activity unless it is a Teams one, signed by a key Bot Framework endorsed for Teams.
+
+ One JWKS signs every Bot Framework channel, so the audience alone does not say the key was
+ allowed to sign this activity. Microsoft's connector authentication holds the activity's
+ `channelId` to an endorsement on the key that signed it, and rejects the activity when that
+ endorsement is absent. This app serves Teams alone, which fixes both halves at `msteams`.
+ """
+ channel_id = str(payload.get("channelId") or "")
+ if channel_id != TEAMS_CHANNEL_ID:
+ raise InvalidPayload("the activity does not name the Teams channel")
+
+ signing_key = facts.get(SIGNING_KEY_FACT)
+ endorsements = signing_key.get("endorsements") if isinstance(signing_key, Mapping) else None
+ # A list, never a bare string: `in` over a string matches a substring, which would accept a
+ # key endorsed for a channel whose name merely contains this one.
+ if not isinstance(endorsements, list) or channel_id not in endorsements:
+ raise InvalidPayload("the signing key does not endorse the activity's channel")
+
+
+def _body_tenant_id(payload: Mapping[str, Any]) -> str:
+ channel_data = payload.get("channelData")
+ channel_data = channel_data if isinstance(channel_data, Mapping) else {}
+ tenant = channel_data.get("tenant")
+ tenant = tenant if isinstance(tenant, Mapping) else {}
+ return str(tenant.get("id") or "")
+
+
+def _matched_service_url(payload: Mapping[str, Any], facts: Mapping[str, Any]) -> str:
+ """The activity's `serviceUrl`, once the token proves the issuer signed that same URL.
+
+ Bot Framework's connector authentication requires the `serviceurl` claim to be present and
+ to equal the activity's `serviceUrl`, and its own SDKs compare the two as strings without
+ regard to case. The claim is what makes the body field safe to use: the bot sends its bearer
+ token to that URL, so a caller holding any valid Bot Framework token could otherwise point
+ the credential at a host of its choosing.
+
+ Trailing slashes are stripped from both sides before the comparison, because Teams sends the
+ URL with one in the body and without one in the claim.
+ """
+ claim_service_url = str(facts.get("serviceurl") or "").rstrip("/")
+ if not claim_service_url:
+ raise InvalidPayload("the token carries no serviceurl claim")
+
+ body_service_url = str(payload.get("serviceUrl") or "").rstrip("/")
+ if body_service_url.casefold() != claim_service_url.casefold():
+ raise InvalidPayload("serviceUrl does not match the signed claim")
+ return body_service_url
+
+
+class TeamsProvider(WebhookProvider):
+ provider = "teams"
+ # The endpoint is public and its verification ends in a signing-key lookup, so an unsigned
+ # request is expensive. The cap has to be reached before verification, which is where the
+ # view runs it.
+ throttle_class = TeamsEventWebhookThrottle
+ # Bot Framework retries an activity for about ten minutes on a 5xx or a timeout, with the
+ # same activity id. A forward that never landed, or a handoff that raised, must therefore
+ # answer a 5xx rather than the receipt, or the activity is lost.
+ retry_status = 503
+
+ def __init__(
+ self,
+ *,
+ app: str = "supporthog",
+ jwks_uri_getter: Callable[[], str | None],
+ audience_getter: Callable[[], str | None],
+ issuers_getter: Callable[[], frozenset[str]],
+ ) -> None:
+ self.app = app
+ self._scheme = BearerJwt(
+ jwks_uri_getter=jwks_uri_getter,
+ audience_getter=audience_getter,
+ issuers_getter=issuers_getter,
+ algorithms=_SIGNING_ALGORITHMS,
+ )
+
+ def scheme(self) -> SignatureScheme:
+ return self._scheme
+
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ if not isinstance(payload, Mapping):
+ return ()
+
+ _check_channel_endorsement(payload, facts)
+ service_url = _matched_service_url(payload, facts)
+ # Microsoft's token validation rules do not list `tid`, so it is checked when both sides
+ # carry it rather than required. `serviceurl` is on that list, and is required, because a
+ # caller who holds any valid Bot Framework token would otherwise choose the host the
+ # bot's own bearer token is sent to.
+ claim_tenant_id = str(facts.get("tid") or "")
+ body_tenant_id = _body_tenant_id(payload)
+ if claim_tenant_id and body_tenant_id and claim_tenant_id != body_tenant_id:
+ raise InvalidPayload("channelData.tenant.id does not match the signed claim")
+
+ activity_id = payload.get("id")
+ # The token itself never leaves the scheme: the context is handed to a consumer and
+ # travels into its logs and its receipts. Both values now equal the body, so a consumer
+ # may read either.
+ context = {
+ "claim_tenant_id": claim_tenant_id,
+ "claim_service_url": service_url,
+ }
+ return (
+ WebhookDelivery(
+ provider=self.provider,
+ app=self.app,
+ delivery_id=str(activity_id) if isinstance(activity_id, str) and activity_id else None,
+ event_type=str(payload.get("type", "")),
+ payload=payload,
+ received_at=timezone.now(),
+ context=context,
+ ),
+ )
+
+
+def build_teams_provider(
+ *,
+ jwks_uri_getter: Callable[[], str | None],
+ audience_getter: Callable[[], str | None],
+ issuers_getter: Callable[[], frozenset[str]],
+ app: str = "supporthog",
+) -> TeamsProvider:
+ """The bot registration belongs to the product, so its three verification values are passed in.
+
+ `jwks_uri_getter` is called on every delivery. Bot Framework publishes its `jwks_uri` inside
+ an OpenID metadata document, so that getter owns the discovery, the cache for it, and the
+ allowlist check on a URI that came out of a remote document.
+ """
+ return TeamsProvider(
+ app=app,
+ jwks_uri_getter=jwks_uri_getter,
+ audience_getter=audience_getter,
+ issuers_getter=issuers_getter,
+ )
diff --git a/posthog/ingress/test/test_teams.py b/posthog/ingress/test/test_teams.py
new file mode 100644
index 000000000000..22247d8c1ce5
--- /dev/null
+++ b/posthog/ingress/test/test_teams.py
@@ -0,0 +1,174 @@
+import json
+import time
+from types import SimpleNamespace
+from typing import Any
+
+from unittest.mock import Mock, patch
+
+from django.test import RequestFactory, SimpleTestCase
+
+import jwt
+from cryptography.hazmat.primitives.asymmetric import rsa
+from parameterized import parameterized
+
+from posthog.ingress.contracts import DeliveryDispatch, DeliveryOwnership
+from posthog.ingress.teams.provider import build_teams_provider
+from posthog.ingress.verify.jwt import _JWKS_CLIENTS
+from posthog.ingress.verify.schemes import VerificationOutcome
+from posthog.ingress.views import build_webhook_view
+
+URL = "/api/conversations/v1/teams/events"
+JWKS_URI = "https://login.botframework.com/v1/.well-known/keys"
+APP_ID = "00000000-0000-0000-0000-000000000001"
+ISSUER = "https://api.botframework.com"
+SERVICE_URL = "https://smba.trafficmanager.net/teams/"
+TENANT_ID = "tenant-abc"
+
+TEAMS_ENDORSED_KEY = {"endorsements": ["msteams"]}
+
+ACTIVITY = {
+ "type": "message",
+ "id": "act-123",
+ "channelId": "msteams",
+ "text": "I have an issue",
+ "serviceUrl": SERVICE_URL,
+ "channelData": {"tenant": {"id": TENANT_ID}},
+}
+
+
+class TestTeamsProvider(SimpleTestCase):
+ private_key: rsa.RSAPrivateKey
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ super().setUpClass()
+ cls.private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+
+ def setUp(self) -> None:
+ # The client map is module-global, so a test must not inherit another test's clients.
+ _JWKS_CLIENTS.clear()
+ self.addCleanup(_JWKS_CLIENTS.clear)
+ self.jwks_uri_calls = 0
+ self.provider = build_teams_provider(
+ jwks_uri_getter=self._jwks_uri,
+ audience_getter=lambda: APP_ID,
+ issuers_getter=lambda: frozenset({ISSUER}),
+ )
+ self.dispatcher = Mock()
+ self.dispatcher.ownership_of.return_value = (DeliveryOwnership.UNDECIDED, ())
+ self.dispatcher.dispatch.return_value = DeliveryDispatch()
+ patcher = patch("posthog.ingress.views.get_dispatcher", return_value=self.dispatcher)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _jwks_uri(self) -> str:
+ self.jwks_uri_calls += 1
+ return JWKS_URI
+
+ def _token(self, **claims: Any) -> str:
+ payload: dict[str, Any] = {
+ "iss": ISSUER,
+ "aud": APP_ID,
+ "serviceurl": SERVICE_URL,
+ "tid": TENANT_ID,
+ "exp": int(time.time()) + 300,
+ **claims,
+ }
+ present = {key: value for key, value in payload.items() if value is not None}
+ return jwt.encode(present, self.private_key, algorithm="RS256")
+
+ def _request(self, activity: dict[str, Any], token: str | None) -> Any:
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ return RequestFactory().post(URL, data=json.dumps(activity), content_type="application/json", headers=headers)
+
+ def _signing_key(self, jwk: dict[str, Any] | None = None) -> Any:
+ # The JWKS fetch is the only boundary mocked here; the decode below it is the real one.
+ key = SimpleNamespace(
+ key=self.private_key.public_key(),
+ _jwk_data=TEAMS_ENDORSED_KEY if jwk is None else jwk,
+ )
+ return patch.object(jwt.PyJWKClient, "get_signing_key_from_jwt", return_value=key)
+
+ def _deliveries(self, activity: dict[str, Any], token: str) -> Any:
+ request = self._request(activity, token)
+ with self._signing_key():
+ verification = self.provider.verify(request)
+ self.assertEqual(verification.outcome, VerificationOutcome.VERIFIED)
+ return self.provider.deliveries(request, self.provider.parse(request), verification.facts)
+
+ def _view_response(self, activity: dict[str, Any], token: str, jwk: dict[str, Any] | None = None) -> Any:
+ with self._signing_key(jwk):
+ return build_webhook_view(self.provider)(self._request(activity, token))
+
+ def test_the_claims_a_consumer_reads_reach_the_delivery(self) -> None:
+ deliveries = self._deliveries(ACTIVITY, self._token())
+
+ self.assertEqual(len(deliveries), 1)
+ delivery = deliveries[0]
+ self.assertEqual(delivery.app, "supporthog")
+ # The activity type, because a consumer registers for `message` or `conversationUpdate`.
+ self.assertEqual(delivery.event_type, "message")
+ self.assertEqual(delivery.delivery_id, "act-123")
+ self.assertEqual(delivery.context["claim_tenant_id"], TENANT_ID)
+ self.assertEqual(delivery.context["claim_service_url"], SERVICE_URL.rstrip("/"))
+ # The token is a credential and the context travels into a consumer's logs.
+ self.assertNotIn("Bearer", json.dumps(dict(delivery.context)))
+
+ @parameterized.expand(
+ [
+ # Bot Framework requires the claim, and the bot sends its bearer token to whatever
+ # the body names, so a token without it must not choose that host.
+ ("a token that carries no serviceurl claim", {"serviceurl": None}, {}, None),
+ ("a serviceUrl the claim does not name", {}, {"serviceUrl": "https://attacker.example.com/"}, None),
+ ("an empty serviceUrl", {}, {"serviceUrl": ""}, None),
+ ("a tenant the claim does not name", {}, {"channelData": {"tenant": {"id": "other-tenant"}}}, None),
+ ("an activity from another channel", {}, {"channelId": "directline"}, None),
+ ("an activity that names no channel", {}, {"channelId": ""}, None),
+ ("a key endorsed for another channel", {}, {}, {"endorsements": ["directline"]}),
+ ("a key that carries no endorsements", {}, {}, {}),
+ ]
+ )
+ def test_an_activity_the_token_does_not_back_is_refused_before_dispatch(
+ self, _name: str, claims: dict[str, Any], activity_overrides: dict[str, Any], jwk: dict[str, Any] | None
+ ) -> None:
+ response = self._view_response({**ACTIVITY, **activity_overrides}, self._token(**claims), jwk=jwk)
+
+ self.assertEqual(response.status_code, 400)
+ self.dispatcher.ownership_of.assert_not_called()
+ self.dispatcher.dispatch.assert_not_called()
+
+ @parameterized.expand(
+ [
+ # Microsoft's own SDKs compare the two as strings without regard to case.
+ ("a claim in another case", "https://SMBA.trafficmanager.net/teams/"),
+ # Teams sends the URL with a trailing slash in the body and without one in the claim.
+ ("a claim without the body's trailing slash", "https://smba.trafficmanager.net/teams"),
+ ]
+ )
+ def test_a_claim_that_names_the_same_url_is_accepted(self, _name: str, claim_service_url: str) -> None:
+ deliveries = self._deliveries(ACTIVITY, self._token(serviceurl=claim_service_url))
+
+ self.assertEqual(len(deliveries), 1)
+ # The body's spelling, because that is what the consumer sends the bot's token to.
+ self.assertEqual(deliveries[0].context["claim_service_url"], SERVICE_URL.rstrip("/"))
+
+ def test_an_activity_without_an_id_is_delivered_with_nothing_for_dedup_to_key_on(self) -> None:
+ activity = {key: value for key, value in ACTIVITY.items() if key != "id"}
+
+ delivery = self._deliveries(activity, self._token())[0]
+
+ self.assertIsNone(delivery.delivery_id)
+
+ def test_the_throttle_refuses_a_request_before_it_buys_a_signing_key_lookup(self) -> None:
+ throttle_class = self.provider.throttle_class
+ assert throttle_class is not None
+
+ with (
+ patch.object(throttle_class, "allow_request", return_value=False),
+ patch.object(throttle_class, "wait", return_value=None),
+ ):
+ response = self._view_response(ACTIVITY, self._token())
+
+ self.assertEqual(response.status_code, 429)
+ # The getter is what discovers the signing keys, so an unsigned flood must not reach it.
+ self.assertEqual(self.jwks_uri_calls, 0)
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index 4f014bc7f241..e63d717cd8af 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -10,9 +10,10 @@ from django.test import SimpleTestCase
import jwt
from cryptography.hazmat.primitives.asymmetric import rsa
+from jwt.algorithms import RSAAlgorithm
from parameterized import parameterized
-from posthog.ingress.verify.jwt import _JWKS_CLIENTS, BearerJwt, _jwks_client
+from posthog.ingress.verify.jwt import _JWKS_CLIENTS, SIGNING_KEY_FACT, BearerJwt, _jwks_client
from posthog.ingress.verify.schemes import HmacSha256, SnsSignature, Verification, VerificationOutcome
SECRET = "s3cret"
@@ -295,6 +296,23 @@ class TestBearerJwt(SimpleTestCase):
headers = {"Authorization": "Bearer " + token}
self.assertEqual(self._verify(self._scheme(), headers).outcome, VerificationOutcome.INVALID)
+ def test_the_key_that_signed_the_token_reaches_deliveries_with_what_the_jwks_published(self) -> None:
+ # A real PyJWKClient over a real JWKS document, so a PyJWT release that stops carrying the
+ # members an incarnation reads fails here rather than at a webhook endpoint.
+ published = {
+ **RSAAlgorithm.to_jwk(self.private_key.public_key(), as_dict=True),
+ "kid": KEY_ID,
+ "endorsements": ["msteams"],
+ }
+ headers = {"Authorization": "Bearer " + self._token()}
+
+ with patch.object(jwt.PyJWKClient, "fetch_data", return_value={"keys": [published]}):
+ verification = self._scheme().verify(body=BODY, headers=headers)
+
+ self.assertEqual(verification.outcome, VerificationOutcome.VERIFIED)
+ self.assertEqual(verification.facts[SIGNING_KEY_FACT]["endorsements"], ["msteams"])
+ self.assertEqual(verification.facts[SIGNING_KEY_FACT]["kid"], KEY_ID)
+
def test_rejects_a_tampered_signature(self) -> None:
header, payload, signature = self._token().split(".")
# The first character, not the last: base64 drops the last one's padding bits, so
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index beb8fefdd5bd..9177c4053999 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -31,7 +31,7 @@ from posthog.ingress.dispatch.forward import HOST_IDENTIFYING_HEADERS, forward_t
from posthog.ingress.dispatch.registry import ConsumerRegistry
from posthog.ingress.github.provider import GitHubProvider, build_github_provider
from posthog.ingress.pandadoc.provider import build_pandadoc_provider
-from posthog.ingress.providers import WebhookProvider
+from posthog.ingress.providers import InvalidPayload, WebhookProvider
from posthog.ingress.slack.provider import build_slack_provider
from posthog.ingress.vapi.provider import VapiProvider
from posthog.ingress.verify.schemes import Verification, VerificationOutcome
@@ -103,6 +103,13 @@ class _ScopedThrottleGitHubProvider(GitHubProvider):
throttle_class = ScopedRateThrottle
+class _RefusingDeliveriesGitHubProvider(GitHubProvider):
+ # Stands in for a provider that holds the body to what the signature proved, the way Teams
+ # refuses an activity whose `serviceUrl` the token did not sign.
+ def deliveries(self, request: HttpRequest, payload: Any, facts: Mapping[str, Any]) -> Sequence[WebhookDelivery]:
+ raise InvalidPayload("installation id does not match the signed claim")
+
+
class _FormBodyGitHubProvider(GitHubProvider):
# Stands in for a provider that posts a form rather than JSON, the way Slack's interactivity
# payloads and Mailgun's events do.
@@ -350,6 +357,21 @@ class TestWebhookView(SimpleTestCase):
self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], ["verify_unavailable"])
self.dispatcher.dispatch.assert_not_called()
+ def test_a_body_deliveries_refuses_is_400_and_reaches_no_consumer(self) -> None:
+ body = b'{"action":"opened"}'
+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
+
+ with (
+ patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET),
+ patch("posthog.ingress.views.logger") as logger,
+ ):
+ response = build_webhook_view(_RefusingDeliveriesGitHubProvider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 400)
+ self.dispatcher.dispatch.assert_not_called()
+ self.dispatcher.ownership_of.assert_not_called()
+ self.assertEqual(logger.warning.call_args.args[0], "ingress_delivery_invalid_payload")
+
def test_slack_url_verification_echoes_the_challenge_before_dispatch(self) -> None:
body = json.dumps({"type": "url_verification", "challenge": "abc123"}).encode()
timestamp = "1789000000"
diff --git a/posthog/ingress/verify/jwt.py b/posthog/ingress/verify/jwt.py
index f1babcb08d14..6bda01c6c8a8 100644
--- a/posthog/ingress/verify/jwt.py
+++ b/posthog/ingress/verify/jwt.py
@@ -1,6 +1,7 @@
"""The bearer-token scheme: a provider that authenticates with a JWT rather than an HMAC."""
from collections.abc import Callable, Mapping
+from typing import Any
import jwt
import structlog
@@ -18,6 +19,20 @@ _JWKS_FETCH_TIMEOUT_SECONDS = 10
# by the incarnations mounted in the process, which is why nothing evicts here.
_JWKS_CLIENTS: dict[str, jwt.PyJWKClient] = {}
+# The scheme writes this fact after the claims, so a token that carries a claim of the same name
+# cannot put its own value here.
+SIGNING_KEY_FACT = "signing_key"
+
+
+def _signing_key_members(signing_key: jwt.PyJWK) -> Mapping[str, Any]:
+ """The key as the JWKS published it, including the members PyJWT does not model.
+
+ PyJWT keeps the decoded JWK on the key object and offers no accessor for it, so this reads the
+ attribute it holds it in. `test_verify.py` pins that against a real JWKS document.
+ """
+ members = getattr(signing_key, "_jwk_data", None)
+ return members if isinstance(members, Mapping) else {}
+
def _jwks_client(jwks_uri: str) -> jwt.PyJWKClient:
client = _JWKS_CLIENTS.get(jwks_uri)
@@ -39,7 +54,9 @@ class BearerJwt:
The verified claims become `facts`, because a signed token proves more than "this is really
them". It names the sender and the audience, so `deliveries` can hold the body to what the
- issuer actually signed rather than to a field of the body that claims the same thing.
+ issuer actually signed rather than to a field of the body that claims the same thing. The key
+ that signed it joins them under `SIGNING_KEY_FACT`, because a JWKS can say what one key is
+ allowed to sign and the token cannot.
"""
jwks_uri_getter: Callable[[], str | None]
@@ -104,4 +121,7 @@ class BearerJwt:
logger.warning("ingress_jwt_rejected", error_type=type(error).__name__)
return Verification(outcome=VerificationOutcome.INVALID)
- return Verification(outcome=VerificationOutcome.VERIFIED, facts=claims)
+ return Verification(
+ outcome=VerificationOutcome.VERIFIED,
+ facts={**claims, SIGNING_KEY_FACT: _signing_key_members(signing_key)},
+ )
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 427190b369ad..33f769375ae9 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -42,8 +42,10 @@ class Verification:
A scheme that checks a signed token learns more than "this is really them": the claims it
validated name the sender and the audience. `facts` carries those to `deliveries`, so an
incarnation can cross-check the body against what was actually signed, rather than trusting
- a field of the body that says the same thing. An HMAC over raw bytes proves nothing beyond
- the signature and leaves `facts` empty.
+ a field of the body that says the same thing. A fact is not always a claim: `BearerJwt` also
+ puts the key that signed the token there, because a JWKS can say what one key is allowed to
+ sign and the token cannot. An HMAC over raw bytes proves nothing beyond the signature and
+ leaves `facts` empty.
"""
outcome: VerificationOutcome
diff --git a/posthog/ingress/views.py b/posthog/ingress/views.py
index 5632236bf784..bda3f2ac5b33 100644
--- a/posthog/ingress/views.py
+++ b/posthog/ingress/views.py
@@ -107,12 +107,7 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
reason = "Invalid signature" if provider.explains_rejections else ""
return HttpResponse(reason, status=provider.invalid_signature_status)
- # Parse after verification, and keep that order: a provider that reads a form body
- # overrides `parse` and reads `request.POST`, and under ASGI that read consumes the
- # stream, so `request.body` is no longer available to the signature check afterwards.
- try:
- payload = provider.parse(request)
- except InvalidPayload as error:
+ def refuse_payload(error: InvalidPayload) -> HttpResponse:
observe_delivery(provider=provider.provider, app=provider.app, outcome="invalid_payload")
logger.warning(
"ingress_delivery_invalid_payload",
@@ -122,13 +117,27 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Htt
)
return HttpResponse("Invalid JSON", status=400)
+ # Parse after verification, and keep that order: a provider that reads a form body
+ # overrides `parse` and reads `request.POST`, and under ASGI that read consumes the
+ # stream, so `request.body` is no longer available to the signature check afterwards.
+ try:
+ payload = provider.parse(request)
+ except InvalidPayload as error:
+ return refuse_payload(error)
+
handshake = provider.pre_dispatch_response(request, payload)
if handshake is not None:
observe_delivery(provider=provider.provider, app=provider.app, outcome="accepted")
return handshake
dispatcher = get_dispatcher()
- deliveries = provider.deliveries(request, payload, verification.facts)
+ # `deliveries` refuses a body the same way `parse` does, because a provider can only
+ # hold the body to the verified claims once it has both. Teams does: an activity whose
+ # `serviceUrl` the token did not sign never becomes a delivery.
+ try:
+ deliveries = provider.deliveries(request, payload, verification.facts)
+ except InvalidPayload as error:
+ return refuse_payload(error)
# One budget for the whole request, not one per delivery: PandaDoc turns a batched body
# into many deliveries, and a budget each would hold the request open for the sum. It
# starts before the ownership lookups, which read the database and forward on the same
diff --git a/products/conversations/backend/api/teams_events.py b/products/conversations/backend/api/teams_events.py
index 6a03353260ff..dfaa36107fa6 100644
--- a/products/conversations/backend/api/teams_events.py
+++ b/products/conversations/backend/api/teams_events.py
@@ -1,198 +1,18 @@
"""Microsoft Teams Bot Framework messaging endpoint for SupportHog."""
-import json
-from typing import Any, cast
+from posthog.ingress.teams.provider import build_teams_provider
+from posthog.ingress.views import build_webhook_view
-from django.conf import settings
-from django.http import HttpRequest, HttpResponse
-from django.views.decorators.csrf import csrf_exempt
-
-import structlog
-from rest_framework.request import Request as DRFRequest
-
-from posthog.models.team import Team
-from posthog.rate_limit import TeamsEventWebhookThrottle
-from posthog.regions import is_primary_region
-
-from products.conversations.backend.models import TeamConversationsTeamsConfig
-from products.conversations.backend.services.region_routing import proxy_to_secondary_region
from products.conversations.backend.support_teams import (
- get_bot_from_id,
- is_trusted_teams_service_url,
- validate_teams_request,
+ get_botframework_issuers,
+ get_botframework_jwks_uri,
+ get_teams_app_id,
)
-from products.conversations.backend.tasks.teams import is_duplicate_teams_event, process_teams_event, send_teams_help
-from products.conversations.backend.teams import is_bot_added_event, is_command_message
-
-logger = structlog.get_logger(__name__)
-
-TEAMS_MESSAGE_TYPES = {"message"}
-
-
-def _team_for_teams_tenant(tenant_id: str) -> Team | None:
- config = (
- TeamConversationsTeamsConfig.objects.filter(teams_tenant_id=tenant_id, teams_graph_access_token__isnull=False)
- .select_related("team")
- .first()
- )
- return config.team if config else None
-
-
-def _claims_match_activity(claims: dict, activity: dict) -> bool:
- """
- Cross-check verified JWT claims against the plaintext activity body.
-
- The Bot Framework JWT authenticates the caller, but tenant attribution and
- the outbound bot-token target URL both come from JSON fields in the
- activity body (``channelData.tenant.id`` and ``serviceUrl``). Without
- tying them back to signature-verified claims, anyone in possession of a
- legitimate Bot Framework token (e.g. replay) could craft an activity that
- attributes messages to a different PostHog-connected tenant, or steer the
- bot's bearer token to a non-Microsoft URL.
-
- Per Microsoft's Bot Framework authentication spec, whenever a claim is
- present it MUST equal the activity field. Missing claims are tolerated
- (the allowlist check on ``serviceUrl`` still applies).
- """
- body_tenant_id = ((activity.get("channelData") or {}).get("tenant") or {}).get("id", "")
- claim_tenant_id = claims.get("tid") or ""
- if claim_tenant_id and body_tenant_id and claim_tenant_id != body_tenant_id:
- logger.warning(
- "supporthog_teams_tid_mismatch",
- body_tenant_id=body_tenant_id,
- claim_tenant_id=claim_tenant_id,
- )
- return False
-
- body_service_url = (activity.get("serviceUrl") or "").rstrip("/")
- if body_service_url and not is_trusted_teams_service_url(body_service_url):
- logger.warning("supporthog_teams_untrusted_service_url", service_url=body_service_url)
- return False
-
- claim_service_url = (claims.get("serviceurl") or "").rstrip("/")
- if claim_service_url and body_service_url and claim_service_url != body_service_url:
- logger.warning(
- "supporthog_teams_serviceurl_mismatch",
- body_service_url=body_service_url,
- claim_service_url=claim_service_url,
- )
- return False
-
- return True
-
-
-def _route_activity_to_relevant_region(request: HttpRequest, activity: dict, claims: dict) -> None:
- activity_type = activity.get("type", "")
- channel_data = activity.get("channelData") or {}
- tenant_id = (channel_data.get("tenant") or {}).get("id", "")
- activity_id = activity.get("id", "")
- logger.info(
- "supporthog_teams_activity",
- activity_type=activity_type,
- tenant_id=tenant_id,
- channel_id=channel_data.get("channel", {}).get("id") if isinstance(channel_data.get("channel"), dict) else None,
+teams_event_handler = build_webhook_view(
+ build_teams_provider(
+ jwks_uri_getter=get_botframework_jwks_uri,
+ audience_getter=get_teams_app_id,
+ issuers_getter=get_botframework_issuers,
)
-
- if activity_type not in TEAMS_MESSAGE_TYPES:
- return
-
- if not _claims_match_activity(claims, activity):
- return
-
- team = _team_for_teams_tenant(tenant_id) if tenant_id else None
-
- if team and not (settings.DEBUG and is_primary_region(request)):
- cast(Any, process_teams_event).delay(
- activity=activity,
- tenant_id=tenant_id,
- activity_id=activity_id,
- )
- elif is_primary_region(request):
- proxy_to_secondary_region(request, log_prefix="supporthog_teams")
- else:
- logger.warning("supporthog_teams_no_team_any_region", tenant_id=tenant_id)
-
-
-@csrf_exempt
-def teams_event_handler(request: HttpRequest) -> HttpResponse:
- """
- Handle incoming Bot Framework activities from Microsoft Teams.
-
- Validates the JWT bearer token, routes to the correct region,
- and dispatches message activities to a Celery task.
- """
- if request.method != "POST":
- return HttpResponse(status=405)
-
- # IP-based throttle in front of the JWT/JWKS path — the first thing we'd do
- # on a request with a bogus token is an expensive signing-key lookup, so we
- # cap total request volume before it reaches that code.
- throttle = TeamsEventWebhookThrottle()
- if not throttle.allow_request(DRFRequest(request), view=None): # type: ignore[arg-type]
- return HttpResponse(status=429)
-
- try:
- claims = validate_teams_request(request)
- except ValueError as e:
- logger.warning("supporthog_teams_invalid_request", error=str(e))
- return HttpResponse("Invalid request", status=403)
-
- try:
- activity = json.loads(request.body)
- except json.JSONDecodeError:
- return HttpResponse("Invalid JSON", status=400)
-
- activity_type = activity.get("type", "")
- logger.info("supporthog_teams_event_received", activity_type=activity_type)
-
- activity_id = activity.get("id", "")
-
- if activity_type == "message":
- # Generic-command guarantee (Teams Store cert 11.4.4.3): "Hi", "Hello",
- # "Help", etc. must always get a valid response — even from tenants
- # that haven't completed PostHog OAuth yet (this is exactly the path
- # the AppSource validators run against). Reply with the help card
- # before the team-config gate, then bail without creating a ticket.
- if is_command_message(activity):
- if not _claims_match_activity(claims, activity):
- return HttpResponse(status=200)
- # Defense in depth: never reply to a message that claims to come
- # from our own bot identity. Bot Framework doesn't echo, but a
- # valid-JWT replay with a spoofed from.id shouldn't loop us.
- try:
- bot_from_id = get_bot_from_id()
- except ValueError:
- bot_from_id = ""
- if bot_from_id and (activity.get("from") or {}).get("id") == bot_from_id:
- return HttpResponse(status=200)
- # Bot Framework retries the webhook on 5xx / timeout for up to ~10
- # minutes with the *same* activity.id. De-dupe on dispatch so we
- # don't post the help card twice.
- if activity_id and is_duplicate_teams_event(activity_id):
- return HttpResponse(status=202)
- cast(Any, send_teams_help).delay(activity=activity, reply=True)
- return HttpResponse(status=202)
- _route_activity_to_relevant_region(request, activity, claims)
- return HttpResponse(status=202)
-
- # Proactive welcome on install (Teams Store cert 11.4.4.3). The serviceUrl
- # cross-check still applies, but we don't need a PostHog-side team match —
- # the customer hasn't necessarily completed the OAuth flow yet, and the
- # welcome card uses only the global Bot Framework token.
- #
- # We also re-run _claims_match_activity here so that an attacker holding a
- # valid Bot Framework JWT can't pair it with a body that points serviceUrl
- # at a different Microsoft regional endpoint than the one the JWT was
- # issued for, even though the practical impact is limited (Bot Connector
- # only delivers to conversations the bot is actually installed in).
- if activity_type == "conversationUpdate" and is_bot_added_event(activity):
- if not _claims_match_activity(claims, activity):
- return HttpResponse(status=200)
- if activity_id and is_duplicate_teams_event(activity_id):
- return HttpResponse(status=200)
- cast(Any, send_teams_help).delay(activity=activity, reply=False)
- return HttpResponse(status=200)
-
- # Acknowledge other activity types (installationUpdate, etc.)
- return HttpResponse(status=200)
+)
diff --git a/products/conversations/backend/api/tests/test_teams_endpoints.py b/products/conversations/backend/api/tests/test_teams_endpoints.py
index a2c65fb83893..4d482316c569 100644
--- a/products/conversations/backend/api/tests/test_teams_endpoints.py
+++ b/products/conversations/backend/api/tests/test_teams_endpoints.py
@@ -1,4 +1,6 @@
import json
+import time
+from types import SimpleNamespace
from typing import Any
from urllib.parse import parse_qs, urlparse
@@ -6,30 +8,44 @@ from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
+from django.db import OperationalError
+import jwt
+from cryptography.hazmat.primitives.asymmetric import rsa
+from parameterized import parameterized
from rest_framework.test import APIClient
+from posthog.ingress.dispatch.loading import reset_consumer_registry
from posthog.models.organization import OrganizationMembership
from products.conversations.backend.models import TeamConversationsTeamsConfig
+from products.conversations.backend.support_teams import JWKS_CACHE_KEY
+
+TEAMS_EVENTS_MODULE = "products.conversations.backend.services.teams_events"
+SUPPORT_TEAMS_MODULE = "products.conversations.backend.support_teams"
+TEAMS_APP_ID = "00000000-0000-0000-0000-000000000009"
+BOT_FROM_ID = f"28:{TEAMS_APP_ID}"
+JWKS_URI = "https://login.botframework.com/v1/.well-known/keys"
+SERVICE_URL = "https://smba.trafficmanager.net/teams/"
def _make_activity(
*,
activity_type: str = "message",
- channel_id: str = "19:[email protected]",
+ teams_channel_id: str = "19:[email protected]",
tenant_id: str = "tenant-abc",
text: str = "I have an issue",
) -> dict[str, Any]:
return {
"type": activity_type,
"id": "act-123",
+ "channelId": "msteams",
"text": text,
- "serviceUrl": "https://smba.trafficmanager.net/teams/",
+ "serviceUrl": SERVICE_URL,
"from": {"id": "29:user", "aadObjectId": "aad-user-1", "role": "user"},
"conversation": {"id": "19:[email protected]"},
"channelData": {
- "channel": {"id": channel_id},
+ "channel": {"id": teams_channel_id},
"tenant": {"id": tenant_id},
},
}
@@ -37,6 +53,14 @@ def _make_activity(
class TestTeamsEventHandler(BaseTest):
client: APIClient
+ private_key: rsa.RSAPrivateKey
+ public_key: rsa.RSAPublicKey
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls.private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ cls.public_key = cls.private_key.public_key()
def setUp(self):
super().setUp()
@@ -52,109 +76,141 @@ class TestTeamsEventHandler(BaseTest):
)
self.client = APIClient()
cache.clear()
+ reset_consumer_registry()
+ self.addCleanup(reset_consumer_registry)
- def _post(self, payload: dict[str, Any], **kwargs):
+ for patcher in (
+ patch(
+ f"{SUPPORT_TEAMS_MODULE}.get_teams_instance_settings",
+ return_value={"SUPPORT_TEAMS_APP_ID": TEAMS_APP_ID},
+ ),
+ patch(
+ "jwt.PyJWKClient.get_signing_key_from_jwt",
+ return_value=SimpleNamespace(key=self.public_key, _jwk_data={"endorsements": ["msteams"]}),
+ ),
+ ):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ # Primed, so the getter serves the signing-key URI without fetching Microsoft's
+ # discovery document.
+ cache.set(JWKS_CACHE_KEY, JWKS_URI, 3600)
+
+ def _token(self, **claims: Any) -> str:
+ payload: dict[str, Any] = {
+ "iss": "https://api.botframework.com",
+ "aud": TEAMS_APP_ID,
+ "serviceurl": SERVICE_URL,
+ "tid": "tenant-abc",
+ "exp": int(time.time()) + 300,
+ **claims,
+ }
+ return jwt.encode(payload, self.private_key, algorithm="RS256")
+
+ def _post_raw(self, body: bytes, token: str | None = None):
+ headers = {} if token is None else {"authorization": f"Bearer {token}"}
return self.client.post(
"/api/conversations/v1/teams/events",
- data=json.dumps(payload),
+ data=body,
content_type="application/json",
- **kwargs,
+ headers=headers,
)
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_invalid_jwt_returns_403(self, mock_validate: MagicMock):
- mock_validate.side_effect = ValueError("JWT validation failed")
+ def _post(self, payload: dict[str, Any], token: str | None = None):
+ return self._post_raw(json.dumps(payload).encode("utf-8"), token=token or self._token())
- response = self._post(_make_activity())
+ def test_a_request_without_a_bot_framework_token_returns_403(self):
+ response = self._post_raw(json.dumps(_make_activity()).encode("utf-8"))
assert response.status_code == 403
- @patch("products.conversations.backend.api.teams_events.process_teams_event")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_message_activity_returns_202(self, mock_validate, mock_process):
- mock_validate.return_value = {}
-
- response = self._post(_make_activity())
+ def test_a_token_signed_for_another_bot_returns_403(self):
+ response = self._post(_make_activity(), token=self._token(aud="another-app-id"))
- assert response.status_code == 202
-
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_non_message_activity_returns_200(self, mock_validate):
- mock_validate.return_value = {}
+ assert response.status_code == 403
- response = self._post(_make_activity(activity_type="conversationUpdate"))
+ @parameterized.expand(
+ [
+ # A conversationUpdate that adds somebody other than the bot.
+ ("conversation_update", "conversationUpdate"),
+ # Bot Framework sends activity types this bot does not act on, and they are receipted.
+ ("installation_update", "installationUpdate"),
+ ]
+ )
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_an_activity_this_bot_does_not_act_on_is_receipted(
+ self, _name: str, activity_type: str, mock_help: MagicMock
+ ):
+ response = self._post(_make_activity(activity_type=activity_type))
- assert response.status_code == 200
+ assert response.status_code == 202
+ mock_help.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_conversation_update_with_bot_added_enqueues_welcome(self, mock_validate, mock_help):
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_conversation_update_with_bot_added_enqueues_welcome(self, mock_help: MagicMock):
"""Cert 11.4.4.3: bot must send a proactive welcome on install."""
- mock_validate.return_value = {}
activity = _make_activity(activity_type="conversationUpdate")
- bot_id = "28:bot-app-id"
- activity["recipient"] = {"id": bot_id, "name": "SupportHog"}
- activity["membersAdded"] = [{"id": bot_id}]
+ activity["recipient"] = {"id": BOT_FROM_ID, "name": "SupportHog"}
+ activity["membersAdded"] = [{"id": BOT_FROM_ID}]
response = self._post(activity)
- assert response.status_code == 200
+ assert response.status_code == 202
mock_help.delay.assert_called_once()
call_kwargs = mock_help.delay.call_args.kwargs
assert call_kwargs["activity"]["type"] == "conversationUpdate"
assert call_kwargs["reply"] is False
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_conversation_update_with_other_member_does_not_welcome(self, mock_validate, mock_help):
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_conversation_update_with_other_member_does_not_welcome(self, mock_help: MagicMock):
"""A non-bot member joining must not trigger the welcome card."""
- mock_validate.return_value = {}
activity = _make_activity(activity_type="conversationUpdate")
- activity["recipient"] = {"id": "28:bot-app-id", "name": "SupportHog"}
+ activity["recipient"] = {"id": BOT_FROM_ID, "name": "SupportHog"}
activity["membersAdded"] = [{"id": "29:some-other-user"}]
response = self._post(activity)
- assert response.status_code == 200
+ assert response.status_code == 202
mock_help.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.process_teams_event")
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_generic_command_replies_with_help_card_without_oauth(self, mock_validate, mock_help, mock_process):
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_generic_command_replies_with_help_card_without_oauth(self, mock_help: MagicMock, mock_process: MagicMock):
"""Cert 11.4.4.3: bot must respond to "Hi" / "Hello" / "Help" even
before OAuth — AppSource validators run against an unconnected tenant."""
- mock_validate.return_value = {}
- # tenant we have no PostHog config for — simulates the validator's tenant.
+ # A tenant we have no PostHog config for, which is the validator's tenant.
activity = _make_activity(text="Hi", tenant_id="unknown-tenant")
- response = self._post(activity)
+ response = self._post(activity, token=self._token(tid="unknown-tenant"))
assert response.status_code == 202
mock_help.delay.assert_called_once()
- call_kwargs = mock_help.delay.call_args.kwargs
- assert call_kwargs["reply"] is True
+ assert mock_help.delay.call_args.kwargs["reply"] is True
# Crucially, do NOT also try to create a ticket.
mock_process.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.process_teams_event")
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_non_command_message_does_not_hit_help_path(self, mock_validate, mock_help, mock_process):
- mock_validate.return_value = {}
-
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_non_command_message_does_not_hit_help_path(self, mock_help: MagicMock, mock_process: MagicMock):
self._post(_make_activity(text="I have an issue"))
mock_help.delay.assert_not_called()
mock_process.delay.assert_called_once()
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_command_message_deduplicated_on_retry(self, mock_validate, mock_help):
- """Bot Framework retries on 5xx for ~10 mins with the same activity.id —
- we must not post the help card twice."""
- mock_validate.return_value = {}
- activity = _make_activity(text="Hi")
+ @parameterized.expand(
+ [
+ ("command_message", "message", "Hi"),
+ ("bot_added", "conversationUpdate", ""),
+ ]
+ )
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_a_help_card_is_posted_once_across_bot_framework_retries(
+ self, _name: str, activity_type: str, text: str, mock_help: MagicMock
+ ):
+ """Bot Framework retries on 5xx for ~10 mins with the same activity.id."""
+ activity = _make_activity(activity_type=activity_type, text=text)
+ if activity_type == "conversationUpdate":
+ activity["recipient"] = {"id": BOT_FROM_ID, "name": "SupportHog"}
+ activity["membersAdded"] = [{"id": BOT_FROM_ID}]
first = self._post(activity)
second = self._post(activity)
@@ -163,75 +219,116 @@ class TestTeamsEventHandler(BaseTest):
assert second.status_code == 202
mock_help.delay.assert_called_once()
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.get_bot_from_id", return_value="28:bot-app-id")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_command_message_from_bot_self_id_suppressed(self, mock_validate, _mock_bot_id, mock_help):
+ @patch(f"{TEAMS_EVENTS_MODULE}.send_teams_help")
+ def test_command_message_from_bot_self_id_suppressed(self, mock_help: MagicMock):
"""Defense-in-depth: a spoofed activity claiming from.id == bot must
not loop us into replying. (Bot Framework doesn't echo, but a valid
JWT replay shouldn't bypass that.)"""
- mock_validate.return_value = {}
activity = _make_activity(text="Hi")
- activity["from"] = {"id": "28:bot-app-id", "aadObjectId": "aad-bot", "role": "bot"}
+ activity["from"] = {"id": BOT_FROM_ID, "aadObjectId": "aad-bot", "role": "bot"}
response = self._post(activity)
- assert response.status_code == 200
+ assert response.status_code == 202
mock_help.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.send_teams_help")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_welcome_deduplicated_on_retry(self, mock_validate, mock_help):
- """Same idempotency guarantee for the bot-added conversationUpdate."""
- mock_validate.return_value = {}
- activity = _make_activity(activity_type="conversationUpdate")
- bot_id = "28:bot-app-id"
- activity["recipient"] = {"id": bot_id, "name": "SupportHog"}
- activity["membersAdded"] = [{"id": bot_id}]
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_a_body_the_token_does_not_back_is_refused(self, mock_process: MagicMock):
+ # The gate itself is covered in posthog/ingress/test/test_teams.py. This is the wiring:
+ # the endpoint's own provider runs it, so a replayed token cannot redirect the activity.
+ activity = {**_make_activity(), "serviceUrl": "https://attacker.example.com/"}
- self._post(activity)
- self._post(activity)
+ response = self._post(activity)
- mock_help.delay.assert_called_once()
+ assert response.status_code == 400
+ mock_process.delay.assert_not_called()
+
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_a_signed_service_url_outside_microsoft_is_not_acted_on(self, mock_process: MagicMock):
+ # The claim backs the body here, so ingress accepts the activity. The bot's own bearer
+ # token goes to this URL, so the consumer still holds it to Microsoft's endpoints.
+ service_url = "https://attacker.example.com/"
+ activity = {**_make_activity(), "serviceUrl": service_url}
+
+ response = self._post(activity, token=self._token(serviceurl=service_url))
+
+ assert response.status_code == 202
+ mock_process.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_get_method_returns_405(self, mock_validate):
+ def test_get_method_returns_405(self):
response = self.client.get("/api/conversations/v1/teams/events")
- assert response.status_code == 405
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_invalid_json_returns_400(self, mock_validate):
- mock_validate.return_value = {}
+ assert response.status_code == 405
- response = self.client.post(
- "/api/conversations/v1/teams/events",
- data="{bad",
- content_type="application/json",
- )
+ def test_invalid_json_returns_400(self):
+ response = self._post_raw(b"{bad", token=self._token())
assert response.status_code == 400
- @patch("products.conversations.backend.api.teams_events.process_teams_event")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_message_dispatches_celery_task(self, mock_validate, mock_process):
- mock_validate.return_value = {}
-
- self._post(_make_activity(tenant_id="tenant-abc"))
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_message_dispatches_celery_task(self, mock_process: MagicMock):
+ response = self._post(_make_activity(tenant_id="tenant-abc"))
+ assert response.status_code == 202
mock_process.delay.assert_called_once()
call_kwargs = mock_process.delay.call_args.kwargs
assert call_kwargs["tenant_id"] == "tenant-abc"
assert call_kwargs["activity"]["type"] == "message"
+ assert call_kwargs["activity_id"] == "act-123"
+
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_a_tenant_this_region_does_not_hold_runs_nothing_here(self, mock_process: MagicMock):
+ response = self._post(_make_activity(tenant_id="unknown-tenant"), token=self._token(tid="unknown-tenant"))
+
+ assert response.status_code == 202
+ mock_process.delay.assert_not_called()
- @patch("products.conversations.backend.api.teams_events.process_teams_event")
- @patch("products.conversations.backend.api.teams_events.validate_teams_request")
- def test_unknown_tenant_proxies_or_warns(self, mock_validate, mock_process):
- mock_validate.return_value = {}
+ @parameterized.expand(
+ [
+ ("the owning region accepts it", 202, 202),
+ # Bot Framework redelivers on a 5xx, so a forward that never landed keeps no receipt.
+ ("the owning region is unreachable", 500, 503),
+ ]
+ )
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_a_tenant_another_region_owns_is_forwarded_from_the_primary(
+ self, _name: str, secondary_status: int, expected_status: int, mock_process: MagicMock
+ ):
+ with (
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),
+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,
+ ):
+ mock_forward.return_value = MagicMock(ok=200 <= secondary_status < 300, status_code=secondary_status)
+ response = self._post(_make_activity(tenant_id="unknown-tenant"), token=self._token(tid="unknown-tenant"))
+
+ assert response.status_code == expected_status
+ mock_forward.assert_called_once()
+ mock_process.delay.assert_not_called()
- self._post(_make_activity(tenant_id="unknown-tenant"))
+ @patch(f"{TEAMS_EVENTS_MODULE}.process_teams_event")
+ def test_a_tenant_lookup_that_does_not_answer_is_redelivered_rather_than_forwarded(self, mock_process: MagicMock):
+ with (
+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),
+ patch("posthog.ingress.dispatch.forward.requests.request") as mock_forward,
+ patch("posthog.ingress.dispatch.dispatcher.capture_exception"),
+ patch(
+ f"{TEAMS_EVENTS_MODULE}._tenant_is_connected_here",
+ side_effect=OperationalError("canceling statement due to statement timeout"),
+ ),
+ ):
+ response = self._post(_make_activity(tenant_id="tenant-abc"))
+ assert response.status_code == 503
+ mock_forward.assert_not_called()
mock_process.delay.assert_not_called()
+ # Nothing claimed a dedup mark on the refused delivery, so Bot Framework's retry of the
+ # same activity id runs the lookup again instead of being swallowed as a duplicate.
+ retry = self._post(_make_activity(tenant_id="tenant-abc"))
+
+ assert retry.status_code == 202
+ mock_process.delay.assert_called_once()
+
class TestTeamsChannelsEndpoints(APIBaseTest):
def setUp(self):
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
index 7c97abcfb853..20fc0c720b67 100644
--- a/products/conversations/backend/facade/api.py
+++ b/products/conversations/backend/facade/api.py
@@ -142,6 +142,26 @@ def slack_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
return slack_events.slack_delivery_ownership(delivery)
+def accept_teams_event(delivery: WebhookDelivery) -> None:
+ """The inbound SupportHog Teams webhook enters conversations here, so its consumer needs no internal import."""
+ # Deferred to keep the Celery task module off the facade import path.
+ from products.conversations.backend.services import teams_events # noqa: PLC0415
+
+ teams_events.accept_teams_event(delivery)
+
+
+def teams_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
+ """Whether this region holds the team the delivery's Teams tenant is connected to.
+
+ Ingress asks before it dispatches, and forwards the signed request to the other region when
+ the answer is elsewhere.
+ """
+ # Deferred to keep the Celery task module off the facade import path.
+ from products.conversations.backend.services import teams_events # noqa: PLC0415
+
+ return teams_events.teams_delivery_ownership(delivery)
+
+
def sync_google_account_email(integration_id: int, team_id: int) -> None:
from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycle
GmailSyncError,
diff --git a/products/conversations/backend/services/teams_events.py b/products/conversations/backend/services/teams_events.py
new file mode 100644
index 000000000000..1a74c7fd55af
--- /dev/null
+++ b/products/conversations/backend/services/teams_events.py
@@ -0,0 +1,169 @@
+"""Bot Framework activities for the SupportHog Microsoft Teams bot.
+
+Two entry points, both reached from the facade after ingress verified the bearer token and
+parsed the activity: ``teams_delivery_ownership`` answers which region holds the tenant the
+activity is about, and ``accept_teams_event`` runs the certification replies and hands a regular
+message to its Celery task. No HTTP in here, because ingress owns the request, the receipt and
+the forward to the region that owns the tenant.
+"""
+
+from typing import Any, cast
+
+import structlog
+
+from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery
+from posthog.ingress.dispatch.database import bounded_statement_timeout
+
+from products.conversations.backend.models import TeamConversationsTeamsConfig
+from products.conversations.backend.support_teams import get_bot_from_id, is_trusted_teams_service_url
+from products.conversations.backend.tasks.teams import is_duplicate_teams_event, process_teams_event, send_teams_help
+from products.conversations.backend.teams import is_bot_added_event, is_command_message
+
+logger = structlog.get_logger(__name__)
+
+# The lookup runs inside the request, before dispatch, so it draws on the delivery's wall clock.
+_TENANT_LOOKUP_TIMEOUT_MS = 800
+
+
+def _activity_tenant_id(activity: dict[str, Any]) -> str:
+ return ((activity.get("channelData") or {}).get("tenant") or {}).get("id", "")
+
+
+def _service_url_is_trusted(delivery: WebhookDelivery) -> bool:
+ """Whether the activity's `serviceUrl` is a Microsoft host the bot may send its token to.
+
+ Ingress already proved the issuer signed this exact URL, so `claim_service_url` is the
+ activity's own `serviceUrl`. That says the URL is genuine, not that it is one of Microsoft's
+ Bot Framework endpoints, and the bot's bearer token goes to whatever this names.
+ """
+ service_url = delivery.context.get("claim_service_url", "")
+ if service_url and not is_trusted_teams_service_url(service_url):
+ logger.warning("supporthog_teams_untrusted_service_url", service_url=service_url)
+ return False
+ return True
+
+
+def _tenant_is_connected_here(tenant_id: str) -> bool:
+ """Whether a team in this region has SupportHog connected for this Teams tenant.
+
+ The Celery task resolves the team again from the tenant id, so nothing here needs the row
+ itself. A cancelled statement raises, because a lookup that never finished is not an answer,
+ and both callers let it out.
+ """
+ with bounded_statement_timeout(_TENANT_LOOKUP_TIMEOUT_MS, models=[TeamConversationsTeamsConfig]):
+ return TeamConversationsTeamsConfig.objects.filter(
+ teams_tenant_id=tenant_id, teams_graph_access_token__isnull=False
+ ).exists()
+
+
+def teams_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
+ """Which region holds the team the delivery's Teams tenant is connected to.
+
+ Two kinds of activity are never forwarded, and answer `UNDECIDED` so they run here exactly
+ once. The Teams Store certification requires a reply to a command message such as "help" and
+ a proactive welcome when the bot is added, both from a tenant that may never have finished
+ OAuth. Neither needs a team, so no region is better placed to answer them, and a forward
+ would post the card twice.
+
+ A regular message is the only kind a team answers for. A tenant this region does not know is
+ `ELSEWHERE` rather than undecided, so the delivery reaches the other region: it is the only
+ one that can tell a tenant it holds from one nobody holds.
+
+ A lookup that spends its statement timeout raises out of here on purpose. The dispatcher
+ turns that into `FAILED`, and ingress answers the provider's `retry_status` with no forward,
+ no dispatch and no dedup mark, so Bot Framework sends the activity again and the lookup runs
+ again with it. `ELSEWHERE` would be a guess: a timeout is no evidence that the other region
+ holds the tenant, and the forward carries the customer's message content into a region that
+ may not own it.
+ """
+ if not _service_url_is_trusted(delivery):
+ # Nothing acts on this activity, here or elsewhere, so there is nothing to forward.
+ return DeliveryOwnership.UNDECIDED
+
+ activity: dict[str, Any] = dict(delivery.payload)
+ if delivery.event_type != "message" or is_command_message(activity):
+ return DeliveryOwnership.UNDECIDED
+
+ tenant_id = _activity_tenant_id(activity)
+ if not tenant_id:
+ return DeliveryOwnership.UNDECIDED
+
+ return DeliveryOwnership.LOCAL if _tenant_is_connected_here(tenant_id) else DeliveryOwnership.ELSEWHERE
+
+
+def _is_from_the_bot_itself(activity: dict[str, Any]) -> bool:
+ """Defense in depth: never reply to a message that claims to come from our own bot identity.
+
+ Bot Framework doesn't echo, but a valid-JWT replay with a spoofed from.id shouldn't loop us.
+ """
+ try:
+ bot_from_id = get_bot_from_id()
+ except ValueError:
+ return False
+ return bool(bot_from_id) and (activity.get("from") or {}).get("id") == bot_from_id
+
+
+def _accept_conversation_update(activity: dict[str, Any], activity_id: str) -> None:
+ """The proactive welcome on install (Teams Store cert 11.4.4.3).
+
+ No PostHog-side team match is needed: the customer hasn't necessarily completed the OAuth
+ flow yet, and the welcome card uses only the global Bot Framework token.
+ """
+ if not is_bot_added_event(activity):
+ return
+ if activity_id and is_duplicate_teams_event(activity_id):
+ return
+ cast(Any, send_teams_help).delay(activity=activity, reply=False)
+
+
+def _accept_message(activity: dict[str, Any], activity_id: str) -> None:
+ # Generic-command guarantee (Teams Store cert 11.4.4.3): "Hi", "Hello", "Help", etc. must
+ # always get a valid response, even from tenants that haven't completed PostHog OAuth yet
+ # (this is exactly the path the AppSource validators run against). Reply with the help card
+ # before the team-config gate, then bail without creating a ticket.
+ if is_command_message(activity):
+ if _is_from_the_bot_itself(activity):
+ return
+ # A second guard under the ingress dedup mark, which fails open on a cache error: the
+ # help card must not be posted twice.
+ if activity_id and is_duplicate_teams_event(activity_id):
+ return
+ cast(Any, send_teams_help).delay(activity=activity, reply=True)
+ return
+
+ tenant_id = _activity_tenant_id(activity)
+ # Unguarded on purpose: a timed-out lookup fails the delivery, so the dispatcher releases the
+ # dedup mark and Bot Framework's redelivery reaches this consumer instead of the activity
+ # being lost.
+ if not tenant_id or not _tenant_is_connected_here(tenant_id):
+ # Quiet on purpose: ingress reports a delivery no region here owns, off the ownership
+ # answer this module gave it before dispatch.
+ return
+
+ cast(Any, process_teams_event).delay(activity=activity, tenant_id=tenant_id, activity_id=activity_id)
+
+
+def accept_teams_event(delivery: WebhookDelivery) -> None:
+ """Act on one verified Bot Framework activity.
+
+ Ingress refused any activity whose `serviceUrl` the token did not sign, so what is left to
+ check is that the URL is a Microsoft host. That runs here as well as in the ownership
+ answer, because a consumer must not depend on another lane having run a check for it.
+ """
+ if not _service_url_is_trusted(delivery):
+ return
+
+ activity: dict[str, Any] = dict(delivery.payload)
+
+ activity_id = delivery.delivery_id or ""
+ logger.info(
+ "supporthog_teams_activity",
+ activity_type=delivery.event_type,
+ tenant_id=_activity_tenant_id(activity),
+ )
+
+ if delivery.event_type == "conversationUpdate":
+ _accept_conversation_update(activity, activity_id)
+ return
+ if delivery.event_type == "message":
+ _accept_message(activity, activity_id)
diff --git a/products/conversations/backend/support_teams.py b/products/conversations/backend/support_teams.py
index 3d307738bad6..7b373ac99ada 100644
--- a/products/conversations/backend/support_teams.py
+++ b/products/conversations/backend/support_teams.py
@@ -1,8 +1,8 @@
"""
-Token management and request validation for the SupportHog Microsoft Teams bot.
+Token management for the SupportHog Microsoft Teams bot.
Handles:
-- Bot Framework JWT validation (inbound activities from Azure Bot Service)
+- The three values ingress verifies inbound Bot Framework activities with (signing keys, audience, issuers)
- Graph API token refresh (per-tenant, for listing teams/channels/users)
- Bot Framework token acquisition (global, for sending replies)
- Save/clear config with activity logging
@@ -14,9 +14,7 @@ from urllib.parse import urlparse
from django.core.cache import cache
from django.db import transaction
-from django.http import HttpRequest
-import jwt
import redis
import requests
import structlog
@@ -26,6 +24,7 @@ from posthog.models.instance_setting import get_instance_settings
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team import Team
from posthog.redis import get_client
+from posthog.security.url_validation import is_url_allowed
from products.conversations.backend.models import TeamConversationsTeamsConfig
@@ -63,8 +62,6 @@ GRAPH_REFRESH_LOCK_KEY_PREFIX = "supporthog:teams:graph_refresh_lock"
GRAPH_REFRESH_LOCK_TIMEOUT_SECONDS = 30
GRAPH_REFRESH_LOCK_BLOCKING_TIMEOUT_SECONDS = 10
-JWT_CLOCK_TOLERANCE_SECONDS = 5 * 60
-
# Must match products.conversations.backend.api.teams_oauth.TEAMS_OAUTH_SCOPES.
# Refresh requests should request the same scopes as the original authorization
# to avoid Azure AD scope-mismatch errors. TeamsAppInstallation.ReadWriteForTeam
@@ -129,7 +126,7 @@ def get_teams_instance_settings() -> dict:
)
-def _get_botframework_valid_issuers() -> tuple[str, ...]:
+def get_botframework_issuers() -> frozenset[str]:
"""
Microsoft Teams / Bot Framework signs inbound activities with a service
token issued by Bot Framework. We validate that issuer only.
@@ -145,7 +142,58 @@ def _get_botframework_valid_issuers() -> tuple[str, ...]:
See: https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-authentication
"""
- return ("https://api.botframework.com",)
+ return frozenset({"https://api.botframework.com"})
+
+
+def get_teams_app_id() -> str | None:
+ """The bot's app id, which is the audience every inbound activity token must carry."""
+ app_id = str(get_teams_instance_settings().get("SUPPORT_TEAMS_APP_ID") or "")
+ return app_id or None
+
+
+def _allowed_jwks_uri(jwks_uri: str) -> str | None:
+ """The URI, once it passes the SSRF allowlist, or None when it does not.
+
+ The value comes out of a document Microsoft serves rather than out of PostHog's own
+ configuration, so it is checked before anything fetches it, the same way
+ ``posthog/api/id_jag.py`` checks the JWKS URI it discovers.
+ """
+ allowed, reason = is_url_allowed(jwks_uri)
+ if not allowed:
+ logger.warning("teams_jwks_uri_not_allowed", reason=reason)
+ return None
+ return jwks_uri
+
+
+def get_botframework_jwks_uri() -> str | None:
+ """The signing-key URI from the Bot Framework OpenID metadata document.
+
+ Ingress calls this on every inbound activity, so the discovery result is cached for an hour
+ rather than fetched each time.
+ """
+ cached_uri = cache.get(JWKS_CACHE_KEY)
+ if cached_uri:
+ # Only the discovery below writes this key, and it writes an allowed URI. Re-checking
+ # here would put a DNS lookup on every inbound activity, and a lookup that failed would
+ # read as an unconfigured instance.
+ return str(cached_uri)
+
+ try:
+ response = requests.get(BOTFRAMEWORK_OPENID_METADATA_URL, timeout=10)
+ response.raise_for_status()
+ jwks_uri = response.json().get("jwks_uri")
+ except Exception:
+ logger.exception("teams_jwks_metadata_fetch_failed")
+ return None
+
+ if not jwks_uri:
+ logger.warning("teams_jwks_metadata_without_uri")
+ return None
+
+ allowed_uri = _allowed_jwks_uri(str(jwks_uri))
+ if allowed_uri:
+ cache.set(JWKS_CACHE_KEY, allowed_uri, JWKS_CACHE_TTL_SECONDS)
+ return allowed_uri
def is_trusted_teams_service_url(service_url: str) -> bool:
@@ -194,120 +242,12 @@ def get_bot_from_id() -> str:
does infer bot identity from the bearer token, but including `from.id` explicitly
avoids undocumented fallback behavior and matches the Activity schema.
"""
- app_id = str(get_teams_instance_settings().get("SUPPORT_TEAMS_APP_ID") or "")
+ app_id = get_teams_app_id()
if not app_id:
raise ValueError("SUPPORT_TEAMS_APP_ID not configured")
return f"28:{app_id}"
-def _get_jwks_client() -> jwt.PyJWKClient:
- """Fetch the JWKS URI from Bot Framework OpenID metadata, cached for 1 hour."""
- cached_uri = cache.get(JWKS_CACHE_KEY)
- if cached_uri:
- return jwt.PyJWKClient(cached_uri)
-
- try:
- resp = requests.get(BOTFRAMEWORK_OPENID_METADATA_URL, timeout=10)
- resp.raise_for_status()
- jwks_uri = resp.json().get("jwks_uri")
- if jwks_uri:
- cache.set(JWKS_CACHE_KEY, jwks_uri, JWKS_CACHE_TTL_SECONDS)
- return jwt.PyJWKClient(jwks_uri)
- except Exception:
- logger.exception("teams_jwks_metadata_fetch_failed")
-
- raise ValueError("Failed to fetch Bot Framework JWKS metadata")
-
-
-def validate_teams_request(request: HttpRequest) -> dict:
- """
- Validate an incoming Bot Framework activity by checking the JWT bearer token.
-
- Returns the decoded JWT claims on success.
- Raises ValueError on any validation failure.
- """
- settings = get_teams_instance_settings()
- app_id = str(settings.get("SUPPORT_TEAMS_APP_ID") or "")
- if not app_id:
- raise ValueError("SUPPORT_TEAMS_APP_ID not configured")
-
- auth_header = request.headers.get("Authorization", "")
- if not auth_header.startswith("Bearer "):
- raise ValueError("Missing or invalid Authorization header")
-
- token = auth_header[7:]
-
- # Peek at unverified claims/header for diagnostics — helps us see why a token
- # is being rejected (wrong issuer, wrong aud, wrong kid, etc.) without having
- # to reproduce the issue. These claims are ONLY used for logging on the error
- # path below; the actual authentication decision is made by the verified
- # jwt.decode() call further down, which enforces signature + aud + exp.
- unverified_claims: dict = {}
- unverified_header: dict = {}
- try:
- # nosemgrep: python.jwt.security.unverified-jwt-decode.unverified-jwt-decode (diagnostics only, not used for auth)
- unverified_claims = jwt.decode(token, options={"verify_signature": False})
- unverified_header = jwt.get_unverified_header(token)
- except Exception:
- pass
-
- try:
- jwks_client = _get_jwks_client()
- signing_key = jwks_client.get_signing_key_from_jwt(token)
-
- # The allowlist is currently a singleton (`api.botframework.com`), but
- # we keep the manual check so adding a second issuer later doesn't silently
- # fall into the `verify_iss=False` branch.
- claims = jwt.decode(
- token,
- signing_key.key,
- algorithms=["RS256", "RS384", "RS512"],
- audience=app_id,
- options={
- "verify_exp": True,
- "verify_iss": False,
- "verify_aud": True,
- },
- leeway=timedelta(seconds=JWT_CLOCK_TOLERANCE_SECONDS),
- )
- issuer = claims.get("iss", "")
- if issuer not in _get_botframework_valid_issuers():
- raise ValueError(f"JWT issuer not allowed: {issuer}")
- return claims
- except jwt.ExpiredSignatureError:
- logger.warning(
- "teams_jwt_rejected",
- reason="expired",
- iss=unverified_claims.get("iss"),
- aud=unverified_claims.get("aud"),
- exp=unverified_claims.get("exp"),
- kid=unverified_header.get("kid"),
- )
- raise ValueError("JWT token expired")
- except jwt.InvalidTokenError as e:
- logger.warning(
- "teams_jwt_rejected",
- reason="invalid_token",
- error=str(e),
- iss=unverified_claims.get("iss"),
- aud=unverified_claims.get("aud"),
- serviceurl=unverified_claims.get("serviceurl"),
- kid=unverified_header.get("kid"),
- alg=unverified_header.get("alg"),
- )
- raise ValueError(f"JWT validation failed: {e}")
- except jwt.PyJWKClientError as e:
- logger.warning(
- "teams_jwt_rejected",
- reason="jwks_lookup_failed",
- error=str(e),
- iss=unverified_claims.get("iss"),
- aud=unverified_claims.get("aud"),
- kid=unverified_header.get("kid"),
- )
- raise ValueError(f"JWKS lookup failed: {e}")
-
-
def invalidate_bot_framework_token() -> None:
"""Drop the cached bot token — call after a 401 from Bot Connector."""
cache.delete(BOT_TOKEN_CACHE_KEY)
diff --git a/products/conversations/backend/webhook_consumers.py b/products/conversations/backend/webhook_consumers.py
index 74f59c468573..c585c2cf7f67 100644
--- a/products/conversations/backend/webhook_consumers.py
+++ b/products/conversations/backend/webhook_consumers.py
@@ -1,4 +1,4 @@
-"""Conversations' consumers on the customer-facing GitHub App and the SupportHog Slack app.
+"""Conversations' consumers on the customer-facing GitHub App and the SupportHog Slack and Teams bots.
The registry imports this module on the first delivery, so it stays cheap: every callable defers
its own product import.
@@ -6,6 +6,7 @@ its own product import.
from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery
from posthog.ingress.slack.provider import SLACK_EVENT_TYPES, SLACK_INTERACTIVITY_APP, SLACK_INTERACTIVITY_TYPES
+from posthog.ingress.teams.provider import TEAMS_ACTIVITY_TYPES
def _run_conversations(delivery: WebhookDelivery) -> None:
@@ -32,6 +33,18 @@ def _slack_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
return slack_delivery_ownership(delivery)
+def _run_teams_events(delivery: WebhookDelivery) -> None:
+ from products.conversations.backend.facade.api import accept_teams_event # noqa: PLC0415
+
+ accept_teams_event(delivery)
+
+
+def _teams_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:
+ from products.conversations.backend.facade.api import teams_delivery_ownership # noqa: PLC0415
+
+ return teams_delivery_ownership(delivery)
+
+
WEBHOOK_CONSUMERS = (
WebhookConsumer(
name="conversations",
@@ -60,4 +73,12 @@ WEBHOOK_CONSUMERS = (
# workspace too, so a click on a workspace the other region holds is forwarded there.
ownership=_slack_ownership,
),
+ WebhookConsumer(
+ name="conversations_teams",
+ provider="teams",
+ app="supporthog",
+ event_types=TEAMS_ACTIVITY_TYPES,
+ handler=_run_teams_events,
+ ownership=_teams_ownership,
+ ),
)