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(agent-platform): wire identity admission into the chat/HTTP trigger (#70582)

Dylan Martin7ffe62edb205
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 92e3b078f189..d0bd7e6a0136 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6767,9 +6767,9 @@ snapshots:
scenes-app-sessionattributionexplorer--session-attribution-explorer--light:
hash: v1.k794b7964.001061d4b295c8f6027e5e0a7316a65883e6c0e08277ae097d3a38d64338795d.CGXqBM7ryEQypLc9SCN1GLFuIXXf0AnFxiwLLaXeFhY
scenes-app-settings-authentication-domains--boost-needs-upgrade--dark:
- hash: v1.k794b7964.a9dd979b05bef31a58e3329ad5dc6f387f88d8c22a90d26edb12eba38a4dcdd0.sB__kQGt5ZkZrn1Ov-jyzf-5wh6eIXfyzvSRnnPGcWY
+ hash: v1.k794b7964.d2354aea8e40abfcfeb18691d15e48abc24724460dbc0118185c750d3f8ce6d1.hd_A7ve1fnL_3LEtdoDKSxqRHrLXH_6hpuXK1o1q6yY
scenes-app-settings-authentication-domains--boost-needs-upgrade--light:
- hash: v1.k794b7964.9b95cc6d26ebd355a55b47a0cbb03da66a76f41bcf75e36ecade5c5183906cf5.850LjAGad2hsHzAM8ZIDo0Hh3ZYsb3qNCQLkicq5W7k
+ hash: v1.k794b7964.e3d329e84737f53476a92d2c93d7f1b252418df229158d771028c74d46818043.bhONXlHgi8Q2Fy3D78gDCNp00cYvbdRVrp46JTDdG6M
scenes-app-settings-authentication-domains--enterprise-mixed--dark:
hash: v1.k794b7964.f2b4d4a69699c20a9fa1437a8fdf83a7bc23525502ac0b9e8bb559a4b0afec4f.Gxj4Sbt2QBXarWrXM5J5IwaOnjP9ecw9ehbXyBubJhI
scenes-app-settings-authentication-domains--enterprise-mixed--light:
diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.md
index 9ee6eb91f562..6d6f84d34ab5 100644
--- a/products/agent_platform/docs/identity-and-tools.md
+++ b/products/agent_platform/docs/identity-and-tools.md
@@ -109,13 +109,18 @@ Resolution order (fail-closed — never enqueue on doubt):
2. **Per-request bearer** the provider can `verifyBearer` (HTTP) → verified on
every request, then upsert canonical + credential + binding. A
present-but-invalid bearer goes straight to re-auth; a stored binding never
- rescues a stale token (freshness wins).
+ rescues a stale token (freshness wins). Only the provider's judgement on the
+ token (userinfo 401/403) reads as invalid — userinfo being unreachable or
+ erroring is a provider failure: fail closed and retryable (chat answers 503),
+ never re-auth.
3. **Durable binding** (Slack/Discord, where the proof is the prior link, not a
token on this request) → admit, but only while the binding's provider still
matches and its authoritative credential is still active; a
dangling/stale/revoked one falls through to re-auth.
4. Otherwise → `auth_required`: deliver an auth block (a link) and enqueue
- nothing. The OAuth callback runs `AdmissionService.complete`, which creates
+ nothing. Slack delivers it privately (ephemeral) and answers 200 to stop retries;
+ chat/HTTP returns it in the response itself as `401 { auth_required, provider, authorize_url }`.
+ The OAuth callback runs `AdmissionService.complete`, which creates
the canonical identity, stores the authoritative credential under it, and
writes the binding.
@@ -124,8 +129,19 @@ future turn (and the same person via another transport) resolves the same
identity. Secondary providers' credentials (below) hang off the **canonical**
`agent_user`, so a person's GitHub/Grafana links are shared across transports.
-> Wired for `slack` triggers only today; the spec schema fail-closes a spec that
-> sets `authoritative_provider` alongside a not-yet-wired trigger type.
+> Wired for `slack` and `chat` triggers today; the spec schema fail-closes a spec that
+> sets `authoritative_provider` alongside a not-yet-wired trigger type (`webhook`, `mcp`, `cron`).
+> On chat, `/run` and `/send` resolve admission before any session work,
+> and an admitted principal carries `canonical_agent_user_id` so secondary
+> credentials key off the canonical identity on HTTP too.
+> Principals with no per-user subject (anonymous, shared-secret, internal) are
+> refused outright (403) — a coexisting `public`/machine auth mode cannot void the gate.
+> JWT subjects are issuer-scoped via an injective encoding of
+> `(issuer_secret_ref, sub)` (`jwtPrincipalSubject`): two configured `jwt` modes
+> are separate trust domains, so colliding `sub`s never resolve each other's
+> binding or canonical identity.
+> A per-request PostHog bearer satisfies a `kind: posthog` authoritative provider inline
+> (`verifyBearer` exists only when the provider has a `userinfo_url`).
## Linked identities
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.test.ts b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.test.ts
new file mode 100644
index 000000000000..6534affe6d7a
--- /dev/null
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.test.ts
@@ -0,0 +1,99 @@
+/**
+ * `httpTransportClaim` — the chat/HTTP claim builder feeding edge admission.
+ * The load-bearing rules:
+ *
+ * - The bearer rides on the claim ONLY when it's a credential for the
+ * authoritative provider (posthog bearer ↔ `kind: posthog`). Attaching an
+ * unrelated token trips admission's freshness rule (present-but-invalid
+ * bearer → re-auth, the durable binding is never consulted) and locks out
+ * users who already linked.
+ * - Machine/anonymous principals yield no claim at all: a claim keyed on a
+ * shared principal (e.g. `shared_secret`) would let one secret holder bind
+ * an identity every other holder is then admitted as. The chat trigger
+ * fails closed (403) on a null claim — see `admitChatPrincipal`.
+ */
+
+import { describe, expect, it } from 'vitest'
+
+import { AgentSpecSchema, type AgentRevision, type SessionPrincipal } from '@posthog/agent-shared'
+
+import { httpTransportClaim } from './admission-gate'
+
+function revisionWith(spec: Record<string, unknown>): AgentRevision {
+ return {
+ id: 'rev-1',
+ application_id: 'app-1',
+ parent_revision_id: null,
+ created_by_id: null,
+ created_at: new Date(0).toISOString(),
+ state: 'live',
+ bundle_uri: 's3://x/',
+ bundle_sha256: null,
+ spec: AgentSpecSchema.parse({
+ model: 'test/x',
+ triggers: [{ type: 'chat', config: {}, auth: { modes: [{ type: 'posthog' }] } }],
+ ...spec,
+ }),
+ encrypted_env: null,
+ }
+}
+
+const POSTHOG_AUTHORITATIVE = {
+ identity_providers: [{ kind: 'posthog', id: 'posthog' }],
+ authoritative_provider: 'posthog',
+}
+const OAUTH2_AUTHORITATIVE = {
+ identity_providers: [
+ {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: 'https://idp.test/authorize',
+ token_url: 'https://idp.test/token',
+ userinfo_url: 'https://idp.test/userinfo',
+ client_id: 'c',
+ },
+ ],
+ authoritative_provider: 'dogs',
+}
+
+const POSTHOG_PRINCIPAL: SessionPrincipal = {
+ kind: 'posthog',
+ user_id: 'ph-uuid-1',
+ team_id: 1,
+ email: '[email protected]',
+}
+const JWT_PRINCIPAL: SessionPrincipal = { kind: 'jwt', issuer_secret_ref: 'S', sub: 'external-7', claims: {} }
+
+describe('httpTransportClaim', () => {
+ it('posthog principal under a posthog authoritative provider attaches the bearer (per-request proof)', () => {
+ const claim = httpTransportClaim(POSTHOG_PRINCIPAL, 'phx_tok', revisionWith(POSTHOG_AUTHORITATIVE))
+ expect(claim).toMatchObject({ transport: 'posthog', subjectId: 'ph-uuid-1', bearer: { token: 'phx_tok' } })
+ })
+
+ it('posthog principal under an oauth2 authoritative provider does NOT attach the bearer (binding path stays reachable)', () => {
+ const claim = httpTransportClaim(POSTHOG_PRINCIPAL, 'phx_tok', revisionWith(OAUTH2_AUTHORITATIVE))
+ expect(claim).toMatchObject({ transport: 'posthog', subjectId: 'ph-uuid-1' })
+ expect(claim?.bearer).toBeUndefined()
+ })
+
+ it('jwt claims are issuer-scoped — a colliding sub under another issuer is a different subject — and never attach the JWT as a bearer', () => {
+ const claim = httpTransportClaim(JWT_PRINCIPAL, 'a.b.c', revisionWith(OAUTH2_AUTHORITATIVE))
+ expect(claim).toMatchObject({ transport: 'jwt', subjectId: JSON.stringify(['S', 'external-7']) })
+ expect(claim?.bearer).toBeUndefined()
+ const otherIssuer = httpTransportClaim(
+ { ...JWT_PRINCIPAL, issuer_secret_ref: 'S2' },
+ 'a.b.c',
+ revisionWith(OAUTH2_AUTHORITATIVE)
+ )
+ expect(otherIssuer?.subjectId).not.toBe(claim?.subjectId)
+ })
+
+ it.each<SessionPrincipal>([
+ { kind: 'anonymous' },
+ { kind: 'shared_secret', team_id: 1 },
+ { kind: 'posthog_internal', team_id: 1 },
+ { kind: 'service', team_id: 1, id: 'cron' },
+ ])('$kind principal yields no claim — no per-sender human identity to admit', (principal) => {
+ expect(httpTransportClaim(principal, 'tok', revisionWith(OAUTH2_AUTHORITATIVE))).toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
index ec3709245b94..87d55f7e0854 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
@@ -4,7 +4,7 @@
* null only when the agent declares no authoritative provider (passthrough).
* The stores are required — the ingress always wires them — so a null return is
* unambiguously "passthrough", never "misconfigured" (which previously fell
- * open). Shared by the Slack trigger (resolve) and the
+ * open). Shared by the Slack trigger, the chat trigger (resolve), and the
* `/link/:provider/callback` route (complete).
*/
@@ -12,6 +12,7 @@ import {
AdmissionService,
buildIdentityRegistry,
buildLinkCallbackUrl,
+ jwtPrincipalSubject,
type AgentRevision,
type EncryptedFields,
type HttpFetcher,
@@ -19,7 +20,9 @@ import {
type IdentityLinkStateStore,
type IdentityStore,
type IngressRoutingMode,
+ type SessionPrincipal,
type TransportBindingStore,
+ type TransportClaim,
} from '@posthog/agent-shared'
export interface AdmissionDepsBundle {
@@ -38,6 +41,65 @@ export interface AdmissionDepsBundle {
publicBaseUrl?: string
}
+/**
+ * Build the transport claim for an authenticated HTTP (chat) principal.
+ *
+ * Only user-shaped principals (posthog, jwt) carry a stable per-sender subject
+ * admission can bind a canonical identity to. Machine principals
+ * (shared_secret, posthog_internal, service) and the public opt-in anonymous
+ * principal have no human behind the transport to resolve — returning null
+ * makes the chat trigger FAIL CLOSED (403, nothing enqueued): an authoritative
+ * provider means "verified human identity required", and a coexisting
+ * public/shared-secret/internal auth mode must not silently void that gate.
+ * (Minting a claim instead would be worse — a claim keyed on a shared
+ * principal would let one secret holder bind an identity every other holder
+ * is then admitted as.)
+ *
+ * `transport` deliberately equals the principal kind (`posthog` / `jwt`), so
+ * the transport AgentUser admission creates is the SAME row
+ * `agentUserIdForPrincipal` maps the principal to — bindings and per-asker
+ * secondary credentials hang off one AgentUser, not two parallel ones.
+ *
+ * The request bearer rides on the claim ONLY when it is a credential FOR the
+ * authoritative provider (a PostHog bearer on a `kind: posthog` provider).
+ * Attaching an unrelated token (a JWT, or a PostHog bearer under an oauth2
+ * authoritative provider) would trip admission's freshness rule — a
+ * present-but-invalid bearer forces re-auth without ever consulting the
+ * durable binding, locking out users who already linked.
+ */
+export function httpTransportClaim(
+ principal: SessionPrincipal,
+ bearer: string | null,
+ revision: AgentRevision
+): TransportClaim | null {
+ switch (principal.kind) {
+ case 'posthog': {
+ const authoritative = revision.spec.identity_providers.find(
+ (p) => p.id === revision.spec.authoritative_provider
+ )
+ const bearerIsProviderCredential = authoritative?.kind === 'posthog'
+ // `subjectId` (the PostHog user UUID) must equal the subject the
+ // provider's userinfo proves for this bearer — the transport row
+ // keys on the former, the canonical row on the latter, and
+ // admission assumes they name the same person for `kind: posthog`.
+ return {
+ transport: 'posthog',
+ subjectId: principal.user_id,
+ ...(bearer && bearerIsProviderCredential ? { bearer: { token: bearer } } : {}),
+ ...(principal.email ? { attributes: { email: principal.email } } : {}),
+ }
+ }
+ case 'jwt':
+ // Issuer-scoped (see `jwtPrincipalSubject`): colliding `sub`s across
+ // two configured jwt modes must not resolve each other's binding.
+ // The JWT proves the transport claim, not the authoritative identity —
+ // it is never attached as a bearer.
+ return { transport: 'jwt', subjectId: jwtPrincipalSubject(principal) }
+ default:
+ return null
+ }
+}
+
/** Build an `AdmissionService` for a revision, or null when the agent declares
* no authoritative provider (passthrough). `slug` is the agent's slug — in
* domain mode the OAuth callback lands on that agent's own host. */
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
index 137e75142e3a..3c0d1622dead 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/chat.ts
@@ -9,13 +9,26 @@
* modes before the handler, so each handler receives an authenticated
* `principal`. The write/stream paths additionally enforce session ownership
* (ACL) on the principal the guard produced.
+ *
+ * Edge admission: when the agent declares an `authoritative_provider`, EVERY
+ * session-touching route (`/run`, `/send`, `/cancel`, `/listen`,
+ * `/client_tool_result`) must additionally resolve a verified canonical
+ * identity for the principal before touching the session — unauthenticated
+ * callers get `401 { auth_required }` with a link (see `admitChatPrincipal`).
+ * Admission also stamps `canonical_agent_user_id` on the principal, which the
+ * ACL's canonical match requires, so skipping it on any route would 403 the
+ * legitimate owner of an admitted session.
*/
import { z } from 'zod'
-import { buildClientToolResultMarker, TRIGGER_ROUTES } from '@posthog/agent-shared'
+import { buildClientToolResultMarker, createLogger, TRIGGER_ROUTES, type SessionPrincipal } from '@posthog/agent-shared'
+
+const log = createLogger('chat-trigger')
import { buildElevationResponse, principalDisplay, recordElevationRequest, requireAclAccess } from '../enqueue/acl'
+import { buildAdmission, httpTransportClaim } from '../enqueue/admission-gate'
+import { readBearer } from '../enqueue/auth'
import { enqueueOrResume } from '../enqueue/enqueue'
import { activeStreams } from '../metrics'
import {
@@ -28,10 +41,69 @@ import {
import { getOwnedSession } from './session-access'
import { defineRoute, type AuthedRouteCtx, type TriggerModule } from './types'
+/**
+ * Edge admission for the HTTP/chat transport (mirrors the Slack trigger): if
+ * the agent declares an authoritative provider, the claim must resolve a
+ * verified identity BEFORE any session work. Unauthenticated → respond
+ * `401 { auth_required, provider, authorize_url }`; a principal that cannot
+ * carry a per-user claim (anonymous/machine) → 403; provider/config error →
+ * fail closed with a 500. Returns the principal to use downstream — stamped
+ * with `canonical_agent_user_id` when admitted — or null when the response
+ * has already been written.
+ */
+async function admitChatPrincipal(ctx: AuthedRouteCtx<unknown>): Promise<SessionPrincipal | null> {
+ const { req, res, deps, resolved } = ctx
+ const admission = buildAdmission(deps, resolved.revision, resolved.application.slug)
+ if (!admission) {
+ return ctx.principal
+ }
+ const claim = httpTransportClaim(ctx.principal, readBearer(req), resolved.revision)
+ if (!claim) {
+ // Machine principals and the public opt-in anonymous principal carry no
+ // per-sender human identity to verify (see `httpTransportClaim`), and
+ // the authoritative gate is absolute: fail closed rather than let a
+ // coexisting public/shared-secret/internal auth mode silently void it.
+ // An agent that wants machine or anonymous callers must not declare an
+ // authoritative_provider.
+ res.status(403).json({ error: 'admission_unsupported_principal', principal_kind: ctx.principal.kind })
+ return null
+ }
+ const result = await admission.resolve(claim, {
+ application: resolved.application,
+ revision: resolved.revision,
+ })
+ if (result.kind === 'auth_required') {
+ // Unlike Slack (which must 200 to stop retries and delivers the link
+ // out-of-band), HTTP callers get the auth block in the response itself.
+ res.status(401).json({
+ error: 'auth_required',
+ auth_required: true,
+ provider: result.provider,
+ authorize_url: result.authorizeUrl,
+ })
+ return null
+ }
+ if (result.kind === 'error') {
+ log.warn({ slug: resolved.application.slug, reason: result.reason }, 'chat_admission_error')
+ // Provider unavailability (userinfo down/timeout) is retryable — the
+ // caller's token may be perfectly valid — so answer 503, not 500.
+ const status = result.reason === 'authoritative_provider_unavailable' ? 503 : 500
+ res.status(status).json({ error: 'admission_failed', reason: result.reason })
+ return null
+ }
+ if (result.kind === 'admitted' && (ctx.principal.kind === 'posthog' || ctx.principal.kind === 'jwt')) {
+ return { ...ctx.principal, canonical_agent_user_id: result.identity.canonicalId }
+ }
+ return ctx.principal
+}
+
async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>): Promise<void> {
const { res, deps, resolved } = ctx
const { message, external_key: externalKey = null, supported_client_tools: supportedClientTools } = ctx.parsed
- const sessionPrincipal = ctx.principal
+ const sessionPrincipal = await admitChatPrincipal(ctx)
+ if (!sessionPrincipal) {
+ return
+ }
const outcome = await enqueueOrResume(
{ queue: deps.queue },
{
@@ -65,13 +137,20 @@ async function runHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatRunBodySchema>>
ok: true,
session_id: outcome.sessionId,
resumed: outcome.isResume,
- principal: ctx.principal,
+ principal: sessionPrincipal,
})
}
async function sendHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatSendBodySchema>>): Promise<void> {
const { res, deps, resolved } = ctx
const { session_id: sessionId, message, client_tool_result } = ctx.parsed
+ // Admission runs per message (like the Slack path) and before the session
+ // lookup, so a revoked binding stops advancing a session — and an
+ // unadmitted caller can't probe session ids through the 404.
+ const incomingPrincipal = await admitChatPrincipal(ctx)
+ if (!incomingPrincipal) {
+ return
+ }
const existing = await getOwnedSession(ctx, sessionId)
if (!existing) {
res.status(404).json({ error: 'session_not_found' })
@@ -79,7 +158,6 @@ async function sendHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatSendBodySchema
}
// Strict principal match: the guard authenticated the caller; compare to
// the principal stored at /run time.
- const incomingPrincipal = ctx.principal
const aclCheck = requireAclAccess(existing, incomingPrincipal)
if (aclCheck.kind === 'denied') {
const proposed: string =
@@ -149,12 +227,20 @@ async function sendHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatSendBodySchema
async function cancelHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatCancelBodySchema>>): Promise<void> {
const { res, deps } = ctx
const { session_id: sessionId } = ctx.parsed
+ // Admission first (mirrors /send): an admitted session's stored principal
+ // carries canonical_agent_user_id, so ACL only recognises the owner once
+ // the incoming principal is stamped too — and a revoked binding loses
+ // control of the session, not just the ability to advance it.
+ const incomingPrincipal = await admitChatPrincipal(ctx)
+ if (!incomingPrincipal) {
+ return
+ }
const existing = await getOwnedSession(ctx, sessionId)
if (!existing) {
res.status(404).json({ error: 'session_not_found' })
return
}
- if (requireAclAccess(existing, ctx.principal).kind === 'denied') {
+ if (requireAclAccess(existing, incomingPrincipal).kind === 'denied') {
res.status(403).json({ error: 'forbidden' })
return
}
@@ -193,6 +279,13 @@ async function cancelHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatCancelBodySc
async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQuerySchema>>): Promise<void> {
const { req, res, deps, resolved } = ctx
const { session_id: sessionId } = ctx.parsed
+ // Admission first (mirrors /send): stamps canonical_agent_user_id so ACL
+ // recognises the admitted owner, and a revoked binding can no longer
+ // replay the conversation.
+ const incomingPrincipal = await admitChatPrincipal(ctx)
+ if (!incomingPrincipal) {
+ return
+ }
const existing = await getOwnedSession(ctx, sessionId)
if (!existing) {
res.status(404).json({ error: 'session_not_found' })
@@ -201,7 +294,7 @@ async function listenHandler(ctx: AuthedRouteCtx<z.infer<typeof ChatListenQueryS
// The stream replays the whole conversation, so gate it the same as the
// write paths. EventSource can't set headers, so the bearer rides in
// `?token=` (handled in readBearer, which the guard already consumed).
- if (requireAclAccess(existing, ctx.principal).kind === 'denied') {
+ if (requireAclAccess(existing, incomingPrincipal).kind === 'denied') {
res.status(403).json({ error: 'forbidden' })
return
}
@@ -289,6 +382,12 @@ async function clientToolResultHandler(
): Promise<void> {
const { res, deps } = ctx
const { session_id: sessionId, call_id, result, error } = ctx.parsed
+ // Admission first (mirrors /send): stamps canonical_agent_user_id so ACL
+ // recognises the admitted owner of the running turn.
+ const incomingPrincipal = await admitChatPrincipal(ctx)
+ if (!incomingPrincipal) {
+ return
+ }
const existing = await getOwnedSession(ctx, sessionId)
if (!existing) {
res.status(404).json({ error: 'no_session' })
@@ -296,7 +395,7 @@ async function clientToolResultHandler(
}
// A tool result feeds straight into the running turn — confirm session
// ownership before publishing it.
- if (requireAclAccess(existing, ctx.principal).kind === 'denied') {
+ if (requireAclAccess(existing, incomingPrincipal).kind === 'denied') {
res.status(403).json({ error: 'forbidden' })
return
}
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/types.ts b/products/agent_platform/services/agent-ingress/src/triggers/types.ts
index fb5a4323d07a..db3bc0c68569 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/types.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/types.ts
@@ -74,7 +74,7 @@ export interface TriggerDeps {
routingMode?: RoutingMode
domainSuffix?: string
publicBaseUrl?: string
- /** Edge-admission stores (Slack trigger). When the agent declares an
+ /** Edge-admission stores (Slack + chat triggers). When the agent declares an
* authoritative_provider, an unauthenticated claim gets an auth link instead
* of a session. See `enqueue/admission-gate.ts`. */
identityLinks: IdentityLinkStateStore
diff --git a/products/agent_platform/services/agent-shared/src/runtime/admission.test.ts b/products/agent_platform/services/agent-shared/src/runtime/admission.test.ts
index 20a0d2b7d265..1c5712477752 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/admission.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/admission.test.ts
@@ -19,7 +19,7 @@ import type { HttpFetcher } from './http-client'
import type { IdentityCredentialStore, LinkedCredential, PutLinkedCredentialInput } from './identity-credential-store'
import type { CreateLinkStateInput, IdentityLinkStateStore, LinkState } from './identity-link-state-store'
import type { BearerVerification, IdentityProvider } from './identity-provider'
-import { MapIdentityProviderRegistry } from './identity-provider'
+import { IdentityProviderUnavailableError, MapIdentityProviderRegistry } from './identity-provider'
import { Oauth2AuthProvider } from './oauth2-identity-provider'
import type { TransportClaim } from './transport'
import { MemoryTransportBindingStore } from './transport-binding-store'
@@ -422,6 +422,43 @@ describe('AdmissionService', () => {
}
})
+ it('HTTP: provider unavailability fails closed as a retryable error — NOT auth_required', async () => {
+ // A userinfo brownout must never read as "token invalid": answering
+ // auth_required would send every holder of a valid bearer to re-auth.
+ const provider: IdentityProvider = {
+ id: 'work',
+ credentialTarget: 'work',
+ establishesIdentity: true,
+ binding: 'principal',
+ allowedHosts: () => ['work.example'],
+ initiate: async () => {
+ throw new Error('should_not_initiate')
+ },
+ exchange: async () => {
+ throw new Error('should_not_exchange')
+ },
+ complete: async () => {
+ throw new Error('should_not_complete')
+ },
+ resolve: async () => null,
+ verifyBearer: async () => {
+ throw new IdentityProviderUnavailableError('work', 'userinfo_status_503')
+ },
+ }
+ const admission = new AdmissionService({
+ registry: new MapIdentityProviderRegistry([provider]),
+ identities: new MemIdentityStore(),
+ bindings: new MemoryTransportBindingStore(),
+ credentials: new MemCredStore(),
+ redirectUriFor: REDIRECT,
+ })
+ const res = await admission.resolve(
+ { transport: 'http', subjectId: 'jwt-sub', bearer: { token: 'perfectly-valid-token' } },
+ { application: APP, revision: revWith('work') }
+ )
+ expect(res).toEqual({ kind: 'error', reason: 'authoritative_provider_unavailable' })
+ })
+
it('HTTP: a revoked bearer is NOT rescued by the binding a prior valid bearer wrote', async () => {
// The per-request contract: a bearer is re-verified every request, even
// after one has already established a binding. A token that later turns
diff --git a/products/agent_platform/services/agent-shared/src/runtime/admission.ts b/products/agent_platform/services/agent-shared/src/runtime/admission.ts
index 8b7913e30167..ce3ac2c23abf 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/admission.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/admission.ts
@@ -11,7 +11,8 @@
import type { AgentUser, IdentityStore } from '../persistence/identity-store'
import type { AgentApplication, AgentRevision } from '../spec/spec'
import type { IdentityCredentialStore } from './identity-credential-store'
-import type { IdentityProviderRegistry } from './identity-provider'
+import { IdentityProviderUnavailableError } from './identity-provider'
+import type { BearerVerification, IdentityProviderRegistry } from './identity-provider'
import type { AdmissionResult, TransportClaim, VerifiedIdentity } from './transport'
import type { TransportBindingStore } from './transport-binding-store'
@@ -75,8 +76,31 @@ export class AdmissionService {
// bearer goes straight to re-auth and is NOT rescued by step 2's
// binding. (No bearer / no `verifyBearer` → fall to the binding path.)
if (claim.bearer && provider.verifyBearer) {
- const verified = await provider.verifyBearer(claim.bearer.token)
+ let verified: BearerVerification | null
+ try {
+ verified = await provider.verifyBearer(claim.bearer.token)
+ } catch (err) {
+ if (err instanceof IdentityProviderUnavailableError) {
+ // The provider couldn't JUDGE the token (userinfo down /
+ // timed out) — fail closed but retryable. Falling through
+ // to auth_required here would misread an IdP brownout as
+ // mass token revocation.
+ this.deps.log?.('error', 'admission.provider_unavailable', {
+ provider: authoritativeId,
+ detail: err.message,
+ })
+ return { kind: 'error', reason: 'authoritative_provider_unavailable' }
+ }
+ throw err
+ }
if (verified) {
+ // Invariant: a provider that exposes `verifyBearer` is
+ // userinfo-backed and can prove a subject, so minting a
+ // canonical identity from it is safe — regardless of its
+ // `establishesIdentity` flag, which gates link-time secondary-
+ // credential stamping, not bearer proof. A future provider
+ // with a bearer check that does NOT prove a subject must not
+ // define `verifyBearer`.
const canonical = await this.upsertCanonical(applicationId, teamId, authoritativeId, verified.subject)
await this.deps.credentials.put({
teamId,
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts
index 3d3a88af25b2..a46bf97e40e8 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.test.ts
@@ -4,7 +4,7 @@ import type { IdentityProviderConfig } from '../spec/spec'
import type { Credential } from './credential-broker'
import type { HttpFetcher } from './http-client'
import type { IdentityCredentialStore } from './identity-credential-store'
-import { buildIdentityRegistry, createToolIdentity } from './identity-gate'
+import { buildIdentityRegistry, createToolIdentity, jwtPrincipalSubject } from './identity-gate'
import type { IdentityLinkStateStore } from './identity-link-state-store'
import type { IdentityProvider } from './identity-provider'
import { MapIdentityProviderRegistry } from './identity-provider'
@@ -49,6 +49,17 @@ function deps(over: Over = {}): { provider: IdentityProvider; toolIdentity: Retu
return { provider, toolIdentity }
}
+describe('jwtPrincipalSubject', () => {
+ it('is injective — a delimiter-style collision must yield distinct subjects', () => {
+ // ('A:B', 'C') vs ('A', 'B:C') both flatten to 'A:B:C' under naive
+ // `${issuer}:${sub}` concatenation; two configured issuers would then
+ // resolve each other's transport binding and canonical identity.
+ expect(jwtPrincipalSubject({ issuer_secret_ref: 'A:B', sub: 'C' })).not.toBe(
+ jwtPrincipalSubject({ issuer_secret_ref: 'A', sub: 'B:C' })
+ )
+ })
+})
+
describe('buildIdentityRegistry', () => {
const regDeps = (posthogBaseUrl?: string): Parameters<typeof buildIdentityRegistry>[1] => ({
links: {} as IdentityLinkStateStore,
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
index b81be83467db..7754f2e048da 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
@@ -106,6 +106,22 @@ export function buildIdentityRegistry(
* directly; jwt/posthog map through the identity store. Anonymous/service
* principals aren't linkable (return null → resolve() reports unavailable).
*/
+/**
+ * JWT identities are issuer-scoped: an agent can declare several `jwt` auth
+ * modes with different `issuer_secret_ref`s, and each is its own trust domain
+ * — `sub` values can collide across them. An unscoped subject would let a
+ * caller from issuer B resolve issuer A's AgentUser (its transport binding,
+ * canonical identity, and linked credentials). Single shared format so the
+ * admission claim and the per-asker credential lookup land on the SAME row.
+ *
+ * JSON-array encoding because it is injective — both fields accept arbitrary
+ * non-empty strings, so a delimiter would be ambiguous: ('A:B', 'C') and
+ * ('A', 'B:C') must NOT map to the same subject.
+ */
+export function jwtPrincipalSubject(principal: { issuer_secret_ref: string; sub: string }): string {
+ return JSON.stringify([principal.issuer_secret_ref, principal.sub])
+}
+
export async function agentUserIdForPrincipal(
principal: SessionPrincipal | null,
deps: { identities?: IdentityStore; applicationId: string; teamId: number }
@@ -131,9 +147,9 @@ export async function agentUserIdForPrincipal(
// shared across transports; fall back to the raw principal on passthrough.
return principal.canonical_agent_user_id ?? principal.agent_user_id ?? null
case 'jwt':
- return findOrCreate('jwt', principal.sub)
+ return principal.canonical_agent_user_id ?? (await findOrCreate('jwt', jwtPrincipalSubject(principal)))
case 'posthog':
- return findOrCreate('posthog', principal.user_id)
+ return principal.canonical_agent_user_id ?? (await findOrCreate('posthog', principal.user_id))
default:
return null
}
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts
index 06696bd2f51b..f523ff095513 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/identity-provider.ts
@@ -75,6 +75,24 @@ export interface BearerVerification {
scopes: string[]
}
+/**
+ * Thrown by `verifyBearer` when the provider could not JUDGE the token —
+ * userinfo unreachable, timed out, or answering 5xx — as opposed to judging it
+ * invalid (`null`). Admission maps this to a retryable failure instead of
+ * `auth_required`: conflating the two would misread an IdP brownout as mass
+ * token revocation, sending every holder of a valid bearer to re-auth while
+ * hammering the degraded endpoint.
+ */
+export class IdentityProviderUnavailableError extends Error {
+ constructor(
+ readonly provider: string,
+ detail: string
+ ) {
+ super(`identity_provider_unavailable: ${provider}: ${detail}`)
+ this.name = 'IdentityProviderUnavailableError'
+ }
+}
+
export interface IdentityProvider {
readonly id: string
/** Broker key tools/MCPs resolve ('posthog_api', 'github', 'dogs', …). Also
diff --git a/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts
index 245a4a6d6c39..51ba8eb97d1e 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/oauth2-identity-provider.ts
@@ -11,7 +11,9 @@ import type { Credential } from './credential-broker'
import type { HttpFetcher } from './http-client'
import type { IdentityCredentialStore, StoredCredential } from './identity-credential-store'
import type { IdentityLinkStateStore } from './identity-link-state-store'
+import { IdentityProviderUnavailableError } from './identity-provider'
import type {
+ BearerVerification,
IdentityCompleteInput,
IdentityCompleteResult,
IdentityExchangeResult,
@@ -56,14 +58,74 @@ interface TokenResponse {
const b64url = (buf: Buffer): string => buf.toString('base64url')
+/** Bearer verification blocks the chat request — far tighter than the 30s fetch default. */
+const VERIFY_BEARER_TIMEOUT_MS = 5_000
+
export class Oauth2AuthProvider implements IdentityProvider {
// Typed `boolean` (not the literal `false`) so an identity-establishing
// subclass can override it to `true`.
readonly establishesIdentity: boolean = false
+ /**
+ * Per-request bearer verification via userinfo. Assigned in the constructor
+ * (not a prototype method) so it is genuinely `undefined` when the provider
+ * has no `userinfoUrl` — admission treats a present `verifyBearer` as "this
+ * provider can judge bearers", and a present-but-invalid bearer forces
+ * re-auth WITHOUT consulting the durable binding. A stub that always
+ * returned null would therefore lock bound users out.
+ */
+ readonly verifyBearer?: (token: string) => Promise<BearerVerification | null>
+
// `protected` (not `private`) so an identity-establishing subclass
// (PostHogAuthProvider) can reach the config + http to derive a subject.
- constructor(protected readonly deps: Oauth2ProviderDeps) {}
+ constructor(protected readonly deps: Oauth2ProviderDeps) {
+ if (deps.config.userinfoUrl) {
+ const userinfoUrl = deps.config.userinfoUrl
+ this.verifyBearer = async (token: string): Promise<BearerVerification | null> => {
+ // Runs on the chat hot path (every request), so: a tight
+ // timeout instead of the fetcher's 30s default, and only the
+ // provider's actual judgement on the token (401/403) reads as
+ // "invalid". Transport failures, timeouts, and server errors
+ // say nothing about the token — surface them as
+ // `IdentityProviderUnavailableError` so admission fails closed
+ // but RETRYABLE instead of demanding re-auth.
+ let res: Response
+ try {
+ res = await this.deps.http.fetch(userinfoUrl, {
+ method: 'GET',
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
+ signal: AbortSignal.timeout(VERIFY_BEARER_TIMEOUT_MS),
+ })
+ } catch (err) {
+ throw new IdentityProviderUnavailableError(
+ this.id,
+ err instanceof Error ? err.message : 'userinfo_fetch_failed'
+ )
+ }
+ if (res.status === 401 || res.status === 403) {
+ return null
+ }
+ if (!res.ok) {
+ throw new IdentityProviderUnavailableError(this.id, `userinfo_status_${res.status}`)
+ }
+ let json: { sub?: string }
+ try {
+ json = (await res.json()) as { sub?: string }
+ } catch {
+ throw new IdentityProviderUnavailableError(this.id, 'userinfo_malformed_body')
+ }
+ const subject = typeof json.sub === 'string' && json.sub.length > 0 ? json.sub : undefined
+ if (!subject) {
+ // 200 but no provable subject — the provider can't establish
+ // who this is, which for admission is the same as invalid.
+ return null
+ }
+ // The bearer is the credential — no refresh token and no known
+ // expiry; admission re-verifies it on every request anyway.
+ return { subject, stored: { access_token: token }, scopes: [] }
+ }
+ }
+ }
get id(): string {
return this.deps.config.id
diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts
index f9b411e0bbe6..44f0f23d6430 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.test.ts
@@ -295,3 +295,79 @@ describe('PostHogAuthProvider', () => {
expect(await credentials.get('au-1', 'byo')).not.toBeNull()
})
})
+
+// Userinfo that only accepts the tokens it was told about — lets the
+// verifyBearer tests distinguish a valid per-request bearer from a bogus one.
+function bearerAwareUserinfo(validTokens: Record<string, string>): HttpFetcher {
+ return {
+ async fetch(input, init) {
+ const url = String(input)
+ if (!url.endsWith('/oauth/userinfo/')) {
+ return new Response('not found', { status: 404 })
+ }
+ const auth = ((init?.headers ?? {}) as Record<string, string>)['Authorization'] ?? ''
+ const sub = validTokens[auth.replace('Bearer ', '')]
+ if (!sub) {
+ return new Response(JSON.stringify({ error: 'invalid_token' }), { status: 401 })
+ }
+ return new Response(JSON.stringify({ sub }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ },
+ }
+}
+
+describe('verifyBearer (per-request identity proof)', () => {
+ const stores = (): { links: MemLinkStore; credentials: MemCredStore } => ({
+ links: new MemLinkStore(),
+ credentials: new MemCredStore(),
+ })
+
+ it('a bearer that userinfo accepts verifies to its subject, carrying the bearer as the credential', async () => {
+ const provider = posthogProvider(bearerAwareUserinfo({ 'live-token': 'phuser-42' }), stores())
+ const verified = await provider.verifyBearer!('live-token')
+ expect(verified).toEqual({ subject: 'phuser-42', stored: { access_token: 'live-token' }, scopes: [] })
+ })
+
+ it('a bearer that userinfo rejects verifies to null (admission then re-auths, never admits)', async () => {
+ const provider = posthogProvider(bearerAwareUserinfo({ 'live-token': 'phuser-42' }), stores())
+ expect(await provider.verifyBearer!('revoked-token')).toBeNull()
+ })
+
+ // Only the provider's judgement on the token (401/403) may read as invalid.
+ // Anything that prevented a judgement must throw — a brownout swallowed
+ // into null would demand re-auth from every holder of a valid bearer.
+ it.each<[string, HttpFetcher]>([
+ ['userinfo answers 5xx', { fetch: async () => new Response('oops', { status: 503 }) }],
+ [
+ 'userinfo is unreachable',
+ {
+ fetch: async () => {
+ throw new Error('ECONNREFUSED')
+ },
+ },
+ ],
+ ])('%s → verifyBearer throws unavailable, never reads as an invalid token', async (_label, http) => {
+ const provider = posthogProvider(http, stores())
+ await expect(provider.verifyBearer!('live-token')).rejects.toMatchObject({
+ name: 'IdentityProviderUnavailableError',
+ })
+ })
+
+ it('is absent without a userinfo endpoint — a defined stub would force re-auth over the durable binding', async () => {
+ const { links, credentials } = stores()
+ const provider = new Oauth2AuthProvider({
+ config: {
+ id: 'byo',
+ authorizeUrl: `${BASE}/oauth/authorize/`,
+ tokenUrl: `${BASE}/oauth/token/`,
+ clientId: 'byo-client',
+ },
+ links,
+ credentials,
+ http: bearerAwareUserinfo({}),
+ })
+ expect(provider.verifyBearer).toBeUndefined()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
index b07db0fbd323..81ce68062aa8 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
@@ -952,6 +952,54 @@ describe('AgentSpecSchema', () => {
})
})
+ // The canonical-rebind guard is branch-tested above via slack; these rows
+ // prove it is WIRED for the HTTP principals chat admission stamps — without
+ // them, dropping the check from the posthog/jwt cases would pass silently.
+ describe('principalsMatch — canonical guard on HTTP principals (chat admission)', () => {
+ type P = { kind: 'posthog'; user_id: string; team_id: number; canonical_agent_user_id?: string }
+ type J = {
+ kind: 'jwt'
+ issuer_secret_ref: string
+ sub: string
+ claims: Record<string, unknown>
+ canonical_agent_user_id?: string
+ }
+ it.each<[string, P | J, P | J, boolean]>([
+ [
+ 'posthog: same user + same canonical matches',
+ { kind: 'posthog', user_id: 'u1', team_id: 1, canonical_agent_user_id: 'C1' },
+ { kind: 'posthog', user_id: 'u1', team_id: 1, canonical_agent_user_id: 'C1' },
+ true,
+ ],
+ [
+ 'posthog: same user but rebound canonical does NOT match',
+ { kind: 'posthog', user_id: 'u1', team_id: 1, canonical_agent_user_id: 'C1' },
+ { kind: 'posthog', user_id: 'u1', team_id: 1, canonical_agent_user_id: 'C2' },
+ false,
+ ],
+ [
+ 'jwt: same sub + same canonical matches',
+ { kind: 'jwt', issuer_secret_ref: 'S', sub: 'a', claims: {}, canonical_agent_user_id: 'C1' },
+ { kind: 'jwt', issuer_secret_ref: 'S', sub: 'a', claims: {}, canonical_agent_user_id: 'C1' },
+ true,
+ ],
+ [
+ 'jwt: same sub but rebound canonical does NOT match',
+ { kind: 'jwt', issuer_secret_ref: 'S', sub: 'a', claims: {}, canonical_agent_user_id: 'C1' },
+ { kind: 'jwt', issuer_secret_ref: 'S', sub: 'a', claims: {}, canonical_agent_user_id: 'C2' },
+ false,
+ ],
+ [
+ 'jwt: same sub under a DIFFERENT issuer does NOT match (issuer-scoped trust domains)',
+ { kind: 'jwt', issuer_secret_ref: 'S', sub: 'a', claims: {} },
+ { kind: 'jwt', issuer_secret_ref: 'S2', sub: 'a', claims: {} },
+ false,
+ ],
+ ])('%s', (_label, stored, incoming, expected) => {
+ expect(principalsMatch(stored, incoming)).toBe(expected)
+ })
+ })
+
describe('principalsMatch — shared_secret', () => {
type SS = { kind: 'shared_secret'; team_id: number }
it.each<[string, SS, SS, boolean]>([
@@ -1071,3 +1119,42 @@ describe('models.optimize_for', () => {
).toThrow()
})
})
+
+describe('authoritative_provider trigger gating (fail-closed)', () => {
+ const DOGS_PROVIDER = {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: 'https://idp.test/authorize',
+ token_url: 'https://idp.test/token',
+ userinfo_url: 'https://idp.test/userinfo',
+ client_id: 'c',
+ }
+ const AUTH = { modes: [{ type: 'jwt', issuer_secret_ref: 'S' }] }
+
+ it('accepts admission-wired triggers (slack + chat) alongside an authoritative provider', () => {
+ const spec = AgentSpecSchema.parse({
+ model: 'x',
+ triggers: [
+ { type: 'slack', config: { trusted_workspaces: '*' } },
+ { type: 'chat', config: {}, auth: AUTH },
+ ],
+ identity_providers: [DOGS_PROVIDER],
+ authoritative_provider: 'dogs',
+ })
+ expect(spec.authoritative_provider).toBe('dogs')
+ })
+
+ it.each([
+ ['webhook', { type: 'webhook', config: { path: '/webhook' }, auth: AUTH }],
+ ['mcp', { type: 'mcp', config: {}, auth: AUTH }],
+ ])('refuses an authoritative provider combined with the un-wired %s trigger', (_type, trigger) => {
+ expect(() =>
+ AgentSpecSchema.parse({
+ model: 'x',
+ triggers: [trigger],
+ identity_providers: [DOGS_PROVIDER],
+ authoritative_provider: 'dogs',
+ })
+ ).toThrow(/not yet enforced/)
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index 78a87b7dfdde..74ac49efa311 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -1080,7 +1080,7 @@ export const AgentSpecObjectSchema = z.object({
* otherwise a spec with `authoritative_provider` set would silently admit the
* transport claim as the identity, defeating the gate.
*/
-const ADMISSION_WIRED_TRIGGER_TYPES: readonly Trigger['type'][] = ['slack']
+const ADMISSION_WIRED_TRIGGER_TYPES: readonly Trigger['type'][] = ['slack', 'chat']
export const AgentSpecSchema = AgentSpecObjectSchema.superRefine((spec, ctx) => {
// authoritative_provider must reference an identity_providers[] entry that can
@@ -1205,6 +1205,24 @@ export function secretHostMatches(pattern: string, host: string): boolean {
return p === h
}
+/**
+ * If either side went through authoritative admission, both must resolve to
+ * the SAME canonical identity. A rebound canonical (unlink + re-link as a
+ * different subject; or an admission trust model that flipped on/off between
+ * the stored session and this request) is a new principal, not a resume of
+ * the old thread — otherwise the new identity would drive a session that
+ * still references the previous identity's stored credentials.
+ */
+function canonicalIdentityMatches(
+ stored: { canonical_agent_user_id?: string },
+ incoming: { canonical_agent_user_id?: string }
+): boolean {
+ if (stored.canonical_agent_user_id || incoming.canonical_agent_user_id) {
+ return stored.canonical_agent_user_id === incoming.canonical_agent_user_id
+ }
+ return true
+}
+
/**
* Strict principal match: same kind + same identifying key. Used at the
* trigger edge (`/send`, Slack-thread resumes) to keep one user's session
@@ -1227,13 +1245,26 @@ export function principalsMatch(stored: SessionPrincipal | null, incoming: Sessi
case 'anonymous':
return true
case 'posthog':
- return (
- incoming.kind === 'posthog' &&
- stored.user_id === incoming.user_id &&
- stored.team_id === incoming.team_id
- )
+ if (
+ incoming.kind !== 'posthog' ||
+ stored.user_id !== incoming.user_id ||
+ stored.team_id !== incoming.team_id
+ ) {
+ return false
+ }
+ return canonicalIdentityMatches(stored, incoming)
case 'jwt':
- return incoming.kind === 'jwt' && stored.sub === incoming.sub
+ if (
+ incoming.kind !== 'jwt' ||
+ stored.sub !== incoming.sub ||
+ // Issuer-scoped: `sub` is only meaningful within one issuer's
+ // trust domain — the same sub under a different configured
+ // jwt mode is a different caller, not a resume.
+ stored.issuer_secret_ref !== incoming.issuer_secret_ref
+ ) {
+ return false
+ }
+ return canonicalIdentityMatches(stored, incoming)
case 'slack':
if (
incoming.kind !== 'slack' ||
@@ -1242,17 +1273,7 @@ export function principalsMatch(stored: SessionPrincipal | null, incoming: Sessi
) {
return false
}
- // If either side went through authoritative admission, both must
- // resolve to the SAME canonical identity. A rebound canonical
- // (unlink + re-link as a different subject; or an admission trust
- // model that flipped on/off between the stored session and this
- // request) is a new principal, not a resume of the old thread —
- // otherwise the new identity would drive a session that still
- // references the previous identity's stored credentials.
- if (stored.canonical_agent_user_id || incoming.canonical_agent_user_id) {
- return stored.canonical_agent_user_id === incoming.canonical_agent_user_id
- }
- return true
+ return canonicalIdentityMatches(stored, incoming)
case 'posthog_internal':
return incoming.kind === 'posthog_internal' && stored.team_id === incoming.team_id
case 'shared_secret':
@@ -1337,6 +1358,9 @@ export type SessionPrincipal =
team_id: number
email?: string
scopes?: string[]
+ /** Canonical identity (authoritative provider) set by edge admission;
+ * keys secondary links when present. Absent on passthrough. */
+ canonical_agent_user_id?: string
}
/** JWT signed with the agent's configured secret. `sub` + `claims`
* are author-defined; the platform treats them as opaque. */
@@ -1345,6 +1369,9 @@ export type SessionPrincipal =
issuer_secret_ref: string
sub: string
claims: Record<string, unknown>
+ /** Canonical identity (authoritative provider) set by edge admission;
+ * keys secondary links when present. Absent on passthrough. */
+ canonical_agent_user_id?: string
}
/**
* Slack user resolved through the slack integration. Pure Slack
diff --git a/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts b/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
index e7c2d54d5237..372073f0c0b5 100644
--- a/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
@@ -10,12 +10,25 @@
*
* Plus a passthrough agent (no authoritative_provider) that runs immediately,
* proving backward-compatibility through the same path.
+ *
+ * The second describe proves the same gate is transport-agnostic: the chat/HTTP
+ * path returns the auth block as `401 { auth_required }` (jwt principals link
+ * like Slack ones do), and a per-request PostHog bearer satisfies a
+ * `kind: posthog` authoritative provider with no link round-trip at all.
*/
+import { createHmac } from 'node:crypto'
import request from 'supertest'
import { afterEach, beforeAll, describe, expect, it } from 'vitest'
-import { canonicalKind, HttpClient, PgTransportBindingStore } from '@posthog/agent-shared'
+import {
+ type AuthProvider,
+ jwtVerifier,
+ type PosthogIdentityIntrospector,
+ posthogVerifier,
+ type TeamOrgLookup,
+} from '@posthog/agent-ingress'
+import { canonicalKind, HttpClient, jwtPrincipalSubject, PgTransportBindingStore } from '@posthog/agent-shared'
import { buildCluster, Cluster, fauxText } from '../harness'
import { DogServer, startDogServer } from '../harness/dog-oauth-server'
@@ -90,6 +103,17 @@ function assistantText(conversation: unknown[]): string {
const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe
+// Drive the real OAuth callback on the ingress route: browser hits the IdP
+// /authorize (302 → our callback), then GET /link/dogs/callback?state&code.
+async function completeLink(c: Cluster, authorizeUrl: string): Promise<void> {
+ const res = await fetch(authorizeUrl, { redirect: 'manual' })
+ const loc = new URL(res.headers.get('location') ?? '')
+ await request(c.ingress)
+ .get(loc.pathname)
+ .query({ state: loc.searchParams.get('state') ?? '', code: loc.searchParams.get('code') ?? '' })
+ .expect(200)
+}
+
maybeDescribe('edge admission e2e (Slack, authoritative provider, mocked inference)', () => {
let ok = false
let dog: DogServer
@@ -104,17 +128,6 @@ maybeDescribe('edge admission e2e (Slack, authoritative provider, mocked inferen
await dog?.close().catch(() => undefined)
})
- // Drive the real OAuth callback on the ingress route: browser hits the IdP
- // /authorize (302 → our callback), then GET /link/dogs/callback?state&code.
- const completeLink = async (authorizeUrl: string): Promise<void> => {
- const res = await fetch(authorizeUrl, { redirect: 'manual' })
- const loc = new URL(res.headers.get('location') ?? '')
- await request(c.ingress)
- .get(loc.pathname)
- .query({ state: loc.searchParams.get('state') ?? '', code: loc.searchParams.get('code') ?? '' })
- .expect(200)
- }
-
it('Slack: unbound → auth_required (no run) → link → admitted → agent runs', async () => {
if (!ok) {
return
@@ -161,7 +174,7 @@ maybeDescribe('edge admission e2e (Slack, authoritative provider, mocked inferen
await c.drain() // nothing queued; a no-op
// Complete the link → admission writes the binding + canonical identity.
- await completeLink(authorizeUrl)
+ await completeLink(c, authorizeUrl)
const bindings = new PgTransportBindingStore(c.pool)
// Turn 2: same user → admitted → the agent actually runs and replies.
@@ -216,3 +229,299 @@ maybeDescribe('edge admission e2e (Slack, authoritative provider, mocked inferen
expect(assistantText(s!.conversation)).toContain('hello right away')
})
})
+
+const JWT_SECRET_REF = 'EMBED_SECRET'
+const JWT_SECRET_VALUE = 'chat-admission-jwt-secret'
+
+function makeJwt(sub: string): string {
+ const b64 = (v: object): string =>
+ Buffer.from(JSON.stringify(v)).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_')
+ const header = b64({ alg: 'HS256', typ: 'JWT' })
+ const payload = b64({ sub })
+ const sig = createHmac('sha256', JWT_SECRET_VALUE)
+ .update(`${header}.${payload}`)
+ .digest('base64')
+ .replace(/=+$/, '')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ return `${header}.${payload}.${sig}`
+}
+
+const jwtAuthProvider: AuthProvider = {
+ verifiers: [
+ jwtVerifier({
+ async resolve(ref) {
+ return ref === JWT_SECRET_REF ? JWT_SECRET_VALUE : null
+ },
+ }),
+ ],
+}
+
+// `project`-audience agents never consult the org lookup.
+const teamOrg: TeamOrgLookup = {
+ async orgForTeam() {
+ return null
+ },
+}
+
+const PH_SUB = 'ph-user-uuid-1'
+const PH_BEARER = 'phx_live_bearer'
+
+const posthogIntrospector: PosthogIdentityIntrospector = {
+ async introspect(bearer) {
+ return bearer === PH_BEARER ? { uuid: PH_SUB, email: '[email protected]', team: { id: 1 } } : null
+ },
+ async canAccessTeam(bearer) {
+ return bearer === PH_BEARER
+ },
+}
+
+// Real HTTP everywhere (the dogs IdP is a real local server), except PostHog's
+// /oauth/userinfo/ — there is no Django in the harness, so the authoritative
+// posthog provider's `verifyBearer` introspection is scripted by token.
+function posthogUserinfoHttp(validBearers: Record<string, string>): { fetch: HttpClient['fetch'] } {
+ const real = new HttpClient()
+ return {
+ fetch: (input, init) => {
+ const url = typeof input === 'string' ? input : input.toString()
+ if (url.includes('/oauth/userinfo')) {
+ const auth = ((init?.headers ?? {}) as Record<string, string>)['Authorization'] ?? ''
+ const sub = validBearers[auth.replace('Bearer ', '')]
+ if (!sub) {
+ return Promise.resolve(new Response(JSON.stringify({ error: 'invalid_token' }), { status: 401 }))
+ }
+ return Promise.resolve(
+ new Response(JSON.stringify({ sub }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )
+ }
+ return real.fetch(input, init)
+ },
+ }
+}
+
+maybeDescribe('edge admission e2e (chat/HTTP, authoritative provider, mocked inference)', () => {
+ let ok = false
+ let dog: DogServer
+ let c: Cluster
+
+ beforeAll(async () => {
+ ok = await reachable()
+ })
+
+ afterEach(async () => {
+ await c?.teardown().catch(() => undefined)
+ await dog?.close().catch(() => undefined)
+ })
+
+ it('chat (jwt): /run → 401 auth_required (no session) → link → admitted → runs; unlink re-gates /send', async () => {
+ if (!ok) {
+ return
+ }
+ dog = await startDogServer({ userSub: 'alice-canonical' })
+ c = await buildCluster({ http: new HttpClient(), authProvider: jwtAuthProvider })
+ await c.deployAgent({
+ slug: 'gatedchat',
+ spec: {
+ triggers: [{ type: 'chat', config: {} }],
+ auth: { modes: [{ type: 'jwt', issuer_secret_ref: JWT_SECRET_REF }] },
+ authoritative_provider: 'dogs',
+ identity_providers: [
+ {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: dog.authorizeUrl,
+ token_url: dog.tokenUrl,
+ userinfo_url: dog.userinfoUrl,
+ client_id: 'dogs-client',
+ scopes: ['read:dog'],
+ },
+ ],
+ },
+ })
+ const bearer = makeJwt('alice')
+
+ // Turn 1: unbound → the auth block comes back IN the response (401),
+ // and nothing is enqueued.
+ c.setScript([fauxText('should not run yet')])
+ const first = await request(c.ingress)
+ .post('/agents/gatedchat/run')
+ .set('Authorization', `Bearer ${bearer}`)
+ .send({ message: 'hi' })
+ expect(first.status).toBe(401)
+ expect(first.body).toMatchObject({ error: 'auth_required', auth_required: true, provider: 'dogs' })
+ expect(first.body.session_id).toBeUndefined()
+ expect(first.body.authorize_url).toContain(dog.baseUrl)
+ await c.drain() // nothing queued; a no-op
+
+ await completeLink(c, first.body.authorize_url as string)
+
+ // Turn 2: same JWT sub → admitted → the agent runs; the response
+ // principal carries the canonical identity admission resolved.
+ c.setScript([fauxText('woof, admitted')])
+ const second = await request(c.ingress)
+ .post('/agents/gatedchat/run')
+ .set('Authorization', `Bearer ${bearer}`)
+ .send({ message: 'still there?' })
+ expect(second.status).toBe(200)
+ await c.drain()
+ const session = await c.queue.get(second.body.session_id)
+ expect(assistantText(session!.conversation)).toContain('woof, admitted')
+
+ const cano = await c.identities.find({
+ application_id: session!.application_id,
+ principal_kind: canonicalKind('dogs'),
+ principal_id: 'alice-canonical',
+ })
+ expect(cano).toBeTruthy()
+ expect(second.body.principal.canonical_agent_user_id).toBe(cano!.id)
+
+ // The ACL routes admit too: the stored principal carries the canonical
+ // id, so /cancel with a raw (un-stamped) principal would 403 the owner.
+ const cancel = await request(c.ingress)
+ .post('/agents/gatedchat/cancel')
+ .set('Authorization', `Bearer ${bearer}`)
+ .send({ session_id: second.body.session_id })
+ expect(cancel.status).toBe(200)
+ expect(cancel.body.ok).toBe(true)
+
+ // Unlink → the binding is gone, so even the EXISTING session stops
+ // advancing: /send re-runs admission per message, like the Slack path.
+ const transportUser = await c.identities.find({
+ application_id: session!.application_id,
+ principal_kind: 'jwt',
+ // Issuer-scoped subject — same helper the ingress keys the row with.
+ principal_id: jwtPrincipalSubject({ issuer_secret_ref: JWT_SECRET_REF, sub: 'alice' }),
+ })
+ await new PgTransportBindingStore(c.pool).unbind(session!.application_id, transportUser!.id)
+ const send = await request(c.ingress)
+ .post('/agents/gatedchat/send')
+ .set('Authorization', `Bearer ${bearer}`)
+ .send({ session_id: second.body.session_id, message: 'one more thing' })
+ expect(send.status).toBe(401)
+ expect(send.body.auth_required).toBe(true)
+ })
+
+ it('chat (posthog): a per-request posthog bearer satisfies a posthog authoritative provider — no link round-trip', async () => {
+ if (!ok) {
+ return
+ }
+ c = await buildCluster({
+ http: posthogUserinfoHttp({ [PH_BEARER]: PH_SUB }),
+ authProvider: { verifiers: [posthogVerifier(posthogIntrospector, teamOrg)] },
+ })
+ await c.deployAgent({
+ slug: 'phgated',
+ spec: {
+ triggers: [{ type: 'chat', config: {} }],
+ auth: { modes: [{ type: 'posthog' }] },
+ authoritative_provider: 'posthog',
+ // client_id is normally backend-injected on promote.
+ identity_providers: [{ kind: 'posthog', id: 'posthog', client_id: 'provisioned-client' }],
+ },
+ })
+
+ c.setScript([fauxText('hello, verified user')])
+ const res = await request(c.ingress)
+ .post('/agents/phgated/run')
+ .set('Authorization', `Bearer ${PH_BEARER}`)
+ .send({ message: 'hi' })
+ expect(res.status).toBe(200)
+ expect(res.body.auth_required).toBeUndefined()
+ await c.drain()
+ const session = await c.queue.get(res.body.session_id)
+ expect(assistantText(session!.conversation)).toContain('hello, verified user')
+
+ // The bearer proved the subject inline: canonical identity + binding
+ // exist without any OAuth link having run.
+ const cano = await c.identities.find({
+ application_id: session!.application_id,
+ principal_kind: canonicalKind('posthog'),
+ principal_id: PH_SUB,
+ })
+ expect(cano).toBeTruthy()
+ expect(res.body.principal.canonical_agent_user_id).toBe(cano!.id)
+ const bindings = await new PgTransportBindingStore(c.pool).listForCanonical(session!.application_id, cano!.id)
+ expect(bindings).toHaveLength(1)
+ })
+
+ it('chat (posthog): a userinfo brownout answers 503 retryable — never auth_required, nothing enqueued', async () => {
+ if (!ok) {
+ return
+ }
+ // Edge auth (the in-memory introspector) accepts the bearer; only the
+ // admission-side userinfo call browns out. Reverting the availability
+ // discrimination flips this case to 401 auth_required — a fake mass
+ // re-auth for a perfectly valid token.
+ const real = new HttpClient()
+ const brownoutHttp: { fetch: HttpClient['fetch'] } = {
+ fetch: (input, init) => {
+ const url = typeof input === 'string' ? input : input.toString()
+ if (url.includes('/oauth/userinfo')) {
+ return Promise.resolve(new Response('upstream sad', { status: 503 }))
+ }
+ return real.fetch(input, init)
+ },
+ }
+ c = await buildCluster({
+ http: brownoutHttp,
+ authProvider: { verifiers: [posthogVerifier(posthogIntrospector, teamOrg)] },
+ })
+ await c.deployAgent({
+ slug: 'phbrownout',
+ spec: {
+ triggers: [{ type: 'chat', config: {} }],
+ auth: { modes: [{ type: 'posthog' }] },
+ authoritative_provider: 'posthog',
+ identity_providers: [{ kind: 'posthog', id: 'posthog', client_id: 'provisioned-client' }],
+ },
+ })
+ c.setScript([fauxText('must not run')])
+ const res = await request(c.ingress)
+ .post('/agents/phbrownout/run')
+ .set('Authorization', `Bearer ${PH_BEARER}`)
+ .send({ message: 'hi' })
+ expect(res.status).toBe(503)
+ expect(res.body.reason).toBe('authoritative_provider_unavailable')
+ expect(res.body.auth_required).toBeUndefined()
+ expect(res.body.session_id).toBeUndefined()
+ })
+
+ it('chat (anonymous): a claim-less principal is refused outright — a public auth mode cannot void the gate', async () => {
+ if (!ok) {
+ return
+ }
+ // Harness default auth provider serves the `public` mode, so an
+ // unauthenticated /run authenticates as `anonymous` — the exact
+ // combination that would bypass admission if the gate failed open.
+ c = await buildCluster()
+ await c.deployAgent({
+ slug: 'gatedpublic',
+ spec: {
+ triggers: [{ type: 'chat', config: {} }],
+ auth: { modes: [{ type: 'public', acknowledge_public_exposure: true }] },
+ authoritative_provider: 'dogs',
+ // No IdP round-trip happens — the refusal is pre-claim — so
+ // dummy endpoints are enough to satisfy the spec schema.
+ identity_providers: [
+ {
+ kind: 'oauth2',
+ id: 'dogs',
+ authorize_url: 'https://idp.test/authorize',
+ token_url: 'https://idp.test/token',
+ userinfo_url: 'https://idp.test/userinfo',
+ client_id: 'dogs-client',
+ },
+ ],
+ },
+ })
+ c.setScript([fauxText('must never run')])
+ const res = await request(c.ingress).post('/agents/gatedpublic/run').send({ message: 'hi' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('admission_unsupported_principal')
+ expect(res.body.session_id).toBeUndefined()
+ await c.drain() // nothing queued; a no-op
+ })
+})