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.

fix(ingress): answer 403 for an unset Teams app id and 503 when key discovery fails (#103823)

Julian Bez368c4c9185da
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.md
index 3ad2a5c8a5a8..9160f1787379 100644
--- a/posthog/ingress/README.md
+++ b/posthog/ingress/README.md
@@ -233,7 +233,8 @@ The same attribute answers a delivery whose consumers did not accept it, under o
Add a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):
- `SPECS` — one `ProviderSpec` per app, naming the event types the app is subscribed to. The registry validates consumers against these.
-- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack and Mailgun on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).
+- A `WebhookProvider` subclass — its `scheme()` (from `verify/`), its `deliveries()` (how to read event type, delivery id and context off the request), and any status codes its protocol fixes. The defaults are 403 on a bad signature, 500 when unconfigured, and 202 on success, with a short body naming the reason on the two rejections. The 500 suits an endpoint whose secret is always set, because an unconfigured one is then an operator fault; an endpoint that a deployment may legitimately never configure, such as Slack, Mailgun and Teams on a self-hosted instance, sets `unconfigured_status = 403` instead, or the URL answers a server error to every anonymous probe. An incarnation that answers 404 to withhold the endpoint's existence sets `explains_rejections = False` so the body stays empty as well, and so does one that must not tell an unauthenticated caller whether the secret is merely unset. Four more attributes are optional: `parse()`, which decodes the body, `throttle_class`, which caps request volume, `retry_status`, which a provider that redelivers on a non-2xx sets so an unaccepted delivery is not receipted, and `reports_unconfigured`, which also sends a missing secret to error tracking. That last one is off by default, because an endpoint that answers an unconfigured request like an unknown route lets an unauthenticated prober fill error tracking from the outside; turn it on where the deliveries are lost while the secret is unset and nothing else would notice. See [The lanes one request runs through](#the-lanes-one-request-runs-through).
+- A provider that lowers `unconfigured_status` to a 4xx, as Teams does, first checks that its scheme reaches `NOT_CONFIGURED` only for a value an operator sets, never for one a remote lookup produces. A 4xx the sender does not retry turns that lookup's outage into lost deliveries. This is why `BearerJwt` answers `UNAVAILABLE` for a signing-key URI it could not discover, and reads the values an operator sets before it.
- A `build_<provider>_provider(...)` function returning that provider, which the URLconf hands to `build_webhook_view()`.
A builder that takes an `app` name checks it with `require_known_app(provider, app, SPECS)` before anything else, so a typo raises `UnknownApp` at import. Without that check the endpoint builds and serves: consumers register against the declared app names, so nothing matches and every delivery is receipted and dropped, or the app has no secret getter and every delivery answers `NOT_CONFIGURED`.
diff --git a/posthog/ingress/teams/README.md b/posthog/ingress/teams/README.md
index 31b8612bd1cb..dd7d9dcb012e 100644
--- a/posthog/ingress/teams/README.md
+++ b/posthog/ingress/teams/README.md
@@ -62,6 +62,16 @@ The `InvalidPayload` message names the field and never either value, because it
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.
+**An unset app id answers 403, and a signing-key URI the getter could not discover answers 503.**
+403 is `unconfigured_status`, not the package default of 500, and is the status the hand-rolled view answered.
+It keeps an instance that never registered a bot from turning every anonymous probe of a public URL into a server error.
+`explains_rejections` is False with it, so neither that answer nor a rejected token names its reason. Bot Framework reads the status alone.
+
+The two cases have to stay apart, because `jwks_uri_getter` fetches Microsoft's OpenID metadata document and answers `None` when that fetch fails.
+`BearerJwt` reads the audience and the issuers first and answers `NOT_CONFIGURED` for those, then reads the URI and answers `UNAVAILABLE` when it is missing.
+Bot Framework retries a 5xx for about ten minutes and does not retry a 403, so folding the failed fetch into the 403 would lose every activity for the length of a Microsoft outage.
+Checking the audience first also means an instance with no bot registration buys no metadata fetch.
+
**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.
diff --git a/posthog/ingress/teams/provider.py b/posthog/ingress/teams/provider.py
index be8a394a5f83..66e5a6f06875 100644
--- a/posthog/ingress/teams/provider.py
+++ b/posthog/ingress/teams/provider.py
@@ -94,6 +94,13 @@ class TeamsProvider(WebhookProvider):
# 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
+ # The status this endpoint answered before it moved here: an instance with no bot registration
+ # reads as a request it refuses, not as a server that broke. A failed signing-key discovery is
+ # not this case and never reaches it, because `BearerJwt` answers UNAVAILABLE for that.
+ unconfigured_status = 403
+ # The body must not tell an unauthenticated caller that the endpoint is unconfigured, which is
+ # an operator fact about an instance anyone can probe. Bot Framework reads the status only.
+ explains_rejections = False
def __init__(
self,
diff --git a/posthog/ingress/test/test_teams.py b/posthog/ingress/test/test_teams.py
index 22247d8c1ce5..20b7211c2f91 100644
--- a/posthog/ingress/test/test_teams.py
+++ b/posthog/ingress/test/test_teams.py
@@ -172,3 +172,35 @@ class TestTeamsProvider(SimpleTestCase):
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)
+
+ def _unconfigured_view_response(self, *, jwks_uri: str | None, audience: str | None) -> Any:
+ provider = build_teams_provider(
+ jwks_uri_getter=lambda: jwks_uri,
+ audience_getter=lambda: audience,
+ issuers_getter=lambda: frozenset({ISSUER}),
+ )
+ throttle_class = provider.throttle_class
+ assert throttle_class is not None
+
+ # The throttle keys on the caller and its cache is shared with every other test in this
+ # process, so the cap is held open rather than left to test order.
+ with patch.object(throttle_class, "allow_request", return_value=True):
+ return build_webhook_view(provider)(self._request(ACTIVITY, self._token()))
+
+ def test_an_unset_app_id_answers_403_with_no_reason(self) -> None:
+ # The package default is 500, which would turn every anonymous probe of this public URL
+ # into a server error on an instance that never registered a bot. The endpoint answered
+ # 403 before it moved into this package.
+ response = self._unconfigured_view_response(jwks_uri=JWKS_URI, audience=None)
+
+ self.assertEqual(response.status_code, 403)
+ # And the body must not tell that caller whether the instance is merely unconfigured.
+ self.assertEqual(response.content, b"")
+
+ def test_a_signing_key_uri_that_could_not_be_discovered_answers_503(self) -> None:
+ # The getter fetches Microsoft's OpenID metadata and answers None when that fetch fails.
+ # Reading that as unconfigured would answer 403, which Bot Framework does not retry, and
+ # a metadata outage would then lose every activity in it.
+ response = self._unconfigured_view_response(jwks_uri=None, audience=APP_ID)
+
+ self.assertEqual(response.status_code, 503)
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index 979fb225eb30..c790a7311db2 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -397,7 +397,6 @@ class TestBearerJwt(SimpleTestCase):
@parameterized.expand(
[
- ("no_jwks_uri", None, AUDIENCE, frozenset({ISSUER})),
("no_audience", JWKS_URI, None, frozenset({ISSUER})),
("no_issuers", JWKS_URI, AUDIENCE, frozenset()),
]
@@ -410,6 +409,33 @@ class TestBearerJwt(SimpleTestCase):
headers = {"Authorization": "Bearer " + self._token()}
self.assertEqual(self._verify(scheme, headers).outcome, VerificationOutcome.NOT_CONFIGURED)
+ def test_a_signing_key_uri_the_getter_could_not_discover_is_unavailable(self) -> None:
+ # The getter fetches the URI from the issuer's metadata document and answers None when
+ # that fetch fails. Reading it as unconfigured gives a provider whose unconfigured status
+ # is a 4xx, which the issuer does not retry, and the outage then loses every delivery.
+ scheme = self._scheme(jwks_uri=None, audience=AUDIENCE, issuers=frozenset({ISSUER}))
+
+ headers = {"Authorization": "Bearer " + self._token()}
+ self.assertEqual(self._verify(scheme, headers).outcome, VerificationOutcome.UNAVAILABLE)
+
+ def test_an_unconfigured_instance_buys_no_signing_key_discovery(self) -> None:
+ # The getter reaches the issuer over the network, and this endpoint is public.
+ calls = 0
+
+ def jwks_uri_getter() -> str:
+ nonlocal calls
+ calls += 1
+ return JWKS_URI
+
+ scheme = BearerJwt(
+ jwks_uri_getter=jwks_uri_getter,
+ audience_getter=lambda: None,
+ issuers_getter=lambda: frozenset({ISSUER}),
+ )
+
+ self._verify(scheme, {"Authorization": "Bearer " + self._token()})
+ self.assertEqual(calls, 0)
+
def test_reuses_one_jwks_client_per_uri(self) -> None:
# The client holds the key cache, so a client per delivery is a JWKS fetch per delivery.
self.assertIs(_jwks_client(JWKS_URI), _jwks_client(JWKS_URI))
diff --git a/posthog/ingress/verify/jwt.py b/posthog/ingress/verify/jwt.py
index 6bda01c6c8a8..9bc667f8a05e 100644
--- a/posthog/ingress/verify/jwt.py
+++ b/posthog/ingress/verify/jwt.py
@@ -85,14 +85,24 @@ class BearerJwt:
if token is None:
return Verification(outcome=VerificationOutcome.INVALID)
- jwks_uri = self.jwks_uri_getter()
audience = self.audience_getter()
issuers = self.issuers_getter()
# An empty issuer allowlist rejects every token that will ever arrive, so it is an
- # operator problem rather than a caller one, the same as a missing secret.
- if not jwks_uri or not audience or not issuers:
+ # operator problem rather than a caller one, the same as a missing secret. Both are read
+ # before the URI, so an instance that was never set up buys no discovery request.
+ if not audience or not issuers:
return Verification(outcome=VerificationOutcome.NOT_CONFIGURED)
+ jwks_uri = self.jwks_uri_getter()
+ if not jwks_uri:
+ # The getter discovers this URI remotely, so no URI reads as a discovery that failed
+ # rather than as an instance nobody configured. It is the same answer as a JWKS fetch
+ # that never completed: the check did not run, and a provider that retries a server
+ # error sends the delivery again. A provider whose unconfigured status is a 4xx would
+ # otherwise drop every delivery for the length of the issuer's outage.
+ logger.warning("ingress_jwt_signing_key_uri_unavailable")
+ return Verification(outcome=VerificationOutcome.UNAVAILABLE)
+
try:
signing_key = _jwks_client(jwks_uri).get_signing_key_from_jwt(token)
claims = jwt.decode(