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.

feat(api): advertise OAuth resource metadata on 401 responses (#59925)

Rafael Audibert09d3945abb5d
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index b8118a294dfb..2642948249ba 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -6,6 +6,7 @@ from django.http.response import JsonResponse
import structlog
from rest_framework import status
from rest_framework.exceptions import APIException
+from rest_framework.response import Response
from posthog.clickhouse.query_tagging import get_query_tags
from posthog.cloud_utils import is_cloud
@@ -122,3 +123,27 @@ def generate_exception_response(
tags={"endpoint": endpoint, "code": code, "type": type, "attr": attr},
)
return JsonResponse({"type": type, "code": code, "detail": detail, "attr": attr}, status=status_code)
+
+
+def exception_handler(exc: Exception, context: ExceptionContext) -> Optional[Response]:
+ """
+ Wraps drf-exceptions-hog and, on 401, advertises the OAuth protected resource
+ metadata document via WWW-Authenticate per RFC 9728, so that MCP-style agents
+ can bootstrap from a stock 401.
+ """
+ # Imported lazily: exceptions_hog calls a non-lazy gettext at module import time,
+ # which raises AppRegistryNotReady when posthog.exceptions is imported during
+ # manage.py bootstrap (before Django apps are loaded).
+ from exceptions_hog import exception_handler as _exceptions_hog_handler
+
+ # Imported lazily to avoid pulling settings into module import.
+ from posthog.utils import absolute_uri
+
+ response = _exceptions_hog_handler(exc, context)
+ if response is not None and response.status_code == status.HTTP_401_UNAUTHORIZED:
+ # Pin to SITE_URL rather than request.build_absolute_uri(): with permissive
+ # ALLOWED_HOSTS, the Host header can otherwise steer the discovery hint to an
+ # attacker-controlled origin.
+ metadata_url = absolute_uri("/.well-known/oauth-protected-resource")
+ response["WWW-Authenticate"] = f'Bearer resource_metadata="{metadata_url}"'
+ return response
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f149c470a4cf..bfd710df7079 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -373,7 +373,7 @@ REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
"DEFAULT_RENDERER_CLASSES": ["posthog.renderers.SafeJSONRenderer"],
"PAGE_SIZE": 100,
- "EXCEPTION_HANDLER": "exceptions_hog.exception_handler",
+ "EXCEPTION_HANDLER": "posthog.exceptions.exception_handler",
"TEST_REQUEST_DEFAULT_FORMAT": "json",
"DEFAULT_SCHEMA_CLASS": "posthog.api.documentation.PostHogAutoSchema",
# These rate limits are defined in `rate_limit.py`, and they're only
diff --git a/posthog/test/test_exceptions.py b/posthog/test/test_exceptions.py
new file mode 100644
index 000000000000..13d78dadde26
--- /dev/null
+++ b/posthog/test/test_exceptions.py
@@ -0,0 +1,72 @@
+from django.http import HttpRequest
+from django.test import RequestFactory, SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework.exceptions import (
+ APIException,
+ AuthenticationFailed,
+ NotAuthenticated,
+ PermissionDenied,
+ ValidationError,
+)
+
+from posthog.exceptions import exception_handler
+
+
+@override_settings(SITE_URL="https://us.posthog.com")
+class TestExceptionHandlerWWWAuthenticate(SimpleTestCase):
+ def _request(self, *, secure: bool = True, host: str = "us.posthog.com") -> HttpRequest:
+ factory = RequestFactory()
+ return factory.get("/api/users/@me/", secure=secure, HTTP_HOST=host)
+
+ @parameterized.expand(
+ [
+ (
+ "not_authenticated",
+ NotAuthenticated(),
+ 401,
+ 'Bearer resource_metadata="https://us.posthog.com/.well-known/oauth-protected-resource"',
+ ),
+ (
+ "authentication_failed",
+ AuthenticationFailed("bad token"),
+ 401,
+ 'Bearer resource_metadata="https://us.posthog.com/.well-known/oauth-protected-resource"',
+ ),
+ (
+ "permission_denied",
+ PermissionDenied(),
+ 403,
+ None,
+ ),
+ (
+ "validation_error",
+ ValidationError("bad"),
+ 400,
+ None,
+ ),
+ ]
+ )
+ def test_www_authenticate_on_drf_exception(
+ self,
+ _name: str,
+ exception: APIException,
+ expected_status: int,
+ expected_header: str | None,
+ ) -> None:
+ response = exception_handler(exception, {"request": self._request()})
+ assert response is not None
+ assert response.status_code == expected_status
+ if expected_header is None:
+ assert "WWW-Authenticate" not in response
+ else:
+ assert response["WWW-Authenticate"] == expected_header
+
+ def test_hint_ignores_host_header(self) -> None:
+ """A spoofed Host header must not steer the discovery URL away from SITE_URL."""
+ response = exception_handler(NotAuthenticated(), {"request": self._request(host="attacker.example")})
+ assert response is not None
+ assert (
+ response["WWW-Authenticate"]
+ == 'Bearer resource_metadata="https://us.posthog.com/.well-known/oauth-protected-resource"'
+ )