:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(oauth): serve protected resource metadata (RFC 9728) (#64141)
Matt Brooker389fbc11269e
diff --git a/posthog/api/oauth/__init__.py b/posthog/api/oauth/__init__.pyindex dc3846b07a72..8783486105d9 100644--- a/posthog/api/oauth/__init__.py+++ b/posthog/api/oauth/__init__.py@@ -14,6 +14,7 @@ from posthog.api.oauth.views import (OAuthConnectDiscoveryInfoView,OAuthIntrospectTokenView,OAuthJwksInfoView,+ OAuthProtectedResourceMetadataView,OAuthRevokeTokenView,OAuthTokenView,OAuthUserInfoView,@@ -29,6 +30,7 @@ __all__ = ["OAuthIntrospectTokenView","OAuthConnectDiscoveryInfoView","OAuthAuthorizationServerMetadataView",+ "OAuthProtectedResourceMetadataView","OAuthJwksInfoView","OAuthUserInfoView","OAuthValidator",diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 25f5146539cf..9ca2a432cf6b 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -3947,6 +3947,49 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):self.assertNotIn("posthog_region", metadata)+class TestOAuthProtectedResourceMetadata(APIBaseTest):+ """Tests for OAuth 2.0 Protected Resource Metadata (RFC 9728)."""++ def test_returns_valid_metadata(self):+ response = self.client.get("/.well-known/oauth-protected-resource")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ metadata = response.json()++ self.assertIn("resource", metadata)+ self.assertEqual(metadata["authorization_servers"], [metadata["resource"]])+ self.assertEqual(metadata["bearer_methods_supported"], ["header"])++ def test_resource_is_a_valid_url(self):+ metadata = self.client.get("/.well-known/oauth-protected-resource").json()+ self.assertRegex(metadata["resource"], r"^https?://")++ def test_authorization_server_is_a_valid_url(self):+ metadata = self.client.get("/.well-known/oauth-protected-resource").json()+ self.assertRegex(metadata["authorization_servers"][0], r"^https?://")++ def test_metadata_includes_scopes(self):+ response = self.client.get("/.well-known/oauth-protected-resource")+ metadata = response.json()++ scopes = metadata["scopes_supported"]+ resource_scopes = [s for s in scopes if ":" in s]+ self.assertGreater(len(resource_scopes), 0, "Should advertise resource scopes like 'event_definition:read'")++ def test_authorization_server_matches_metadata_endpoint(self):+ response = self.client.get("/.well-known/oauth-protected-resource")+ auth_server = response.json()["authorization_servers"][0]++ as_metadata = self.client.get("/.well-known/oauth-authorization-server")+ self.assertEqual(as_metadata.json()["issuer"], auth_server)++ def test_metadata_accessible_without_authentication(self):+ self.client.logout()++ response = self.client.get("/.well-known/oauth-protected-resource")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++class TestOIDCInactiveKeysSetting(SimpleTestCase):"""OIDC_RSA_PRIVATE_KEYS_INACTIVE is assembled from two env vars so multi-line PEMsdon't need delimiter parsing. Only keys that are actually set may be included — andiff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 9c2e13ee67ee..c125fffcb823 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -61,7 +61,7 @@ from posthog.scopes import ()from posthog.security.url_validation import has_authority_bypass_charsfrom posthog.user_permissions import UserPermissions-from posthog.utils import render_template+from posthog.utils import absolute_uri, render_templatefrom posthog.views import login_requiredlogger = structlog.get_logger(__name__)@@ -1492,8 +1492,11 @@ class OAuthAuthorizationServerMetadataView(APIView):authentication_classes = []def get(self, request, *args, **kwargs):- # Build base URL from request- base_url = request.build_absolute_uri("/").rstrip("/")+ # Pin to SITE_URL rather than the request Host header so the advertised+ # endpoints can't be steered to an attacker-controlled origin via Host on+ # permissive ALLOWED_HOSTS, and so issuer matches the protected resource+ # metadata's authorization_servers.+ base_url = absolute_uri().rstrip("/")all_scopes = get_oauth_scopes_supported()@@ -1530,3 +1533,36 @@ class OAuthAuthorizationServerMetadataView(APIView):metadata.update(region_info)return JsonResponse(metadata)+++class OAuthProtectedResourceMetadataView(APIView):+ """+ OAuth 2.0 Protected Resource Metadata (RFC 9728).++ PostHog already points agents at this document via the+ `WWW-Authenticate: Bearer resource_metadata=...` header on 401 responses+ (see posthog/exceptions.py). This serves the document it promises, letting+ a client that hit a 401 discover which authorization server issues tokens+ for this API, which scopes exist, and how to present the token.+ """++ permission_classes = []+ authentication_classes = []++ def get(self, request, *args, **kwargs):+ # Pin to SITE_URL rather than the request Host header: with permissive+ # ALLOWED_HOSTS an attacker could otherwise steer this discovery document+ # to an attacker-controlled origin (matches posthog/exceptions.py).+ base_url = absolute_uri().rstrip("/")++ metadata = {+ # Required by RFC 9728+ "resource": base_url,+ # The same PostHog instance is its own authorization server+ "authorization_servers": [base_url],+ "scopes_supported": get_oauth_scopes_supported(),+ "bearer_methods_supported": ["header"],+ "resource_documentation": "https://posthog.com/docs/api",+ }++ return JsonResponse(metadata)diff --git a/posthog/oauth2_urls.py b/posthog/oauth2_urls.pyindex df9aad333b76..5618b34e1076 100644--- a/posthog/oauth2_urls.py+++ b/posthog/oauth2_urls.py@@ -7,6 +7,7 @@ from posthog.api.oauth import (OAuthConnectDiscoveryInfoView,OAuthIntrospectTokenView,OAuthJwksInfoView,+ OAuthProtectedResourceMetadataView,OAuthRevokeTokenView,OAuthTokenView,OAuthUserInfoView,@@ -30,6 +31,11 @@ urlpatterns = [OAuthAuthorizationServerMetadataView.as_view(),name="oauth-authorization-server-metadata",),+ re_path(+ r"^\.well-known/oauth-protected-resource/?$",+ OAuthProtectedResourceMetadataView.as_view(),+ name="oauth-protected-resource-metadata",+ ),path(".well-known/jwks.json", OAuthJwksInfoView.as_view(), name="jwks-info"),opt_slash_path("oauth/userinfo", OAuthUserInfoView.as_view(), name="user-info"),opt_slash_path("oauth/register", DynamicClientRegistrationView.as_view(), name="register"),