: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
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const AUTHORITATIVE_METADATA = {
issuer: 'https://us.posthog.com',
authorization_endpoint: 'https://us.posthog.com/oauth/authorize/',
token_endpoint: 'https://us.posthog.com/oauth/token/',
revocation_endpoint: 'https://us.posthog.com/oauth/revoke/',
introspection_endpoint: 'https://us.posthog.com/oauth/introspect/',
userinfo_endpoint: 'https://us.posthog.com/oauth/userinfo/',
jwks_uri: 'https://us.posthog.com/.well-known/jwks.json',
registration_endpoint: 'https://us.posthog.com/oauth/register/',
scopes_supported: ['openid', 'profile', 'email'],
response_types_supported: ['code'],
response_modes_supported: ['query'],
grant_types_supported: ['authorization_code', 'refresh_token', 'urn:ietf:params:oauth:grant-type:jwt-bearer'],
authorization_grant_profiles_supported: ['urn:ietf:params:oauth:grant-profile:id-jag'],
token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
code_challenge_methods_supported: ['S256'],
service_documentation: 'https://posthog.com/docs/model-context-protocol',
client_id_metadata_document_supported: true,
agent_auth: {
skill: 'https://us.posthog.com/auth.md',
identity_endpoint: 'https://us.posthog.com/oauth/token/',
identity_types_supported: ['identity_assertion'],
},
posthog_region: 'us',
posthog_base_url: 'https://us.posthog.com',
}
const AUTHORITATIVE_OPENID_CONFIGURATION = {
issuer: 'https://us.posthog.com',
authorization_endpoint: 'https://us.posthog.com/oauth/authorize/',
token_endpoint: 'https://us.posthog.com/oauth/token/',
userinfo_endpoint: 'https://us.posthog.com/oauth/userinfo/',
jwks_uri: 'https://us.posthog.com/.well-known/jwks.json',
registration_endpoint: 'https://us.posthog.com/oauth/register/',
scopes_supported: ['openid', 'profile', 'email'],
claims_supported: ['email', 'email_verified', 'family_name', 'given_name', 'sub'],
subject_types_supported: ['public'],
id_token_signing_alg_values_supported: ['RS256'],
}
describe('handleMetadata', () => {
beforeEach(() => {
vi.resetModules()
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(AUTHORITATIVE_METADATA),
})
)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('returns valid OAuth authorization server metadata with endpoints rewritten', async () => {
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
const response = await handleMetadata(request)
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
expect(data.issuer).toBe('https://oauth.posthog.com')
expect(data.authorization_endpoint).toBe('https://oauth.posthog.com/oauth/authorize/')
expect(data.token_endpoint).toBe('https://oauth.posthog.com/oauth/token/')
expect(data.revocation_endpoint).toBe('https://oauth.posthog.com/oauth/revoke/')
expect(data.introspection_endpoint).toBe('https://oauth.posthog.com/oauth/introspect/')
expect(data.userinfo_endpoint).toBe('https://oauth.posthog.com/oauth/userinfo/')
expect(data.jwks_uri).toBe('https://oauth.posthog.com/.well-known/jwks.json')
expect(data.registration_endpoint).toBe('https://oauth.posthog.com/oauth/register/')
})
it('preserves non-endpoint fields from authoritative metadata', async () => {
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
const response = await handleMetadata(request)
const data = (await response.json()) as Record<string, unknown>
expect(data.scopes_supported).toEqual(AUTHORITATIVE_METADATA.scopes_supported)
expect(data.response_types_supported).toEqual(AUTHORITATIVE_METADATA.response_types_supported)
expect(data.grant_types_supported).toEqual(AUTHORITATIVE_METADATA.grant_types_supported)
expect(data.authorization_grant_profiles_supported).toEqual(
AUTHORITATIVE_METADATA.authorization_grant_profiles_supported
)
expect(data.code_challenge_methods_supported).toContain('S256')
expect(data.service_documentation).toBe(AUTHORITATIVE_METADATA.service_documentation)
expect(data.client_id_metadata_document_supported).toBe(true)
})
it('rewrites the agent_auth endpoints onto the proxy', async () => {
// Left pointing at US, an EU user's ID-JAG assertion goes to the wrong region.
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
const response = await handleMetadata(request)
const data = (await response.json()) as { agent_auth: Record<string, unknown> }
expect(data.agent_auth.skill).toBe('https://oauth.posthog.com/auth.md')
expect(data.agent_auth.identity_endpoint).toBe('https://oauth.posthog.com/oauth/token/')
})
it('keeps posthog_base_url pointing at the region that issues the tokens', async () => {
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
const response = await handleMetadata(request)
const data = (await response.json()) as Record<string, unknown>
expect(data.posthog_base_url).toBe('https://us.posthog.com')
})
it('caches the authoritative metadata', async () => {
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
await handleMetadata(request)
await handleMetadata(request)
expect(fetch).toHaveBeenCalledTimes(1)
})
it('re-fetches after cache expires', async () => {
vi.useFakeTimers()
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
await handleMetadata(request)
expect(fetch).toHaveBeenCalledTimes(1)
// Advance past the 10-minute cache TTL
vi.advanceTimersByTime(601 * 1000)
await handleMetadata(request)
expect(fetch).toHaveBeenCalledTimes(2)
vi.useRealTimers()
})
it('returns 502 when authoritative metadata fetch fails and no cache exists', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: false,
statusText: 'Internal Server Error',
})
)
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
const response = await handleMetadata(request)
expect(response.status).toBe(502)
const data = (await response.json()) as Record<string, unknown>
expect(data.error).toBe('server_error')
})
it('returns 502 when metadata refresh fails after cache expires', async () => {
vi.useFakeTimers()
const { handleMetadata } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/oauth-authorization-server')
// Populate cache with a successful fetch
const response1 = await handleMetadata(request)
expect(response1.status).toBe(200)
// Expire cache
vi.advanceTimersByTime(601 * 1000)
// Make fetch fail
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: false,
statusText: 'Service Unavailable',
})
)
const response2 = await handleMetadata(request)
expect(response2.status).toBe(502)
const data = (await response2.json()) as Record<string, unknown>
expect(data.error).toBe('server_error')
vi.useRealTimers()
})
})
describe('handleOpenIdConfiguration', () => {
beforeEach(() => {
vi.resetModules()
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(AUTHORITATIVE_OPENID_CONFIGURATION),
})
)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('serves the OIDC discovery document a relying party needs to sign users in', async () => {
// Without it the proxy is not a discoverable OpenID provider.
const { handleOpenIdConfiguration } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/openid-configuration')
const response = await handleOpenIdConfiguration(request)
const data = (await response.json()) as Record<string, unknown>
expect(response.status).toBe(200)
expect(data.issuer).toBe('https://oauth.posthog.com')
expect(data.userinfo_endpoint).toBe('https://oauth.posthog.com/oauth/userinfo/')
expect(data.jwks_uri).toBe('https://oauth.posthog.com/.well-known/jwks.json')
expect(data.claims_supported).toEqual(AUTHORITATIVE_OPENID_CONFIGURATION.claims_supported)
})
it('is readable cross-origin', async () => {
const { handleOpenIdConfiguration } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/.well-known/openid-configuration')
const response = await handleOpenIdConfiguration(request)
expect(response.headers.get('access-control-allow-origin')).toBe('*')
})
})
describe('handleClientManifest', () => {
beforeEach(() => {
vi.resetModules()
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response('Authorize at https://us.posthog.com/oauth/authorize/ with scope `openid`.', {
status: 200,
})
)
)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('serves the manifest the metadata advertises, with its URLs on the proxy', async () => {
// `agent_auth.skill` points agents at this path on the proxy, which had no route for it.
const { handleClientManifest } = await import('@/handlers/metadata')
const request = new Request('https://oauth.posthog.com/auth.md')
const response = await handleClientManifest(request)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('text/markdown')
expect(await response.text()).toBe(
'Authorize at https://oauth.posthog.com/oauth/authorize/ with scope `openid`.'
)
})
})