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(oauth): advertise agent auth metadata and serve auth.md (#64152)

Matt Brooker9e9cf4635d3d
diff --git a/posthog/api/oauth/__init__.py b/posthog/api/oauth/__init__.py
index 8783486105d9..5432d9eb687a 100644
--- a/posthog/api/oauth/__init__.py
+++ b/posthog/api/oauth/__init__.py
@@ -11,6 +11,7 @@ from posthog.api.oauth.views import (
OAuthAuthorizationSerializer,
OAuthAuthorizationServerMetadataView,
OAuthAuthorizationView,
+ OAuthClientManifestView,
OAuthConnectDiscoveryInfoView,
OAuthIntrospectTokenView,
OAuthJwksInfoView,
@@ -31,6 +32,7 @@ __all__ = [
"OAuthConnectDiscoveryInfoView",
"OAuthAuthorizationServerMetadataView",
"OAuthProtectedResourceMetadataView",
+ "OAuthClientManifestView",
"OAuthJwksInfoView",
"OAuthUserInfoView",
"OAuthValidator",
diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.py
index 7db1832ca782..65bfed0dba63 100644
--- a/posthog/api/oauth/test_views.py
+++ b/posthog/api/oauth/test_views.py
@@ -36,6 +36,7 @@ from posthog.models.oauth import (
revoke_application_sessions,
)
from posthog.models.team.team import Team
+from posthog.scopes import get_oauth_scopes_supported
from posthog.settings.utils import generate_rsa_private_key_pem
@@ -4030,6 +4031,58 @@ class TestOAuthAuthorizationServerMetadata(APIBaseTest):
metadata = response.json()
self.assertNotIn("posthog_region", metadata)
+ def test_metadata_advertises_agent_auth_identity_assertion(self):
+ response = self.client.get("/.well-known/oauth-authorization-server")
+ agent_auth = response.json()["agent_auth"]
+
+ self.assertTrue(agent_auth["skill"].endswith("/auth.md"))
+ self.assertTrue(agent_auth["identity_endpoint"].endswith("/oauth/token/"))
+ self.assertEqual(agent_auth["identity_types_supported"], ["identity_assertion"])
+ self.assertEqual(
+ agent_auth["identity_assertion"]["assertion_types_supported"],
+ ["urn:ietf:params:oauth:token-type:id-jag"],
+ )
+
+ def test_metadata_does_not_advertise_unbuilt_agent_flows(self):
+ response = self.client.get("/.well-known/oauth-authorization-server")
+ metadata = response.json()
+
+ # The device-claim and revocation-receiver endpoints do not exist yet.
+ self.assertNotIn("claim_endpoint", metadata["agent_auth"])
+ self.assertNotIn("events_endpoint", metadata["agent_auth"])
+
+
+class TestOAuthClientManifest(APIBaseTest):
+ """Tests for the auth.md agent-registration manifest."""
+
+ def test_returns_markdown(self):
+ response = self.client.get("/auth.md")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn("text/markdown", response["Content-Type"])
+
+ def test_manifest_describes_identity_flow(self):
+ response = self.client.get("/auth.md")
+ body = response.content.decode()
+
+ self.assertIn("# PostHog", body)
+ self.assertIn("/oauth/token/", body)
+ self.assertIn("urn:ietf:params:oauth:token-type:id-jag", body)
+ self.assertIn("/.well-known/oauth-protected-resource", body)
+
+ def test_manifest_lists_scopes(self):
+ response = self.client.get("/auth.md")
+ body = response.content.decode()
+
+ for scope in get_oauth_scopes_supported():
+ with self.subTest(scope=scope):
+ self.assertIn(f"`{scope}`", body)
+
+ def test_manifest_accessible_without_authentication(self):
+ self.client.logout()
+
+ response = self.client.get("/auth.md")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
class TestOAuthProtectedResourceMetadata(APIBaseTest):
"""Tests for OAuth 2.0 Protected Resource Metadata (RFC 9728)."""
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 8ccef863a8ad..da80e0ba196b 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -10,6 +10,7 @@ from django.conf import settings
from django.core.exceptions import DisallowedRedirect
from django.db import OperationalError
from django.http import JsonResponse
+from django.shortcuts import render
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@@ -55,6 +56,7 @@ from posthog.scopes import (
downgrade_scopes_to_read_only,
effective_ceiling,
get_oauth_scopes_supported,
+ get_scope_descriptions,
narrow_scopes_to_ceiling,
scopes_outside_ceiling,
scopes_within_ceiling,
@@ -1516,7 +1518,22 @@ class OAuthUserInfoView(UserInfoView):
pass
-class OAuthAuthorizationServerMetadataView(APIView):
+class _PublicMetadataView(APIView):
+ """Shared base for the unauthenticated OAuth discovery documents.
+
+ Pins the base URL to SITE_URL rather than the request Host header so a spoofed
+ Host on a permissive-ALLOWED_HOSTS instance cannot steer these discovery
+ documents to an attacker-controlled origin.
+ """
+
+ permission_classes: list = []
+ authentication_classes: list = []
+
+ def base_url(self) -> str:
+ return absolute_uri().rstrip("/")
+
+
+class OAuthAuthorizationServerMetadataView(_PublicMetadataView):
"""
OAuth 2.0 Authorization Server Metadata (RFC 8414).
@@ -1527,15 +1544,8 @@ class OAuthAuthorizationServerMetadataView(APIView):
is specifically for OAuth-only clients that need DCR support.
"""
- permission_classes = []
- authentication_classes = []
-
def get(self, request, *args, **kwargs):
- # 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("/")
+ base_url = self.base_url()
all_scopes = get_oauth_scopes_supported()
@@ -1566,6 +1576,19 @@ class OAuthAuthorizationServerMetadataView(APIView):
"service_documentation": "https://posthog.com/docs/api",
# Client ID Metadata Document (draft-ietf-oauth-client-id-metadata-document-00)
"client_id_metadata_document_supported": True,
+ # auth.md agent registration profile (https://workos.com/auth-md).
+ # Only flows that actually exist are advertised: ID-JAG identity
+ # assertions at the identity endpoint. The user-claimed device flow
+ # (claim_endpoint) and revocation receiver (events_endpoint) are not
+ # built yet, so they are deliberately omitted rather than advertised.
+ "agent_auth": {
+ "skill": f"{base_url}/auth.md",
+ "identity_endpoint": f"{base_url}/oauth/token/",
+ "identity_types_supported": ["identity_assertion"],
+ "identity_assertion": {
+ "assertion_types_supported": ["urn:ietf:params:oauth:token-type:id-jag"],
+ },
+ },
}
if region_info := get_region_info():
@@ -1574,7 +1597,7 @@ class OAuthAuthorizationServerMetadataView(APIView):
return JsonResponse(metadata)
-class OAuthProtectedResourceMetadataView(APIView):
+class OAuthProtectedResourceMetadataView(_PublicMetadataView):
"""
OAuth 2.0 Protected Resource Metadata (RFC 9728).
@@ -1585,14 +1608,8 @@ class OAuthProtectedResourceMetadataView(APIView):
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("/")
+ base_url = self.base_url()
metadata = {
# Required by RFC 9728
@@ -1605,3 +1622,37 @@ class OAuthProtectedResourceMetadataView(APIView):
}
return JsonResponse(metadata)
+
+
+# OIDC scopes have no entry in get_scope_descriptions(), which only covers obj:action scopes.
+_OIDC_SCOPE_DESCRIPTIONS = {
+ "openid": "Sign in and read your user identifier",
+ "profile": "Read your basic profile",
+ "email": "Read your email address",
+}
+
+
+class OAuthClientManifestView(_PublicMetadataView):
+ """
+ auth.md agent-registration manifest (https://workos.com/auth-md).
+
+ A Markdown document agents read to learn how to register and authenticate
+ against PostHog without a human-driven signup. Served at /auth.md, the
+ location the authorization server metadata's `agent_auth.skill` points at.
+ """
+
+ def get(self, request, *args, **kwargs):
+ base_url = self.base_url()
+
+ descriptions = get_scope_descriptions()
+ scopes = [
+ (scope, descriptions[scope] if scope in descriptions else _OIDC_SCOPE_DESCRIPTIONS.get(scope, scope))
+ for scope in get_oauth_scopes_supported()
+ ]
+
+ return render(
+ request,
+ "auth_md.md",
+ {"base_url": base_url, "scopes": scopes},
+ content_type="text/markdown; charset=utf-8",
+ )
diff --git a/posthog/oauth2_urls.py b/posthog/oauth2_urls.py
index 5618b34e1076..ba0e4e38f8c3 100644
--- a/posthog/oauth2_urls.py
+++ b/posthog/oauth2_urls.py
@@ -4,6 +4,7 @@ from posthog.api.oauth import (
DynamicClientRegistrationView,
OAuthAuthorizationServerMetadataView,
OAuthAuthorizationView,
+ OAuthClientManifestView,
OAuthConnectDiscoveryInfoView,
OAuthIntrospectTokenView,
OAuthJwksInfoView,
@@ -36,6 +37,7 @@ urlpatterns = [
OAuthProtectedResourceMetadataView.as_view(),
name="oauth-protected-resource-metadata",
),
+ path("auth.md", OAuthClientManifestView.as_view(), name="auth-md-manifest"),
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"),
diff --git a/posthog/templates/auth_md.md b/posthog/templates/auth_md.md
new file mode 100644
index 000000000000..60eb58d6c835
--- /dev/null
+++ b/posthog/templates/auth_md.md
@@ -0,0 +1,47 @@
+{% autoescape off %}# PostHog
+
+PostHog is an open-source platform for product analytics, session replay, feature flags, experiments, surveys, and data warehousing.
+
+## Creating an account
+
+- AI wizard: `npx @posthog/wizard@latest --signup` creates a new account and project from the command line, with no signup form. This is the most direct path for a new user. See https://posthog.com/docs/ai-engineering/ai-wizard
+- Provisioning API: partners and platforms can create accounts for their users and deep-link them in. See https://posthog.com/docs/integrate/provisioning
+
+## Authenticating an existing user
+
+- OAuth 2.0: standard authorization-code flow for an app acting on behalf of a user. See https://posthog.com/docs/api/oauth
+- Personal API keys: long-lived keys for scripts and server-to-server use. See https://posthog.com/docs/api#authentication
+
+## Agent registration via ID-JAG (Enterprise, beta)
+
+Available on the Enterprise plan with XAA enabled, and currently in beta, so most clients should use one of the options above. With it configured, an agent presents an [ID-JAG](https://xaa.dev) identity assertion (`identity_assertion`) to the token endpoint using the JWT-bearer grant (`urn:ietf:params:oauth:grant-type:jwt-bearer`) and receives a scoped, short-lived OAuth access token bound to the user. See https://posthog.com/docs/settings/id-jag
+
+- Identity endpoint: `{{ base_url }}/oauth/token/`
+- Assertion type: `urn:ietf:params:oauth:token-type:id-jag`
+- Protected resource metadata: `{{ base_url }}/.well-known/oauth-protected-resource`
+- Authorization server metadata: `{{ base_url }}/.well-known/oauth-authorization-server`
+
+The user-claimed device flow (`service_auth`, `anonymous`) is not supported yet.
+
+## Scopes
+
+{% for scope, description in scopes %}- `{{ scope }}` — {{ description }}
+{% endfor %}
+
+## Changing scopes
+
+Access tokens carry the scope set granted when they were issued.
+Scopes do not change on refresh — refreshing a token returns the same or narrower scopes, never more.
+
+If your app needs additional scopes, for example a newly required scope, or a request that returns `403` because the token is missing a required scope, start a new authorization at `{{ base_url }}/oauth/authorize/`.
+The user re-consents and the new token carries the updated scopes.
+PostHog does not push new scopes to existing tokens; the client must re-authorize.
+
+## Links
+
+- Pricing: https://posthog.com/pricing
+- Terms: https://posthog.com/terms
+- Privacy: https://posthog.com/privacy
+- API docs: https://posthog.com/docs/api
+- Contact: [email protected]
+{% endautoescape %}