: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(agent-platform): authoritative-provider identity admission (transport-decoupled) (#66050)
Ben White85c0717ad973
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 979809573e73..15096ac5f95f 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -68,6 +68,7 @@ rules:|AgentSession|AgentSessionCredential|AgentToolApprovalRequest+ |AgentTransportBinding|AgentUser|Alert|AlertConfiguration@@ -364,6 +365,7 @@ rules:|AgentSession|AgentSessionCredential|AgentToolApprovalRequest+ |AgentTransportBinding|AgentUser|Alert|AlertConfigurationdiff --git a/products/agent_platform/backend/migrations/0013_agent_transport_binding.py b/products/agent_platform/backend/migrations/0013_agent_transport_binding.pynew file mode 100644index 000000000000..c9cd019b293a--- /dev/null+++ b/products/agent_platform/backend/migrations/0013_agent_transport_binding.py@@ -0,0 +1,60 @@+# Durable transport→canonical-identity binding. Records that a transport+# principal (Slack/Discord/HTTP agent_user) authenticated, via the agent's+# authoritative provider, AS a canonical identity (another agent_user keyed+# identity:<provider>/subject). Resolved at admission so a session only runs+# once a verified identity exists. See docs/identity-and-tools.md.++import django.db.models.manager+import django.db.models.functions.datetime+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("agent_platform", "0012_agentsession_search_text_turn_count"),+ ]++ operations = [+ migrations.CreateModel(+ name="AgentTransportBinding",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("team_id", models.BigIntegerField(db_index=True)),+ ("application_id", models.UUIDField()),+ ("transport_agent_user_id", models.UUIDField()),+ ("canonical_agent_user_id", models.UUIDField()),+ ("provider", models.TextField()),+ (+ "created_at",+ models.DateTimeField(auto_now_add=True, db_default=django.db.models.functions.datetime.Now()),+ ),+ ],+ options={+ "db_table": "agent_transport_binding",+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ migrations.AddConstraint(+ model_name="agenttransportbinding",+ constraint=models.UniqueConstraint(+ fields=("application_id", "transport_agent_user_id"),+ name="agent_transport_binding_unique_transport",+ ),+ ),+ migrations.AddIndex(+ model_name="agenttransportbinding",+ index=models.Index(fields=["application_id", "canonical_agent_user_id"], name="atb_canonical_idx"),+ ),+ ]diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txtindex c48d57f0cd82..eef3fb5cf8ba 100644--- a/products/agent_platform/backend/migrations/max_migration.txt+++ b/products/agent_platform/backend/migrations/max_migration.txt@@ -1 +1 @@-0012_agentsession_search_text_turn_count+0013_agent_transport_bindingdiff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.pyindex 8b0bec8f6d42..8f288f865e4c 100644--- a/products/agent_platform/backend/models.py+++ b/products/agent_platform/backend/models.py@@ -410,3 +410,36 @@ class AgentIdentityLinkState(ProductTeamModel, UUIDModel):indexes = [models.Index(fields=["expires_at"], name="ails_expires_idx"),]+++class AgentTransportBinding(ProductTeamModel, UUIDModel):+ """Durable transport→canonical-identity binding.++ Records that a transport principal (a Slack/Discord/HTTP agent_user) was+ authenticated, via the agent's authoritative provider, AS a canonical+ identity (another agent_user keyed `identity:<provider>` / subject). The+ ingress resolves this at admission so a session only runs once a verified+ identity exists. One canonical identity may have many bindings (the same+ person across transports); unlink = delete a binding.+ """++ application_id = models.UUIDField()+ # The transport principal (agent_user.id, principal_kind = transport).+ transport_agent_user_id = models.UUIDField()+ # The canonical identity (agent_user.id, principal_kind = identity:<provider>).+ canonical_agent_user_id = models.UUIDField()+ # Authoritative provider that established the binding.+ provider = models.TextField()+ created_at = models.DateTimeField(auto_now_add=True, db_default=Now())++ class Meta:+ db_table = "agent_transport_binding"+ constraints = [+ models.UniqueConstraint(+ fields=["application_id", "transport_agent_user_id"],+ name="agent_transport_binding_unique_transport",+ ),+ ]+ indexes = [+ models.Index(fields=["application_id", "canonical_agent_user_id"], name="atb_canonical_idx"),+ ]diff --git a/products/agent_platform/docs/identity-and-tools.md b/products/agent_platform/docs/identity-and-tools.mdindex a057ccd6f65f..9ee6eb91f562 100644--- a/products/agent_platform/docs/identity-and-tools.md+++ b/products/agent_platform/docs/identity-and-tools.md@@ -51,8 +51,10 @@ slack · posthog_internal · shared_secret · service`) defined in`principalsMatch(stored, incoming)` decides whether an inbound request mayresume/append to an existing session: Slack matches on `(workspace_id,-slack_user_id)`, JWT on `sub`, posthog on `(user_id, team_id)`, shared_secret-on `team_id`.+slack_user_id)`, JWT on `sub`, posthog on `(user_id, team_id)`, `shared_secret`+on `team_id`. When either side carries a `canonical_agent_user_id` (set by edge+admission, below), both must additionally resolve to the same canonical+identity — a rebound identity is a new principal, not a resume.## From request to a running session@@ -81,6 +83,50 @@ durable identity behind it (keyed by `application_id · principal_kind ·principal_id`); the **CredentialBroker** holds the short-lived edge credential(e.g. the PostHog bearer the caller presented) keyed by `session_id`.+## Authoritative identity & edge admission++The five auth modes prove _the transport_ is authentic (a valid Slack+signature, a well-formed JWT); on their own they don't prove _which human_ the+agent should trust across transports. An agent can opt into a stronger model by+declaring **one** `spec.authoritative_provider` — an `identity_providers[]`+entry that can prove a subject (`posthog`, or `oauth2` with a `userinfo_url`).+When set, the **ingress edge** must resolve a verified **canonical identity**+from that provider _before_ a session is enqueued+([AdmissionService.resolve](../services/agent-shared/src/runtime/admission.ts)).++Two `agent_user` flavours plus one binding table carry this:++| Row | `principal_kind` | `principal_id` | Meaning |+| ------------------------- | ------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------- |+| transport principal | the transport (`slack`, `http`) | per-transport sender id (`T01:U01`) | who sent _this_ message, per that transport |+| canonical identity | `identity:<provider>` | the provider's proven `subject` | the source-of-truth human |+| `agent_transport_binding` | — | — | durable transport-principal → canonical map, provider-scoped; unique per `(application, transport principal)` |++Resolution order (fail-closed — never enqueue on doubt):++1. **No authoritative provider** → `passthrough`: the transport claim _is_ the+ identity (today's default / public agents).+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).+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+ the canonical identity, stores the authoritative credential under it, and+ writes the binding.++One canonical identity can own many bindings — auth once via Slack and every+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.+## Linked identitiesA principal (say a Slack user) can act as themselves on external systems once@@ -92,7 +138,10 @@ Providers are declared in `spec.identity_providers[]` (`kind: posthog` or`oauth2`, `binding: principal` (per-asker, default) or `agent`). Identity-establishing providers (e.g. PostHog OAuth) record a `subject` — the provenexternal identity — which is how a Slack user gets bridged to "their PostHog-person".+person". When one such provider is the agent's `authoritative_provider`, its+subject becomes the canonical identity (above) and every _other_ provider's+credential keys off that canonical `agent_user` rather than the transport+principal.```mermaidsequenceDiagramdiff --git a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.tsnew file mode 100644index 000000000000..367745a8e989--- /dev/null+++ b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts@@ -0,0 +1,61 @@+/**+ * Edge admission wiring. Builds an `AdmissionService` for a revision from the+ * ingress's identity stores + the revision's declared providers/env. Returns+ * 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+ * `/link/:provider/callback` route (complete).+ */++import {+ AdmissionService,+ buildIdentityRegistry,+ type AgentRevision,+ type EncryptedFields,+ type HttpFetcher,+ type IdentityCredentialStore,+ type IdentityLinkStateStore,+ type IdentityStore,+ type TransportBindingStore,+} from '@posthog/agent-shared'++export interface AdmissionDepsBundle {+ identities: IdentityStore+ identityLinks: IdentityLinkStateStore+ identityCredentials: IdentityCredentialStore+ transportBindings: TransportBindingStore+ envEncryption: EncryptedFields+ http: HttpFetcher+ posthogApiBaseUrl?: string+ publicBaseUrl?: string+}++/** The ingress's own OAuth callback URL for a provider. */+export function admissionRedirectUri(publicBaseUrl: string | undefined, providerId: string): string {+ const base = (publicBaseUrl ?? 'https://agents.posthog.com').replace(/\/+$/, '')+ return `${base}/link/${providerId}/callback`+}++/** Build an `AdmissionService` for a revision, or null when the agent declares+ * no authoritative provider (passthrough). */+export function buildAdmission(deps: AdmissionDepsBundle, revision: AgentRevision): AdmissionService | null {+ if (!revision.spec.authoritative_provider) {+ return null+ }+ const env = deps.envEncryption.decryptJsonEnv(revision.encrypted_env)+ const registry = buildIdentityRegistry(revision.spec.identity_providers, {+ links: deps.identityLinks,+ credentials: deps.identityCredentials,+ http: deps.http,+ secret: (name) => env[name],+ posthogBaseUrl: deps.posthogApiBaseUrl,+ })+ return new AdmissionService({+ registry,+ identities: deps.identities,+ bindings: deps.transportBindings,+ credentials: deps.identityCredentials,+ redirectUriFor: (p) => admissionRedirectUri(deps.publicBaseUrl, p),+ })+}diff --git a/products/agent_platform/services/agent-ingress/src/index.ts b/products/agent_platform/services/agent-ingress/src/index.tsindex 8f52560efdb1..9303466e0cf5 100644--- a/products/agent_platform/services/agent-ingress/src/index.ts+++ b/products/agent_platform/services/agent-ingress/src/index.ts@@ -27,6 +27,7 @@ import {PgIdentityCredentialStore,PgIdentityLinkStateStore,PgIdentityStore,+ PgTransportBindingStore,PgApprovalStore,PgRevisionStore,PgSessionQueue,@@ -144,6 +145,7 @@ async function main(): Promise<void> {// rebuilds the provider from the app's spec + decrypted env, and persists.identityCredentials: new PgIdentityCredentialStore(agentDb, { encryptionSaltKeys: config.encryptionSaltKeys }),identityLinks: new PgIdentityLinkStateStore(agentDb),+ transportBindings: new PgTransportBindingStore(agentDb),envEncryption: encryption,posthogApiBaseUrl: config.posthogApiBaseUrl,http,diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts b/products/agent_platform/services/agent-ingress/src/routing/server.test.tsindex b77fe722d175..e88ca5a92004 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.test.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.test.ts@@ -4,10 +4,16 @@ import request from 'supertest'import {AgentSpecSchema,+ DirectHttpClient,+ EncryptedFields,PgApprovalStore,PgCredentialBroker,+ PgIdentityCredentialStore,+ PgIdentityLinkStateStore,+ PgIdentityStore,PgRevisionStore,PgSessionQueue,+ PgTransportBindingStore,RedisSessionEventBus,} from '@posthog/agent-shared'import type { AgentApplication, AgentRevision } from '@posthog/agent-shared'@@ -180,6 +186,14 @@ describe('ingress HTTP server (path mode)', () => {approvals,bus,credentialBroker,+ identities: new PgIdentityStore(pool),+ http: new DirectHttpClient(),+ identityCredentials: new PgIdentityCredentialStore(pool, {+ encryptionSaltKeys: HARNESS_ENCRYPTION_SALT_KEYS,+ }),+ identityLinks: new PgIdentityLinkStateStore(pool),+ transportBindings: new PgTransportBindingStore(pool),+ envEncryption: new EncryptedFields(HARNESS_ENCRYPTION_SALT_KEYS),// Opt in to the PostHog identity verifiers for the principal-authed// read-route tests; default stays public-only like the rest....(opts?.withAuth ? { authProvider: testAuthProvider } : {}),diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.tsindex 45b303b1e326..b014ff65d197 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts@@ -16,6 +16,7 @@ import type {IdentityLinkStateStore,IdentityStore,SecretResolver,+ TransportBindingStore,} from '@posthog/agent-shared'import {applyApprovalDecision,@@ -36,6 +37,7 @@ const log = createLogger('ingress')import { SessionEventBus } from '@posthog/agent-shared'import type { AuthConfig } from '@posthog/agent-shared'+import { buildAdmission } from '../enqueue/admission-gate'import { authorize, AuthProvider, principalsMatch, PUBLIC_ONLY_AUTH_PROVIDER } from '../enqueue/auth'import { chatTrigger } from '../triggers/chat'import { mcpTrigger } from '../triggers/mcp'@@ -108,8 +110,8 @@ export interface BuildAppOpts {*/slackSigningSecretResolver?: SecretResolverauthProvider?: AuthProvider- /** Optional identity store — Slack trigger uses this to mint stable AgentUser ids. */- identities?: IdentityStore+ /** Identity store — mints stable AgentUser ids for transport principals. */+ identities: IdentityStore/*** Approval store — backs the principal-decision surfaces (the Slack* interactivity handler today; the `POST /approvals/:id/decide` route).@@ -134,20 +136,20 @@ export interface BuildAppOpts {/*** Outbound HTTP for a trigger's outbound calls (the slack trigger's* bot-token Slack calls). Wired at the ingress entrypoint from- * `config.httpsProxy` so the call dispatches through smokescreen in- * prod. Optional — falls back to a direct HttpClient in tests.+ * `config.httpsProxy` so the call dispatches through smokescreen in prod.*/- http?: import('@posthog/agent-shared').HttpFetcher+ http: import('@posthog/agent-shared').HttpFetcher/**- * Identity-linking stores + env decryptor. When all three are wired, the- * ingress serves `GET /link/:provider/callback`: it consumes the OAuth- * link-state row, rebuilds the provider from the app's spec + decrypted- * encrypted_env, and persists the credential. Optional — omitted in tests- * that don't exercise the callback.+ * Identity-linking stores + env decryptor. The ingress serves+ * `GET /link/:provider/callback`: it consumes the OAuth link-state row,+ * rebuilds the provider from the app's spec + decrypted encrypted_env, and+ * persists the credential.*/- identityCredentials?: IdentityCredentialStore- identityLinks?: IdentityLinkStateStore- envEncryption?: EncryptedFields+ identityCredentials: IdentityCredentialStore+ identityLinks: IdentityLinkStateStore+ /** Durable transport→canonical-identity bindings; backs edge admission. */+ transportBindings: TransportBindingStore+ envEncryption: EncryptedFields/** PostHog API base — the `{kind:posthog}` provider builds its OAuth* endpoints from this in the link callback. Without it the callback can't* rebuild the posthog provider ("Unknown provider"). */@@ -279,10 +281,6 @@ export function buildApp(opts: BuildAppOpts): Express {'/link/:provider/callback',asyncHandler(async (req: Request, res: Response) => {const { identityLinks, identityCredentials, envEncryption, http } = opts- if (!identityLinks || !identityCredentials || !envEncryption || !http) {- res.status(500).send(linkResultPage('Identity linking is not configured on this ingress.'))- return- }const providerId = req.params.providerconst stateId = typeof req.query.state === 'string' ? req.query.state : ''const code = typeof req.query.code === 'string' ? req.query.code : undefined@@ -320,7 +318,15 @@ export function buildApp(opts: BuildAppOpts): Express {return}try {- await provider.complete({ stateId, query: { code, error: errorParam } })+ // Authoritative-provider callback → admission.complete (writes the+ // canonical identity + transport binding). Any other provider is a+ // per-asker capability link → the provider persists its own credential.+ const admission = buildAdmission(opts, revision)+ if (admission && providerId === revision.spec.authoritative_provider) {+ await admission.complete(providerId, stateId, { code, error: errorParam })+ } else {+ await provider.complete({ stateId, query: { code, error: errorParam } })+ }} catch (err) {log.warn({ provider: providerId, err: err instanceof Error ? err.message : String(err) },@@ -352,6 +358,12 @@ export function buildApp(opts: BuildAppOpts): Express {routingMode: opts.routingMode,domainSuffix: opts.domainSuffix,publicBaseUrl: opts.publicBaseUrl,+ // Edge admission (Slack trigger).+ identityLinks: opts.identityLinks,+ identityCredentials: opts.identityCredentials,+ transportBindings: opts.transportBindings,+ envEncryption: opts.envEncryption,+ posthogApiBaseUrl: opts.posthogApiBaseUrl,} as constconst mount = opts.routingMode === 'path' ? `${opts.pathPrefix ?? '/agents'}/:slug` : ''diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.tsindex c99cffe65fde..964fd158cf5b 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts@@ -28,6 +28,7 @@ import {} from '@posthog/agent-shared'import { applyElevationDecline, applyElevationGrant, authorizeGrant } from '../enqueue/acl'+import { buildAdmission } from '../enqueue/admission-gate'import { enqueueOrResume } from '../enqueue/enqueue'import { getOwnedSession } from './session-access'import { verifySlackSignature } from './slack-signature'@@ -219,11 +220,61 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {agentUserId = agentUser.id}+ // Edge admission: if the agent declares an authoritative provider, the Slack+ // claim must resolve a verified identity before we run. Unauthenticated →+ // deliver an auth link and enqueue nothing.+ let canonicalAgentUserId: string | undefined+ const admission = buildAdmission(deps, resolved.revision)+ if (admission) {+ const result = await admission.resolve(+ {+ transport: 'slack',+ subjectId: principalId,+ attributes: { workspace: workspaceId, slack_user: event.user },+ },+ { application: resolved.application, revision: resolved.revision }+ )+ if (result.kind === 'auth_required') {+ // Deliver the link privately with chat.postEphemeral so only the+ // original sender sees it — otherwise any channel member could open+ // the state-bearing URL and bind their provider account to the+ // sender's Slack transport principal. A thread fallback would+ // re-open that hijack, so on delivery failure we return non-2xx+ // instead — Slack retries the event (recovers from transient+ // errors) and ops gets an error log for persistent failures.+ const delivered = await postEphemeralMessage(deps, resolved.application, resolved.revision, {+ channel: event.channel,+ user: event.user,+ thread_ts: event.thread_ts ?? event.ts,+ text: `Before I can help, please connect your account: ${result.authorizeUrl}`,+ }).catch(() => false)+ if (!delivered) {+ log.error(+ { slug: resolved.application.slug, provider: result.provider },+ 'slack_admission_link_delivery_failed'+ )+ res.status(500).json({ error: 'auth_link_delivery_failed' })+ return+ }+ res.json({ ok: true, auth_required: true, provider: result.provider, authorize_url: result.authorizeUrl })+ return+ }+ if (result.kind === 'error') {+ log.warn({ slug: resolved.application.slug, reason: result.reason }, 'slack_admission_error')+ res.status(500).json({ error: 'admission_failed' })+ return+ }+ if (result.kind === 'admitted') {+ canonicalAgentUserId = result.identity.canonicalId+ }+ }+const slackPrincipal: SessionPrincipal = {kind: 'slack',workspace_id: workspaceId,slack_user_id: event.user,agent_user_id: agentUserId,+ ...(canonicalAgentUserId ? { canonical_agent_user_id: canonicalAgentUserId } : {}),}// Embed the Slack envelope context in the seed message so the model knows// which channel/ts/thread_ts to use when calling Slack APIs.@@ -624,6 +675,63 @@ async function postAckReaction(log.info({ slug: application.slug, channel: opts.channel, ts: opts.ts, reaction: opts.name }, 'ack_reaction_ok')}+/**+ * Post an ephemeral message visible only to `user` using the agent's bot token.+ * Used to deliver admission auth links privately so the state-bearing URL is+ * not visible to other channel members. Same error-swallow contract as+ * `postThreadMessage`. Returns true if the message posted.+ */+async function postEphemeralMessage(+ deps: TriggerDeps,+ application: AgentApplication,+ revision: AgentRevision,+ opts: { channel: string; user: string; thread_ts: string; text: string }+): Promise<boolean> {+ const token = await deps.signingSecretResolver.resolve(SLACK_BOT_TOKEN_KEY, revision)+ if (!token || !deps.http) {+ log.warn(+ { slug: application.slug, has_token: Boolean(token), has_http: Boolean(deps.http) },+ 'ephemeral_message_skipped'+ )+ return false+ }+ try {+ const res = await deps.http.fetch('https://slack.com/api/chat.postEphemeral', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json; charset=utf-8',+ },+ body: JSON.stringify({+ channel: opts.channel,+ user: opts.user,+ thread_ts: opts.thread_ts,+ text: opts.text,+ }),+ })+ let body: { ok?: boolean; error?: string } = {}+ try {+ body = (await res.json()) as { ok?: boolean; error?: string }+ } catch {+ // Non-JSON response — treat as failure but don't throw.+ }+ if (!res.ok || body.ok === false) {+ log.warn(+ { slug: application.slug, channel: opts.channel, status: res.status, slack_error: body.error ?? null },+ 'ephemeral_message_failed'+ )+ return false+ }+ return true+ } catch (err) {+ log.warn(+ { slug: application.slug, channel: opts.channel, err: err instanceof Error ? err.message : String(err) },+ 'ephemeral_message_threw'+ )+ return false+ }+}+/*** Post a plain text reply into a thread using the agent's bot token. Used to* tell a rejected non-owner (owner-only threads) why their message diddiff --git a/products/agent_platform/services/agent-ingress/src/triggers/types.ts b/products/agent_platform/services/agent-ingress/src/triggers/types.tsindex e9c78a9ce1ee..fb5a4323d07a 100644--- a/products/agent_platform/services/agent-ingress/src/triggers/types.ts+++ b/products/agent_platform/services/agent-ingress/src/triggers/types.ts@@ -25,12 +25,16 @@ import type {AuthConfig,CredentialBroker,CredentialMap,+ EncryptedFields,HttpFetcher,+ IdentityCredentialStore,+ IdentityLinkStateStore,IdentityStore,SecretResolver,SessionEventBus,SessionPrincipal,SessionQueue,+ TransportBindingStore,Trigger,} from '@posthog/agent-shared'@@ -45,7 +49,7 @@ export interface TriggerDeps {authProvider?: AuthProvider/** Resolves the per-agent Slack signing secret named by `slack.config.signing_secret_ref`. */signingSecretResolver: SecretResolver- identities?: IdentityStore+ identities: IdentityStore/*** Approval store — the Slack interactivity handler drives `principal`-type* tool-approval decisions through it (markApproving/markRejected + wake) via@@ -65,11 +69,19 @@ export interface TriggerDeps {* entrypoint so the call dispatches through smokescreen in prod alongside* every other fetch.*/- http?: HttpFetcher+ http: HttpFetcher/** Routing mode + URL inputs the MCP connect-info endpoint advertises. */routingMode?: RoutingModedomainSuffix?: stringpublicBaseUrl?: string+ /** Edge-admission stores (Slack trigger). 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+ identityCredentials: IdentityCredentialStore+ transportBindings: TransportBindingStore+ envEncryption: EncryptedFields+ posthogApiBaseUrl?: string}/** Pulled from the `Trigger` discriminator in `@posthog/agent-shared` so thisdiff --git a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts b/products/agent_platform/services/agent-runner/src/loop/approval.test.tsindex fba9910db719..85915508d9d2 100644--- a/products/agent_platform/services/agent-runner/src/loop/approval.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/approval.test.ts@@ -324,3 +324,87 @@ describe('dispatchApprovedResult: proxy-routed resume', () => {expect(d.error).toBe('native tool unknown: posthog__get-insights')})})++describe('dispatchApprovedResult: proxy-routed resume', () => {+ // A proxy connection gates `call_tool` on the underlying tool, so the+ // approval row is keyed `<prefix>__<remoteName>` with the call_tool args+ // stashed as proposed_args. On resume the driver must route that row back to+ // the connection's `call_tool` executor (via resolveApprovedExecutor) — a+ // plain `realExecute.get(row.tool_name)` misses it and drops the call.+ function makeProxyRow(over: Partial<ApprovalRequest> = {}): ApprovalRequest {+ return {+ id: 'req-proxy-1',+ session_id: TEST_SESSION_ID,+ application_id: TEST_APP_ID,+ revision_id: TEST_REV_ID,+ team_id: 1,+ turn: 1,+ tool_call_id: 'tc-9',+ tool_name: 'posthog__get-insights',+ proposed_args: { tool_name: 'get-insights', arguments: { limit: 5 } },+ args_hash: Buffer.alloc(0),+ assistant_message: null,+ approver_scope: null,+ state: 'approving',+ decision_by: 'u1',+ decision_at: null,+ decision_reason: null,+ decided_args: null,+ dispatch_outcome: null,+ expires_at: '2026-06-26',+ created_at: '2026-06-26',+ ...over,+ } as ApprovalRequest+ }++ function dispatchStore(): ApprovalStore & { dispatched: Array<{ id: string; outcome: unknown }> } {+ const dispatched: Array<{ id: string; outcome: unknown }> = []+ return {+ dispatched,+ async markDispatched(id: string, outcome: unknown): Promise<void> {+ dispatched.push({ id, outcome })+ },+ } as unknown as ApprovalStore & { dispatched: Array<{ id: string; outcome: unknown }> }+ }++ it('replays the approved proxy call through the connection call_tool executor', async () => {+ const seen: Array<{ id: string; args: Record<string, unknown> }> = []+ const callToolExec: RealToolExecute = async (id, args) => {+ seen.push({ id, args })+ return { content: [{ type: 'text' as const, text: 'ok' }], details: { output: { ran: true } } }+ }+ const realExecute = new Map<string, RealToolExecute>([['posthog__call_tool', callToolExec]])+ const proxyCallTools = new Map<string, unknown>([['posthog__call_tool', {}]])+ const row = makeProxyRow()+ const store = dispatchStore()++ const d = await dispatchApprovedResult({+ approvals: store,+ realExecute: resolveApprovedExecutor(row.tool_name, realExecute, proxyCallTools),+ row,+ })++ expect(d.isError).toBe(false)+ // The call_tool executor ran with the row's stored call_tool args (the+ // remote tool + its arguments), i.e. the real call replayed.+ expect(seen).toEqual([{ id: 'tc-9', args: { tool_name: 'get-insights', arguments: { limit: 5 } } }])+ expect(store.dispatched[0]?.outcome).toEqual({ result: { ran: true } })+ })++ it('the old direct lookup (the bug) drops the call with a synthetic "unknown tool"', async () => {+ const realExecute = new Map<string, RealToolExecute>([+ ['posthog__call_tool', async () => ({ content: [], details: {} })],+ ])+ const row = makeProxyRow()++ const d = await dispatchApprovedResult({+ approvals: dispatchStore(),+ // What the driver did before: a plain lookup by the re-keyed name.+ realExecute: realExecute.get(row.tool_name),+ row,+ })++ expect(d.isError).toBe(true)+ expect(d.error).toBe('native tool unknown: posthog__get-insights')+ })+})diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.tsindex 865e19072de8..05f92a4cf80b 100644--- a/products/agent_platform/services/agent-shared/src/index.ts+++ b/products/agent_platform/services/agent-shared/src/index.ts@@ -57,6 +57,9 @@ export * from './runtime/identity-provider'export * from './runtime/oauth2-identity-provider'export * from './runtime/posthog-identity-provider'export * from './runtime/identity-gate'+export * from './runtime/transport'+export * from './runtime/transport-binding-store'+export * from './runtime/admission'export * from './runtime/log-sink'export * from './runtime/logger'export * from './runtime/instrument'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.tsnew file mode 100644index 000000000000..20a0d2b7d265--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/admission.test.ts@@ -0,0 +1,713 @@+/**+ * Admission engine — the architecture-level e2e, PG-free. Drives the full arc+ * with the REAL `Oauth2AuthProvider` against scripted IdPs and in-memory stores:+ *+ * claim → auth_required → OAuth round-trip → binding + canonical identity →+ * re-admit (durable) → second transport binds to the SAME identity →+ * secondary provider links to the SAME canonical identity → per-request bearer+ * admits inline → passthrough when no authoritative provider → fail-closed.+ */++import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import type { AgentUser, IdentityStore } from '../persistence/identity-store'+import { AgentSpecSchema } from '../spec/spec'+import type { AgentApplication, AgentRevision, AgentSpec } from '../spec/spec'+import { AdmissionService, canonicalKind } from './admission'+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 { Oauth2AuthProvider } from './oauth2-identity-provider'+import type { TransportClaim } from './transport'+import { MemoryTransportBindingStore } from './transport-binding-store'++// ---------- in-memory stores ----------++let auSeq = 0+class MemIdentityStore implements IdentityStore {+ readonly rows = new Map<string, AgentUser>()+ private key(app: string, kind: string, id: string): string {+ return `${app}::${kind}::${id}`+ }+ async findOrCreate(input: {+ team_id: number+ application_id: string+ principal_kind: string+ principal_id: string+ metadata?: Record<string, unknown>+ }): Promise<AgentUser> {+ const k = this.key(input.application_id, input.principal_kind, input.principal_id)+ const existing = this.rows.get(k)+ if (existing) {+ return existing+ }+ const row: AgentUser = {+ id: `au-${++auSeq}`,+ team_id: input.team_id,+ application_id: input.application_id,+ principal_kind: input.principal_kind,+ principal_id: input.principal_id,+ metadata: input.metadata,+ created_at: '2026-01-01T00:00:00Z',+ }+ this.rows.set(k, row)+ return row+ }+ async find(input: {+ application_id: string+ principal_kind: string+ principal_id: string+ }): Promise<AgentUser | null> {+ return this.rows.get(this.key(input.application_id, input.principal_kind, input.principal_id)) ?? null+ }+ async getById(agentUserId: string): Promise<AgentUser | null> {+ for (const r of this.rows.values()) {+ if (r.id === agentUserId) {+ return r+ }+ }+ return null+ }+}++class MemLinkStore implements IdentityLinkStateStore {+ private rows = new Map<string, LinkState & { used: boolean }>()+ private seq = 0+ async create(input: CreateLinkStateInput): Promise<string> {+ const id = `state-${++this.seq}`+ this.rows.set(id, { id, ...input, used: false } as LinkState & { used: boolean })+ return id+ }+ async peek(id: string): Promise<{ applicationId: string; provider: string } | null> {+ const r = this.rows.get(id)+ return r && !r.used ? { applicationId: r.applicationId, provider: r.provider } : null+ }+ async consume(id: string): Promise<LinkState | null> {+ const r = this.rows.get(id)+ if (!r || r.used) {+ return null+ }+ r.used = true+ const { used: _u, ...state } = r+ return state+ }+ async sweepExpired(): Promise<number> {+ return 0+ }+}++class MemCredStore implements IdentityCredentialStore {+ readonly rows = new Map<string, { input: PutLinkedCredentialInput; subject?: string; state: string }>()+ private key(a: string, p: string): string {+ return `${a}::${p}`+ }+ async put(input: PutLinkedCredentialInput): Promise<void> {+ const k = this.key(input.agentUserId, input.provider)+ const existing = this.rows.get(k)+ this.rows.set(k, { input, subject: input.subject ?? existing?.subject, state: 'active' })+ }+ async get(agentUserId: string, provider: string): Promise<LinkedCredential | null> {+ const r = this.rows.get(this.key(agentUserId, provider))+ if (!r || r.state !== 'active') {+ return null+ }+ return { agentUserId, provider, credential: r.input.credential, scopes: r.input.scopes ?? [] }+ }+ async getEstablishedSubject(agentUserId: string): Promise<string | null> {+ for (const [k, r] of this.rows) {+ if (k.startsWith(`${agentUserId}::`) && r.state === 'active' && r.subject) {+ return r.subject+ }+ }+ return null+ }+ async getAgentScoped(): Promise<LinkedCredential | null> {+ throw new Error('agent_binding_not_implemented')+ }+ async revoke(agentUserId: string, provider: string): Promise<void> {+ const r = this.rows.get(this.key(agentUserId, provider))+ if (r) {+ r.state = 'revoked'+ }+ }+ async remove(agentUserId: string, provider: string): Promise<void> {+ this.rows.delete(this.key(agentUserId, provider))+ }+}++// ---------- scripted IdP ----------++interface FakeIdp {+ base: string+ authorizeUrl: string+ tokenUrl: string+ userinfoUrl: string+ sub: string+ issued: string[]+}++function makeIdp(base: string, sub: string): FakeIdp {+ return {+ base,+ authorizeUrl: `${base}/authorize`,+ tokenUrl: `${base}/token`,+ userinfoUrl: `${base}/userinfo`,+ sub,+ issued: [],+ }+}++/** One HttpFetcher routing /token + /userinfo across several IdPs by host. */+function combinedHttp(idps: FakeIdp[]): HttpFetcher {+ const byHost = new Map(idps.map((i) => [new URL(i.base).host, i]))+ return {+ async fetch(input, init) {+ const url = new URL(String(input))+ const idp = byHost.get(url.host)+ if (!idp) {+ return new Response('no idp', { status: 404 })+ }+ if (init?.method === 'POST' && url.pathname === '/token') {+ const token = `${idp.sub}-at-${idp.issued.length + 1}`+ idp.issued.push(token)+ return new Response(+ JSON.stringify({+ access_token: token,+ refresh_token: `${idp.sub}-rt`,+ token_type: 'Bearer',+ expires_in: 3600,+ }),+ { status: 200, headers: { 'content-type': 'application/json' } }+ )+ }+ if (url.pathname === '/userinfo') {+ return new Response(JSON.stringify({ sub: idp.sub, email: `${idp.sub}@example.com` }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ }+ return new Response('not found', { status: 404 })+ },+ }+}++// ---------- fixtures + harness ----------++const APP: AgentApplication = {+ id: 'app-1',+ team_id: 7,+ slug: 'bot',+ name: 'Bot',+ description: '',+ live_revision_id: 'rev-1',+ archived: false,+}++function revWith(authoritative?: string): AgentRevision {+ return {+ id: 'rev-1',+ application_id: 'app-1',+ parent_revision_id: null,+ created_by_id: null,+ created_at: '2026-01-01T00:00:00Z',+ state: 'live',+ bundle_uri: 's3://x',+ bundle_sha256: null,+ spec: { authoritative_provider: authoritative } as AgentSpec,+ encrypted_env: null,+ }+}++const REDIRECT = (p: string): string => `https://cb.test/link/${p}/callback`++interface Harness {+ admission: AdmissionService+ identities: MemIdentityStore+ bindings: MemoryTransportBindingStore+ credentials: MemCredStore+ links: MemLinkStore+ registry: MapIdentityProviderRegistry+}++function harness(idps: FakeIdp[]): Harness {+ const identities = new MemIdentityStore()+ const bindings = new MemoryTransportBindingStore()+ const credentials = new MemCredStore()+ const links = new MemLinkStore()+ const http = combinedHttp(idps)+ const registry = new MapIdentityProviderRegistry(+ idps.map(+ (i) =>+ new Oauth2AuthProvider({+ config: {+ id: providerIdFor(i),+ authorizeUrl: i.authorizeUrl,+ tokenUrl: i.tokenUrl,+ userinfoUrl: i.userinfoUrl,+ clientId: `${providerIdFor(i)}-client`,+ scopes: ['read'],+ },+ links,+ credentials,+ http,+ })+ )+ )+ const admission = new AdmissionService({ registry, identities, bindings, credentials, redirectUriFor: REDIRECT })+ return { admission, identities, bindings, credentials, links, registry }+}++const providerIdFor = (i: FakeIdp): string => new URL(i.base).host.split('.')[0]++/** Simulate the browser leg: pull `state` out of the authorize URL, hand a code+ * back through the admission callback. */+async function driveLink(h: Harness, authorizeUrl: string): Promise<ReturnType<AdmissionService['complete']>> {+ const u = new URL(authorizeUrl)+ const state = u.searchParams.get('state')+ const providerId = h.registry.all().find((p) => p.id && authorizeUrl.includes(p.id))?.id+ expect(state).toBeTruthy()+ expect(providerId).toBeTruthy()+ return h.admission.complete(providerId!, state!, { code: 'code-1', state: state! })+}++describe('AdmissionService', () => {+ it('Slack: unbound → auth_required → link writes binding + canonical → re-admit is durable', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const claim: TransportClaim = { transport: 'slack', subjectId: 'T01:U01' }++ const first = await h.admission.resolve(claim, { application: APP, revision: revWith('work') })+ expect(first.kind).toBe('auth_required')+ if (first.kind !== 'auth_required') {+ return+ }+ expect(first.provider).toBe('work')+ expect(first.authorizeUrl).toContain('work.example/authorize')++ const verified = await driveLink(h, first.authorizeUrl)+ expect(verified.subject).toBe('alice')+ expect(verified.provider).toBe('work')++ // Canonical identity is an AgentUser keyed on the authoritative subject.+ const canonical = await h.identities.find({+ application_id: 'app-1',+ principal_kind: canonicalKind('work'),+ principal_id: 'alice',+ })+ expect(canonical?.id).toBe(verified.canonicalId)++ // Authoritative credential persisted under the canonical id, resolvable.+ const cred = await h.credentials.get(verified.canonicalId, 'work')+ expect(cred?.credential.access_token).toBe('alice-at-1')++ // Second turn: durable binding admits without a link.+ const second = await h.admission.resolve(claim, { application: APP, revision: revWith('work') })+ expect(second.kind).toBe('admitted')+ if (second.kind === 'admitted') {+ expect(second.identity.canonicalId).toBe(verified.canonicalId)+ expect(second.identity.transportAgentUserId).toBe(verified.transportAgentUserId)+ }+ })++ it('one identity, many transports: Slack + Discord for the same person bind to ONE canonical identity', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const rev = revWith('work')++ const slack = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:US' },+ { application: APP, revision: rev }+ )+ const slackId = slack.kind === 'auth_required' ? (await driveLink(h, slack.authorizeUrl)).canonicalId : ''++ const discord = await h.admission.resolve(+ { transport: 'discord', subjectId: 'G:UD' },+ { application: APP, revision: rev }+ )+ expect(discord.kind).toBe('auth_required')+ const discordId = discord.kind === 'auth_required' ? (await driveLink(h, discord.authorizeUrl)).canonicalId : ''++ expect(slackId).toBe(discordId) // same subject → same canonical identity+ const all = await h.bindings.listForCanonical('app-1', slackId)+ expect(all.map((b) => b.transportAgentUserId).sort()).toHaveLength(2)+ expect(new Set(all.map((b) => b.transportAgentUserId)).size).toBe(2) // two distinct transports+ })++ it('multi-provider: a secondary provider links to the SAME canonical identity, shared across transports', async () => {+ const work = makeIdp('https://work.example', 'alice') // authoritative+ const dogs = makeIdp('https://dogs.example', 'alice-dog') // secondary capability+ const h = harness([work, dogs])+ const rev = revWith('work')++ // Admit via Slack.+ const admit = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:US' },+ { application: APP, revision: rev }+ )+ const canonicalId = admit.kind === 'auth_required' ? (await driveLink(h, admit.authorizeUrl)).canonicalId : ''+ expect(canonicalId).toBeTruthy()++ // Link the secondary 'dogs' provider directly against the CANONICAL id.+ const dogsProvider = h.registry.require('dogs')+ const { authorizeUrl } = await dogsProvider.initiate({+ agentUserId: canonicalId,+ teamId: 7,+ applicationId: 'app-1',+ scopes: [],+ redirectUri: REDIRECT('dogs'),+ })+ const dogsState = new URL(authorizeUrl).searchParams.get('state')!+ await dogsProvider.complete({ stateId: dogsState, query: { code: 'c', state: dogsState } })++ // Resolvable as the canonical identity → usable from ANY of that person's+ // transports, because every transport binds to this one canonical id.+ const dogCred = await dogsProvider.resolve({+ agentUserId: canonicalId,+ teamId: 7,+ applicationId: 'app-1',+ scopes: [],+ })+ expect(dogCred?.kind).toBe('oauth_bearer')+ expect(dogCred && 'token' in dogCred ? dogCred.token : '').toBe('alice-dog-at-1')+ })++ it('HTTP: a per-request bearer the provider can verify inline admits without a link', async () => {+ const identities = new MemIdentityStore()+ const bindings = new MemoryTransportBindingStore()+ const credentials = new MemCredStore()+ // An authoritative provider that proves identity from a bearer (no OAuth leg).+ 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,+ async verifyBearer(token: string): Promise<BearerVerification | null> {+ return token === 'good-bearer'+ ? { subject: 'alice', stored: { access_token: token }, scopes: ['read'] }+ : null+ },+ }+ const admission = new AdmissionService({+ registry: new MapIdentityProviderRegistry([provider]),+ identities,+ bindings,+ credentials,+ redirectUriFor: REDIRECT,+ })+ const res = await admission.resolve(+ { transport: 'http', subjectId: 'jwt-sub', bearer: { token: 'good-bearer' } },+ { application: APP, revision: revWith('work') }+ )+ expect(res.kind).toBe('admitted')+ if (res.kind === 'admitted') {+ expect(res.identity.subject).toBe('alice')+ const cred = await credentials.get(res.identity.canonicalId, 'work')+ expect(cred?.credential.access_token).toBe('good-bearer')+ const binding = await bindings.find('app-1', res.identity.transportAgentUserId)+ expect(binding?.canonicalAgentUserId).toBe(res.identity.canonicalId)+ }+ })++ 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+ // invalid (revoked/expired) must stop admitting — the durable binding+ // must not substitute for the freshness check.+ const identities = new MemIdentityStore()+ const bindings = new MemoryTransportBindingStore()+ const credentials = new MemCredStore()+ const provider: IdentityProvider = {+ id: 'work',+ credentialTarget: 'work',+ establishesIdentity: true,+ binding: 'principal',+ allowedHosts: () => ['work.example'],+ // A real OAuth leg so a failed bearer re-auths (auth_required) rather+ // than erroring — makes the "not admitted" assertion crisp.+ initiate: async () => ({ authorizeUrl: 'https://work.example/authorize?state=s', stateId: 's' }),+ exchange: async () => {+ throw new Error('should_not_exchange')+ },+ complete: async () => {+ throw new Error('should_not_complete')+ },+ resolve: async () => null,+ async verifyBearer(token: string): Promise<BearerVerification | null> {+ return token === 'good-bearer'+ ? { subject: 'alice', stored: { access_token: token }, scopes: ['read'] }+ : null+ },+ }+ const admission = new AdmissionService({+ registry: new MapIdentityProviderRegistry([provider]),+ identities,+ bindings,+ credentials,+ redirectUriFor: REDIRECT,+ })+ const claim = (token: string): TransportClaim => ({+ transport: 'http',+ subjectId: 'jwt-sub',+ bearer: { token },+ })+ const ctx = { application: APP, revision: revWith('work') }++ // First request with a valid bearer → admitted + binding written.+ const ok = await admission.resolve(claim('good-bearer'), ctx)+ expect(ok.kind).toBe('admitted')+ const transportUserId = ok.kind === 'admitted' ? ok.identity.transportAgentUserId : ''+ expect((await bindings.find('app-1', transportUserId))?.canonicalAgentUserId).toBeTruthy()++ // Same transport principal, now a revoked/expired bearer → must re-auth,+ // NOT admit via the stale binding.+ const revoked = await admission.resolve(claim('revoked-bearer'), ctx)+ expect(revoked.kind).toBe('auth_required')+ })++ it('passthrough: no authoritative provider → transport claim is the identity', async () => {+ const h = harness([])+ const res = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:U' },+ { application: APP, revision: revWith(undefined) }+ )+ expect(res.kind).toBe('passthrough')+ if (res.kind === 'passthrough') {+ const u = await h.identities.getById(res.transportAgentUserId)+ expect(u?.principal_kind).toBe('slack')+ }+ })++ it('fails closed on an unknown authoritative provider', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const res = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:U' },+ { application: APP, revision: revWith('nope') }+ )+ expect(res.kind).toBe('error')+ })++ it('replay: completing the same link state twice fails (single-use)', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const first = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:U' },+ { application: APP, revision: revWith('work') }+ )+ if (first.kind !== 'auth_required') {+ throw new Error('expected auth_required')+ }+ const state = new URL(first.authorizeUrl).searchParams.get('state')!+ await h.admission.complete('work', state, { code: 'c', state })+ await expect(h.admission.complete('work', state, { code: 'c', state })).rejects.toThrow('oauth_invalid_state')+ })++ it('dangling binding (canonical vanished) falls through to auth_required', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const rev = revWith('work')+ const claim: TransportClaim = { transport: 'slack', subjectId: 'T:U' }+ const first = await h.admission.resolve(claim, { application: APP, revision: rev })+ const verified = first.kind === 'auth_required' ? await driveLink(h, first.authorizeUrl) : null+ expect(verified).toBeTruthy()+ // Drop the canonical identity row out from under the binding.+ h.identities.rows.delete(`app-1::${canonicalKind('work')}::alice`)+ const again = await h.admission.resolve(claim, { application: APP, revision: rev })+ expect(again.kind).toBe('auth_required') // not a crash, not a stale admit+ })++ it('stale binding: authoritative provider swapped since link → re-auth against the new provider', async () => {+ // A binding is scoped to the provider that established it. If the agent+ // switches its authoritative_provider, the prior binding must NOT admit+ // the transport principal against the new provider — otherwise a+ // once-linked Slack user stays "authenticated" as a different identity+ // system than the current spec demands.+ const work = makeIdp('https://work.example', 'alice')+ const dogs = makeIdp('https://dogs.example', 'rex')+ const h = harness([work, dogs])+ const claim: TransportClaim = { transport: 'slack', subjectId: 'T:U' }++ // Link under provider 'work'.+ const first = await h.admission.resolve(claim, { application: APP, revision: revWith('work') })+ expect(first.kind).toBe('auth_required')+ if (first.kind === 'auth_required') {+ await driveLink(h, first.authorizeUrl)+ }+ // Sanity: same claim + same authoritative provider → durable admit.+ const durable = await h.admission.resolve(claim, { application: APP, revision: revWith('work') })+ expect(durable.kind).toBe('admitted')++ // Agent flips authoritative_provider to 'dogs'. The old binding must+ // not carry over — force a fresh link against 'dogs'.+ const flipped = await h.admission.resolve(claim, { application: APP, revision: revWith('dogs') })+ expect(flipped.kind).toBe('auth_required')+ if (flipped.kind === 'auth_required') {+ expect(flipped.provider).toBe('dogs')+ }+ })++ it('revoked authoritative credential invalidates the binding → re-auth', async () => {+ // A binding without a live credential is meaningless — the authoritative+ // provider has nothing to prove the identity with anymore. Revoking+ // (or removing) the credential must stop admitting via the durable+ // binding until the user re-links.+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const rev = revWith('work')+ const claim: TransportClaim = { transport: 'slack', subjectId: 'T:U' }++ const first = await h.admission.resolve(claim, { application: APP, revision: rev })+ const linked = first.kind === 'auth_required' ? await driveLink(h, first.authorizeUrl) : null+ expect(linked).toBeTruthy()++ // Sanity: durable admit works while the credential is active.+ const admittedAgain = await h.admission.resolve(claim, { application: APP, revision: rev })+ expect(admittedAgain.kind).toBe('admitted')++ // Credential revoked (e.g. admin unlinked). Binding still exists but+ // must no longer admit — a fresh link is required.+ await h.credentials.revoke(linked!.canonicalId, 'work')+ const afterRevoke = await h.admission.resolve(claim, { application: APP, revision: rev })+ expect(afterRevoke.kind).toBe('auth_required')+ })++ it('re-auth as a different subject replaces the binding (account switch)', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const h = harness([work])+ const rev = revWith('work')+ const claim: TransportClaim = { transport: 'slack', subjectId: 'T:U' }+ const a = await h.admission.resolve(claim, { application: APP, revision: rev })+ const first = a.kind === 'auth_required' ? await driveLink(h, a.authorizeUrl) : null++ // The IdP now proves a different subject for the same transport principal.+ work.sub = 'bob'+ const b = await h.admission.resolve(claim, { application: APP, revision: rev })+ // Still admitted via the OLD binding until re-link; force a re-link instead.+ const transportUserId = first!.transportAgentUserId+ await h.bindings.unbind('app-1', transportUserId)+ const c = await h.admission.resolve(claim, { application: APP, revision: rev })+ const second = c.kind === 'auth_required' ? await driveLink(h, c.authorizeUrl) : null+ expect(second!.subject).toBe('bob')+ expect(second!.canonicalId).not.toBe(first!.canonicalId)+ // Exactly one binding for this transport principal — the new one.+ const binding = await h.bindings.find('app-1', transportUserId)+ expect(binding?.canonicalAgentUserId).toBe(second!.canonicalId)+ void b+ })++ it('complete() rejects a provider that does not match the link state', async () => {+ const work = makeIdp('https://work.example', 'alice')+ const dogs = makeIdp('https://dogs.example', 'rex')+ const h = harness([work, dogs])+ const a = await h.admission.resolve(+ { transport: 'slack', subjectId: 'T:U' },+ { application: APP, revision: revWith('work') }+ )+ if (a.kind !== 'auth_required') {+ throw new Error('expected auth_required')+ }+ const state = new URL(a.authorizeUrl).searchParams.get('state')!+ // The link state is for 'work'; completing as 'dogs' must fail.+ await expect(h.admission.complete('dogs', state, { code: 'c', state })).rejects.toThrow('oauth_invalid_state')+ })+})++describe('AgentSpecSchema.authoritative_provider validation', () => {+ const base = { models: { mode: 'auto', level: 'medium', optimize_for: 'cost' } }+ const dogs = (userinfo?: string): Record<string, unknown> => ({+ kind: 'oauth2',+ id: 'dogs',+ authorize_url: 'https://d/authorize',+ token_url: 'https://d/token',+ client_id: 'c',+ ...(userinfo ? { userinfo_url: userinfo } : {}),+ })++ it('rejects an authoritative_provider with no matching identity_providers entry', () => {+ const r = AgentSpecSchema.safeParse({ ...base, authoritative_provider: 'nope' })+ expect(r.success).toBe(false)+ })++ it('rejects an oauth2 authoritative provider without userinfo_url (cannot prove a subject)', () => {+ const r = AgentSpecSchema.safeParse({+ ...base,+ authoritative_provider: 'dogs',+ identity_providers: [dogs()],+ })+ expect(r.success).toBe(false)+ })++ it('accepts an oauth2 authoritative provider with userinfo_url', () => {+ const r = AgentSpecSchema.safeParse({+ ...base,+ authoritative_provider: 'dogs',+ identity_providers: [dogs('https://d/userinfo')],+ })+ expect(r.success).toBe(true)+ })++ it('accepts a posthog authoritative provider', () => {+ const r = AgentSpecSchema.safeParse({+ ...base,+ authoritative_provider: 'posthog',+ identity_providers: [{ kind: 'posthog', id: 'posthog' }],+ })+ expect(r.success).toBe(true)+ })++ it('accepts a spec with no authoritative_provider (passthrough)', () => {+ expect(AgentSpecSchema.safeParse(base).success).toBe(true)+ })++ it('rejects authoritative_provider combined with a trigger whose ingress does not yet call admission', () => {+ // Fail-closed: today only the slack trigger runs `buildAdmission()`+ // before enqueue. A spec that mixes an authoritative provider with a+ // webhook / chat / mcp trigger would silently bypass admission on that+ // path. Loosen this once the other triggers wire the gate.+ const r = AgentSpecSchema.safeParse({+ ...base,+ authoritative_provider: 'posthog',+ identity_providers: [{ kind: 'posthog', id: 'posthog' }],+ triggers: [+ {+ type: 'webhook',+ config: { path: '/hook' },+ auth: { modes: [{ type: 'shared_secret', header: 'x-key', secret_ref: 'S' }] },+ },+ ],+ })+ expect(r.success).toBe(false)+ if (!r.success) {+ const msg = r.error.issues.map((i) => i.message).join('\n')+ expect(msg).toMatch(/webhook/)+ }+ })++ it('accepts authoritative_provider combined with a slack trigger (admission-wired)', () => {+ const r = AgentSpecSchema.safeParse({+ ...base,+ authoritative_provider: 'posthog',+ identity_providers: [{ kind: 'posthog', id: 'posthog' }],+ triggers: [{ type: 'slack', config: { trusted_workspaces: ['T01'] } }],+ })+ expect(r.success).toBe(true)+ })++ it('still serializes to JSON Schema (the refine does not break toJSONSchema)', () => {+ expect(() => z.toJSONSchema(AgentSpecSchema, { reused: 'ref' })).not.toThrow()+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/admission.ts b/products/agent_platform/services/agent-shared/src/runtime/admission.tsnew file mode 100644index 000000000000..8b7913e30167--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/admission.ts@@ -0,0 +1,236 @@+/**+ * Admission — the edge gate. Given a `TransportClaim` and an agent revision,+ * resolves a verified canonical identity from the agent's authoritative provider,+ * or returns an auth block to deliver. Runs BEFORE a session is enqueued.+ *+ * Canonical identity = an `AgentUser` keyed on (authoritative provider, subject).+ * The transport principal is a separate `AgentUser` (kind=transport); a durable+ * `TransportBinding` connects them. Secondary providers link to the canonical id.+ */++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 type { AdmissionResult, TransportClaim, VerifiedIdentity } from './transport'+import type { TransportBindingStore } from './transport-binding-store'++export type AdmissionLog = (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void++export interface AdmissionDeps {+ registry: IdentityProviderRegistry+ identities: IdentityStore+ bindings: TransportBindingStore+ credentials: IdentityCredentialStore+ /** Build the OAuth callback URL for a provider. */+ redirectUriFor: (providerId: string) => string+ log?: AdmissionLog+}++/** Canonical identities are AgentUsers namespaced so a provider id can never+ * collide with a transport id (e.g. an agent named provider 'posthog' vs a+ * hypothetical 'posthog' transport). */+export function canonicalKind(providerId: string): string {+ return `identity:${providerId}`+}++export class AdmissionService {+ constructor(private readonly deps: AdmissionDeps) {}++ /** Resolve admission for an inbound transport claim against an agent revision. */+ async resolve(+ claim: TransportClaim,+ ctx: { application: AgentApplication; revision: AgentRevision }+ ): Promise<AdmissionResult> {+ const teamId = ctx.application.team_id+ const applicationId = ctx.application.id+ const authoritativeId = ctx.revision.spec.authoritative_provider++ // The transport principal always exists — per-message sender for audit,+ // bindings, and per-asker secondary creds.+ const transportUser = await this.deps.identities.findOrCreate({+ team_id: teamId,+ application_id: applicationId,+ principal_kind: claim.transport,+ principal_id: claim.subjectId,+ metadata: claim.attributes,+ })++ if (!authoritativeId) {+ return { kind: 'passthrough', transportAgentUserId: transportUser.id }+ }++ const provider = this.deps.registry.get(authoritativeId)+ if (!provider) {+ this.deps.log?.('error', 'admission.unknown_provider', { provider: authoritativeId })+ return { kind: 'error', reason: `unknown_authoritative_provider:${authoritativeId}` }+ }++ // 1. Per-request bearer the provider can verify inline (HTTP transports).+ // A bearer is a PER-REQUEST proof: verify it on every request, BEFORE+ // consulting any durable binding. A binding must never substitute for+ // a fresh bearer check — otherwise a revoked or expired token keeps+ // admitting until the binding is explicitly unbound, silently turning+ // a one-time link into a permanent grant. So a present-but-invalid+ // 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)+ if (verified) {+ const canonical = await this.upsertCanonical(applicationId, teamId, authoritativeId, verified.subject)+ await this.deps.credentials.put({+ teamId,+ applicationId,+ agentUserId: canonical.id,+ provider: authoritativeId,+ credential: verified.stored,+ scopes: verified.scopes,+ subject: verified.subject,+ })+ await this.deps.bindings.bind({+ teamId,+ applicationId,+ transportAgentUserId: transportUser.id,+ canonicalAgentUserId: canonical.id,+ provider: authoritativeId,+ })+ return this.admitted(authoritativeId, canonical, transportUser.id, 'bearer')+ }+ this.deps.log?.('warn', 'admission.bearer_invalid', { provider: authoritativeId })+ // Present-but-invalid → fall through to initiate (re-auth). Do NOT+ // consult the durable binding — freshness must win over a prior link.+ } else {+ // 2. Durable binding → already authenticated. Only when there's no+ // verifiable per-request bearer (Slack/Discord, where the proof of+ // identity is the prior OAuth link, not a token on this request).+ const binding = await this.deps.bindings.find(applicationId, transportUser.id)+ if (binding) {+ // Bindings are provider-scoped: if the agent's authoritative+ // provider changed since the link, the old binding is stale —+ // fall through to re-auth against the current provider.+ if (binding.provider !== authoritativeId) {+ this.deps.log?.('warn', 'admission.stale_binding_provider', {+ binding_id: binding.id,+ binding_provider: binding.provider,+ authoritative_provider: authoritativeId,+ })+ } else {+ const canonical = await this.deps.identities.getById(binding.canonicalAgentUserId)+ if (canonical && canonical.principal_kind === canonicalKind(authoritativeId)) {+ // The binding is only trustworthy while the underlying+ // authoritative credential is still active. If it was+ // revoked or removed (`credentials.get` returns null+ // for both), the durable link is invalidated — fall+ // through so the user re-links and a fresh credential+ // is written before we admit again.+ const credential = await this.deps.credentials.get(canonical.id, authoritativeId)+ if (credential) {+ return this.admitted(authoritativeId, canonical, transportUser.id, 'binding')+ }+ this.deps.log?.('warn', 'admission.binding_credential_inactive', {+ binding_id: binding.id,+ canonical_id: canonical.id,+ provider: authoritativeId,+ })+ } else {+ // Dangling / mismatched canonical → fall through to re-auth.+ this.deps.log?.('warn', 'admission.dangling_binding', { binding_id: binding.id })+ }+ }+ }+ }++ // 3. Not authenticated → initiate a link bound to the transport principal.+ try {+ const { authorizeUrl } = await provider.initiate({+ agentUserId: transportUser.id,+ teamId,+ applicationId,+ scopes: [], // authoritative scopes come from the provider's own config+ redirectUri: this.deps.redirectUriFor(authoritativeId),+ })+ this.deps.log?.('info', 'admission.auth_required', {+ provider: authoritativeId,+ transport: claim.transport,+ })+ return { kind: 'auth_required', provider: authoritativeId, authorizeUrl }+ } catch (err) {+ this.deps.log?.('error', 'admission.initiate_failed', {+ provider: authoritativeId,+ reason: (err as Error).message,+ })+ return { kind: 'error', reason: (err as Error).message }+ }+ }++ /**+ * Complete an admission OAuth callback: exchange the code, derive the subject,+ * upsert the canonical identity, persist the authoritative credential under it,+ * and write the transport binding. The callback route peeks the link-state to+ * find `providerId`, rebuilds the registry, then calls this.+ */+ async complete(+ providerId: string,+ stateId: string,+ query: Record<string, string | undefined>+ ): Promise<VerifiedIdentity> {+ const provider = this.deps.registry.require(providerId)+ const { state, stored, subject, scopes } = await provider.exchange({ stateId, query })+ if (!subject) {+ // The authoritative provider MUST prove a subject (userinfo). Fail closed.+ throw new Error('admission_no_subject')+ }+ const transportAgentUserId = state.agentUserId+ const canonical = await this.upsertCanonical(state.applicationId, state.teamId, providerId, subject)+ await this.deps.credentials.put({+ teamId: state.teamId,+ applicationId: state.applicationId,+ agentUserId: canonical.id,+ provider: providerId,+ credential: stored,+ scopes,+ subject,+ })+ await this.deps.bindings.bind({+ teamId: state.teamId,+ applicationId: state.applicationId,+ transportAgentUserId,+ canonicalAgentUserId: canonical.id,+ provider: providerId,+ })+ this.deps.log?.('info', 'admission.linked', { provider: providerId, canonical_id: canonical.id })+ return { provider: providerId, subject, canonicalId: canonical.id, transportAgentUserId }+ }++ private async upsertCanonical(+ applicationId: string,+ teamId: number,+ providerId: string,+ subject: string+ ): Promise<AgentUser> {+ return this.deps.identities.findOrCreate({+ team_id: teamId,+ application_id: applicationId,+ principal_kind: canonicalKind(providerId),+ principal_id: subject,+ })+ }++ private admitted(+ provider: string,+ canonical: AgentUser,+ transportAgentUserId: string,+ source: string+ ): AdmissionResult {+ this.deps.log?.('info', 'admission.admitted', { provider, source, canonical_id: canonical.id })+ return {+ kind: 'admitted',+ identity: {+ provider,+ subject: canonical.principal_id,+ canonicalId: canonical.id,+ transportAgentUserId,+ },+ }+ }+}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.tsindex fc0e7c83f4da..3d28353b2145 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@@ -20,6 +20,7 @@ function fakeProvider(over: Partial<IdentityProvider> = {}): IdentityProvider {allowedHosts: () => ['app.posthog.test'],resolve: vi.fn(async () => null),initiate: vi.fn(async () => ({ authorizeUrl: 'https://app.posthog.test/oauth/authorize/?x=1', stateId: 's' })),+ exchange: vi.fn(),complete: vi.fn(),...over,}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.tsindex 733f70f6123a..a69799aef9a1 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@@ -126,7 +126,9 @@ export async function agentUserIdForPrincipal(}switch (principal.kind) {case 'slack':- return principal.agent_user_id ?? null+ // Canonical identity (edge admission) keys secondary links so they're+ // shared across transports; fall back to the raw principal on passthrough.+ return principal.canonical_agent_user_id ?? principal.agent_user_id ?? nullcase 'jwt':return findOrCreate('jwt', principal.sub)case 'posthog':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.tsindex 3eb3618941d7..06696bd2f51b 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@@ -11,6 +11,8 @@*/import type { Credential } from './credential-broker'+import type { StoredCredential } from './identity-credential-store'+import type { LinkState } from './identity-link-state-store'export interface IdentityInitiateInput {/** The principal being linked, resolved to an AgentUser id. */@@ -47,6 +49,32 @@ export interface IdentityResolveInput {scopes: string[]}+/**+ * Result of the OAuth code exchange WITHOUT persistence. `complete()` (per-asker+ * linking) persists under `state.agentUserId`; admission persists under the+ * canonical identity it derives from `subject` and writes a transport binding.+ * One code path for the crypto (consume + token + deriveSubject), two persistence+ * policies on top.+ */+export interface IdentityExchangeResult {+ /** The consumed single-use link-state (carries team/app/agentUser/redirect). */+ state: LinkState+ /** The fetched access/refresh token, not yet stored. */+ stored: StoredCredential+ /** The proven external subject, if this provider establishes identity. */+ subject?: string+ /** Effective granted scopes (from the token response, else the requested set). */+ scopes: string[]+}++/** Per-request identity proof carried by a transport (e.g. an HTTP bearer the+ * authoritative provider can introspect inline). No OAuth round-trip needed. */+export interface BearerVerification {+ subject: string+ stored: StoredCredential+ scopes: string[]+}+export interface IdentityProvider {readonly id: string/** Broker key tools/MCPs resolve ('posthog_api', 'github', 'dogs', …). Also@@ -60,11 +88,17 @@ export interface IdentityProvider {* seam, `resolve()` throws `agent_binding_not_implemented` until it lands. */readonly binding: 'principal' | 'agent'initiate(input: IdentityInitiateInput): Promise<IdentityInitiateResult>+ /** Exchange the OAuth code but do NOT persist. Used by both `complete()` and+ * the admission engine, which apply different persistence policies. */+ exchange(input: IdentityCompleteInput): Promise<IdentityExchangeResult>complete(input: IdentityCompleteInput): Promise<IdentityCompleteResult>/** Usable credential for a linked principal, refreshed if stale; null if unlinked. */resolve(input: IdentityResolveInput): Promise<Credential | null>/** Hosts the resolved bearer may be sent to (SSRF guard). Empty = none allowed. */allowedHosts(): string[]+ /** Optional: verify a per-request bearer the transport already carries (HTTP),+ * proving identity inline without an OAuth round-trip. Undefined = unsupported. */+ verifyBearer?(token: string): Promise<BearerVerification | null>}export interface IdentityProviderRegistry {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.tsindex c6e0cddcae1c..245a4a6d6c39 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@@ -14,6 +14,7 @@ import type { IdentityLinkStateStore } from './identity-link-state-store'import type {IdentityCompleteInput,IdentityCompleteResult,+ IdentityExchangeResult,IdentityInitiateInput,IdentityInitiateResult,IdentityProvider,@@ -112,7 +113,12 @@ export class Oauth2AuthProvider implements IdentityProvider {return { authorizeUrl: u.toString(), stateId }}- async complete(input: IdentityCompleteInput): Promise<IdentityCompleteResult> {+ /**+ * Exchange the authorization code for a token and derive the subject, but do+ * NOT persist. Both `complete()` (per-asker linking) and the admission engine+ * build on this — they differ only in WHERE the credential lands.+ */+ async exchange(input: IdentityCompleteInput): Promise<IdentityExchangeResult> {if (input.query.error) {throw new Error(`oauth_error: ${input.query.error}`)}@@ -131,27 +137,52 @@ export class Oauth2AuthProvider implements IdentityProvider {redirect_uri: state.redirectUri,code_verifier: state.codeVerifier,})- const subject = await this.deriveSubject(token.access_token)+ return {+ state,+ stored: this.toStored(token),+ // The discoverable subject (for admission/canonical identity), regardless+ // of `establishesIdentity` — which only gates secondary-credential stamping.+ subject: await this.fetchSubject(token.access_token),+ scopes: token.scope ? token.scope.split(' ') : state.scopes,+ }+ }++ async complete(input: IdentityCompleteInput): Promise<IdentityCompleteResult> {+ const { state, stored, subject, scopes } = await this.exchange(input)await this.deps.credentials.put({teamId: state.teamId,applicationId: state.applicationId,agentUserId: state.agentUserId,provider: this.id,- credential: this.toStored(token),- scopes: token.scope ? token.scope.split(' ') : state.scopes,- subject,+ credential: stored,+ scopes,+ // A capability-only link makes no identity claim — stamp a subject only+ // when this provider establishes identity.+ subject: this.establishesIdentity ? subject : undefined,})return { agentUserId: state.agentUserId, provider: this.id }}- /**- * The external subject this link proves, if any. Base provider establishes- * no identity → undefined. An identity-establishing subclass overrides this- * (e.g. PostHog reads /oauth/userinfo `sub`) so `complete()` stamps it on- * the stored credential. Runs once, at link time, with a fresh access token.- */- protected async deriveSubject(_accessToken: string): Promise<string | undefined> {- return undefined+ /** Read the provider's stable subject from userinfo, if configured. Best-effort:+ * a hiccup just yields no subject, never blocks the link. */+ protected async fetchSubject(accessToken: string): Promise<string | undefined> {+ const url = this.deps.config.userinfoUrl+ if (!url) {+ return undefined+ }+ try {+ const res = await this.deps.http.fetch(url, {+ method: 'GET',+ headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },+ })+ if (!res.ok) {+ return undefined+ }+ const json = (await res.json()) as { sub?: string }+ return typeof json.sub === 'string' && json.sub.length > 0 ? json.sub : undefined+ } catch {+ return undefined+ }}async resolve(input: IdentityResolveInput): Promise<Credential | null> {diff --git a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.tsindex 1742af27381f..5d62065589b1 100644--- a/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/posthog-identity-provider.ts@@ -22,6 +22,7 @@ import type { Credential } from './credential-broker'import type {IdentityCompleteInput,IdentityCompleteResult,+ IdentityExchangeResult,IdentityInitiateInput,IdentityInitiateResult,IdentityProvider,@@ -30,6 +31,8 @@ import type {import { Oauth2AuthProvider } from './oauth2-identity-provider'export class PostHogAuthProvider extends Oauth2AuthProvider {+ // Linking proves WHO the principal is; `complete()` stamps the userinfo `sub`+ // (read by the inherited `fetchSubject`) as the credential subject.override readonly establishesIdentity = true// The edge seed (PostHog Code's posthog bearer) and the native `@posthog/*`@@ -37,28 +40,6 @@ export class PostHogAuthProvider extends Oauth2AuthProvider {override get credentialTarget(): string {return 'posthog_api'}-- protected override async deriveSubject(accessToken: string): Promise<string | undefined> {- const url = this.deps.config.userinfoUrl- if (!url) {- return undefined- }- // Best-effort: a userinfo hiccup must not block the link succeeding as a- // capability. Without a subject the credential just isn't identity-bearing.- try {- const res = await this.deps.http.fetch(url, {- method: 'GET',- headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },- })- if (!res.ok) {- return undefined- }- const json = (await res.json()) as { sub?: string }- return typeof json.sub === 'string' && json.sub.length > 0 ? json.sub : undefined- } catch {- return undefined- }- }}/**@@ -92,6 +73,10 @@ export class SeedOnlyPostHogProvider implements IdentityProvider {throw new Error('link_unavailable_no_oauth_app')}+ async exchange(_input: IdentityCompleteInput): Promise<IdentityExchangeResult> {+ throw new Error('link_unavailable_no_oauth_app')+ }+async complete(_input: IdentityCompleteInput): Promise<IdentityCompleteResult> {throw new Error('link_unavailable_no_oauth_app')}diff --git a/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.test.ts b/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.test.tsnew file mode 100644index 000000000000..7abc30ef3890--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.test.ts@@ -0,0 +1,136 @@+/**+ * Real-PG tests for the transport→canonical-identity binding store. The+ * (application, transport) uniqueness + idempotent re-bind is what makes "auth+ * once, every future turn resolves the same identity" durable, so it's proven+ * against Postgres, not a mock. The in-memory impl is exercised via admission.test.ts.+ */++import { randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'++import { isReachable, reset } from '@posthog/agent-shared/testing'++import { PgTransportBindingStore } from './transport-binding-store'++const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'++const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe++maybeDescribe('PgTransportBindingStore (real PG)', () => {+ let pool: Pool+ let reachable = false+ let store: PgTransportBindingStore+ const APP = randomUUID()++ beforeAll(async () => {+ reachable = await isReachable(TEST_DB_URL)+ if (!reachable) {+ return+ }+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })+ store = new PgTransportBindingStore(pool)+ })++ beforeEach(async () => {+ if (reachable) {+ await reset({ databaseUrl: TEST_DB_URL })+ }+ })++ afterAll(async () => {+ await pool?.end().catch(() => undefined)+ })++ it('binds, finds, and is null before binding', async () => {+ if (!reachable) {+ return+ }+ const transport = randomUUID()+ const canonical = randomUUID()+ expect(await store.find(APP, transport)).toBeNull()++ const bound = await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: transport,+ canonicalAgentUserId: canonical,+ provider: 'work',+ })+ expect(bound.canonicalAgentUserId).toBe(canonical)++ const found = await store.find(APP, transport)+ expect(found?.canonicalAgentUserId).toBe(canonical)+ expect(found?.provider).toBe('work')+ })++ it('re-binding the same transport replaces the canonical id, keeps created_at', async () => {+ if (!reachable) {+ return+ }+ const transport = randomUUID()+ const first = await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: transport,+ canonicalAgentUserId: randomUUID(),+ provider: 'work',+ })+ const newCanonical = randomUUID()+ const second = await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: transport,+ canonicalAgentUserId: newCanonical,+ provider: 'work',+ })+ expect(second.canonicalAgentUserId).toBe(newCanonical)+ expect(second.createdAt).toBe(first.createdAt) // idempotent upsert preserves created_at+ // Still exactly one row for this transport.+ const all = await store.listForCanonical(APP, newCanonical)+ expect(all).toHaveLength(1)+ })++ it('lists many transports for one canonical identity (one identity, many transports)', async () => {+ if (!reachable) {+ return+ }+ const canonical = randomUUID()+ const slack = randomUUID()+ const discord = randomUUID()+ await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: slack,+ canonicalAgentUserId: canonical,+ provider: 'work',+ })+ await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: discord,+ canonicalAgentUserId: canonical,+ provider: 'work',+ })++ const all = await store.listForCanonical(APP, canonical)+ expect(all.map((b) => b.transportAgentUserId).sort()).toEqual([slack, discord].sort())+ })++ it('unbind removes the binding (unlink)', async () => {+ if (!reachable) {+ return+ }+ const transport = randomUUID()+ await store.bind({+ teamId: 1,+ applicationId: APP,+ transportAgentUserId: transport,+ canonicalAgentUserId: randomUUID(),+ provider: 'work',+ })+ await store.unbind(APP, transport)+ expect(await store.find(APP, transport)).toBeNull()+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.ts b/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.tsnew file mode 100644index 000000000000..a8320144e0a7--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/transport-binding-store.ts@@ -0,0 +1,157 @@+/**+ * Durable transport→canonical-identity bindings. A binding records "this+ * transport principal (Slack T01:U01) authenticated as this canonical identity+ * (the authoritative provider's subject)". One canonical identity can have many+ * bindings (same person via Slack + Discord); unlink = delete a binding.+ *+ * Backed by `agent_transport_binding`.+ */++import { randomUUID } from 'node:crypto'+import type { Pool } from 'pg'++export interface TransportBinding {+ id: string+ teamId: number+ applicationId: string+ /** Transport AgentUser (principal_kind=transport, principal_id=subjectId). */+ transportAgentUserId: string+ /** Canonical identity AgentUser (principal_kind=identity:<provider>, id=subject). */+ canonicalAgentUserId: string+ /** Authoritative provider that established the binding. */+ provider: string+ createdAt: string+}++export interface BindInput {+ teamId: number+ applicationId: string+ transportAgentUserId: string+ canonicalAgentUserId: string+ provider: string+}++export interface TransportBindingStore {+ /** Resolve a transport principal to its canonical identity, if bound. */+ find(applicationId: string, transportAgentUserId: string): Promise<TransportBinding | null>+ /** Create/replace the binding for a transport principal (idempotent on+ * (application, transportAgentUserId)). */+ bind(input: BindInput): Promise<TransportBinding>+ /** Remove a transport principal's binding (unlink). */+ unbind(applicationId: string, transportAgentUserId: string): Promise<void>+ /** All bindings for a canonical identity (audit / cascade unlink). */+ listForCanonical(applicationId: string, canonicalAgentUserId: string): Promise<TransportBinding[]>+}++/** In-memory store for tests and module-level integration. */+export class MemoryTransportBindingStore implements TransportBindingStore {+ private readonly byKey = new Map<string, TransportBinding>()++ private key(applicationId: string, transportAgentUserId: string): string {+ return `${applicationId}:${transportAgentUserId}`+ }++ async find(applicationId: string, transportAgentUserId: string): Promise<TransportBinding | null> {+ return this.byKey.get(this.key(applicationId, transportAgentUserId)) ?? null+ }++ async bind(input: BindInput): Promise<TransportBinding> {+ const k = this.key(input.applicationId, input.transportAgentUserId)+ const existing = this.byKey.get(k)+ const binding: TransportBinding = {+ id: existing?.id ?? randomUUID(),+ teamId: input.teamId,+ applicationId: input.applicationId,+ transportAgentUserId: input.transportAgentUserId,+ canonicalAgentUserId: input.canonicalAgentUserId,+ provider: input.provider,+ createdAt: existing?.createdAt ?? new Date(Date.now()).toISOString(),+ }+ this.byKey.set(k, binding)+ return binding+ }++ async unbind(applicationId: string, transportAgentUserId: string): Promise<void> {+ this.byKey.delete(this.key(applicationId, transportAgentUserId))+ }++ async listForCanonical(applicationId: string, canonicalAgentUserId: string): Promise<TransportBinding[]> {+ return [...this.byKey.values()].filter(+ (b) => b.applicationId === applicationId && b.canonicalAgentUserId === canonicalAgentUserId+ )+ }+}++interface BindingRow {+ id: string+ team_id: string | number+ application_id: string+ transport_agent_user_id: string+ canonical_agent_user_id: string+ provider: string+ created_at: string | Date+}++const SELECT_COLS = `id, team_id, application_id, transport_agent_user_id, canonical_agent_user_id, provider, created_at`++const toBinding = (r: BindingRow): TransportBinding => ({+ id: r.id,+ teamId: Number(r.team_id),+ applicationId: r.application_id,+ transportAgentUserId: r.transport_agent_user_id,+ canonicalAgentUserId: r.canonical_agent_user_id,+ provider: r.provider,+ createdAt: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,+})++export class PgTransportBindingStore implements TransportBindingStore {+ constructor(private readonly pool: Pool) {}++ async find(applicationId: string, transportAgentUserId: string): Promise<TransportBinding | null> {+ const r = await this.pool.query<BindingRow>(+ `SELECT ${SELECT_COLS} FROM agent_transport_binding+ WHERE application_id = $1 AND transport_agent_user_id = $2`,+ [applicationId, transportAgentUserId]+ )+ return r.rowCount === 0 ? null : toBinding(r.rows[0])+ }++ async bind(input: BindInput): Promise<TransportBinding> {+ // Re-auth as a different identity replaces the binding; created_at is kept.+ const r = await this.pool.query<BindingRow>(+ `INSERT INTO agent_transport_binding+ (id, team_id, application_id, transport_agent_user_id, canonical_agent_user_id, provider, created_at)+ VALUES ($1, $2, $3, $4, $5, $6, NOW())+ ON CONFLICT (application_id, transport_agent_user_id)+ DO UPDATE SET canonical_agent_user_id = EXCLUDED.canonical_agent_user_id,+ provider = EXCLUDED.provider+ RETURNING ${SELECT_COLS}`,+ [+ randomUUID(),+ input.teamId,+ input.applicationId,+ input.transportAgentUserId,+ input.canonicalAgentUserId,+ input.provider,+ ]+ )+ return toBinding(r.rows[0])+ }++ async unbind(applicationId: string, transportAgentUserId: string): Promise<void> {+ await this.pool.query(+ `DELETE FROM agent_transport_binding WHERE application_id = $1 AND transport_agent_user_id = $2`,+ [applicationId, transportAgentUserId]+ )+ }++ async listForCanonical(applicationId: string, canonicalAgentUserId: string): Promise<TransportBinding[]> {+ const r = await this.pool.query<BindingRow>(+ `SELECT ${SELECT_COLS} FROM agent_transport_binding+ WHERE application_id = $1 AND canonical_agent_user_id = $2+ ORDER BY created_at`,+ [applicationId, canonicalAgentUserId]+ )+ return r.rows.map(toBinding)+ }+}diff --git a/products/agent_platform/services/agent-shared/src/runtime/transport.ts b/products/agent_platform/services/agent-shared/src/runtime/transport.tsnew file mode 100644index 000000000000..27d69b72a916--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/transport.ts@@ -0,0 +1,66 @@+/**+ * Transport / admission types. A transport (Slack, Discord, HTTP, …) proves its+ * own authenticity and emits a `TransportClaim` — who the sender is *per that+ * transport*. That claim is NOT an authorising identity: the agent's+ * authoritative provider decides, via `AdmissionService`, whether it's enough to+ * run, must be upgraded with a link, or carries a verifiable per-request bearer.+ */++/** What a transport asserts about an inbound request. */+export interface TransportClaim {+ /** Stable transport id ('slack' | 'discord' | 'http' | …); also the+ * `principal_kind` of the transport AgentUser. */+ transport: string+ /** Stable per-transport sender id (the transport AgentUser `principal_id`),+ * e.g. 'T01:U01' for Slack, the JWT `sub` for http-jwt. */+ subjectId: string+ /** A per-request credential the transport already carries (HTTP bearer / JWT)+ * that the authoritative provider MAY verify inline to admit without a link. */+ bearer?: { token: string }+ /** Attributes the transport vouches for (display name, email hint). Advisory+ * only — never an authorisation input. Stored as AgentUser metadata. */+ attributes?: Record<string, unknown>+}++/** A verified, authoritative identity — the source of truth for "who is this". */+export interface VerifiedIdentity {+ /** Authoritative provider id that proved this. */+ provider: string+ /** The provider's stable subject (PostHog user uuid, Google sub, …). */+ subject: string+ /** Our canonical identity row id (an AgentUser keyed on provider+subject). */+ canonicalId: string+ /** The transport AgentUser bound to the canonical identity (per-message sender). */+ transportAgentUserId: string+}++/** A link to send a user so they can authenticate with the authoritative provider. */+export interface AuthBlock {+ provider: string+ authorizeUrl: string+}++export type AdmissionResult =+ /** No authoritative provider — the transport claim IS the identity (public /+ * passthrough agents, today's behaviour). */+ | { kind: 'passthrough'; transportAgentUserId: string }+ /** Verified — safe to enqueue a session. */+ | { kind: 'admitted'; identity: VerifiedIdentity }+ /** Not yet authenticated — deliver this block and do NOT enqueue. */+ | ({ kind: 'auth_required' } & AuthBlock)+ /** Provider/config error — fail closed (do NOT enqueue). */+ | { kind: 'error'; reason: string }++/**+ * A generic entrypoint. Extracts a claim from a raw inbound request and delivers+ * an auth block back over its own channel. Implemented per host in the ingress+ * (Slack ephemeral/DM, HTTP response body, …); the admission engine itself is+ * transport-agnostic.+ */+export interface Transport<TRequest = unknown> {+ readonly id: string+ /** Extract the claim, or null if the request isn't a valid invocation. */+ claim(req: TRequest): TransportClaim | null+ /** Deliver an auth block privately to the claimant over this transport. */+ deliverAuthBlock(req: TRequest, block: AuthBlock): Promise<void>+}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.tsindex f406eb78a44c..b07db0fbd323 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@@ -914,6 +914,44 @@ describe('AgentSpecSchema', () => {})})+ describe('principalsMatch — slack', () => {+ type S = { kind: 'slack'; workspace_id: string; slack_user_id: string; canonical_agent_user_id?: string }+ it.each<[string, S, S, boolean]>([+ [+ 'same workspace + user with no canonical on either side matches (passthrough)',+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U' },+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U' },+ true,+ ],+ [+ 'same workspace + user + same canonical matches',+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C1' },+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C1' },+ true,+ ],+ [+ 'same workspace + user but different canonical does NOT match (rebound identity)',+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C1' },+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C2' },+ false,+ ],+ [+ 'stored has canonical, incoming does not (admission model changed) does NOT match',+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C1' },+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U' },+ false,+ ],+ [+ 'incoming has canonical, stored does not (admission newly enabled) does NOT match',+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U' },+ { kind: 'slack', workspace_id: 'T', slack_user_id: 'U', canonical_agent_user_id: 'C1' },+ 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]>([diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex 88a37c607e00..d6020c9c81e4 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -976,7 +976,14 @@ export const IdentityProviderConfigSchema = z.discriminatedUnion('kind', [])export type IdentityProviderConfig = z.infer<typeof IdentityProviderConfigSchema>-export const AgentSpecSchema = z.object({+/**+ * Base object shape, before the cross-field superRefine. Exported so the+ * author-facing `TypedSpecSchema` (storage/typed-bundle.ts) can guard its key+ * set against this single source of truth — a top-level field added here that+ * the author slice doesn't pass through would be strict-rejected by the+ * authoring API. The parity test in typed-bundle.test.ts enforces that.+ */+export const AgentSpecObjectSchema = z.object({/** Model selection: auto level (default) or manual priority list. Resolve via `modelPolicyToList`. */models: ModelPolicySchema.default({ mode: 'auto', level: 'medium', optimize_for: 'cost' }),triggers: z@@ -1009,6 +1016,23 @@ export const AgentSpecSchema = z.object({'Identity providers users can link against so the agent can act AS the user (the credential axis). kind posthog = managed (provisioned on promote), oauth2 = bring-your-own third-party app.').default([]),+ /**+ * The ONE provider that gates admission and is the source-of-truth identity.+ * Must reference an `identity_providers[]` entry that establishes identity.+ * When set, every inbound request (regardless of transport) must resolve a+ * verified identity from this provider before a session runs — the ingress+ * either finds a durable transport→identity binding, verifies a per-request+ * credential, or returns an auth block. When unset, the transport claim is+ * the identity (passthrough / public agents). All OTHER identity_providers+ * link as secondary credentials to the authoritative (canonical) identity.+ */+ authoritative_provider: z+ .string()+ .min(1)+ .describe(+ 'The ONE identity_providers[] id that gates admission and is the canonical identity. When set, every inbound request must resolve a verified identity from it before a session runs (transport-independent). Unset = transport claim is the identity (passthrough/public).'+ )+ .optional(),secrets: z.array(SecretRefSchema).describe(@@ -1034,6 +1058,54 @@ export const AgentSpecSchema = z.object({).optional(),})+/**+ * Trigger types whose ingress path calls `buildAdmission()` before enqueueing.+ * Add a type here only once its handler resolves the authoritative identity —+ * 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']++export const AgentSpecSchema = AgentSpecObjectSchema.superRefine((spec, ctx) => {+ // authoritative_provider must reference an identity_providers[] entry that can+ // prove a subject (posthog, or oauth2 with userinfo_url) — else admission+ // either 500s (unknown) or soft-locks (no subject) at runtime.+ if (!spec.authoritative_provider) {+ return+ }+ const provider = spec.identity_providers.find((p) => p.id === spec.authoritative_provider)+ if (!provider) {+ ctx.addIssue({+ code: 'custom',+ path: ['authoritative_provider'],+ message: `authoritative_provider "${spec.authoritative_provider}" must reference an identity_providers[] id`,+ })+ return+ }+ const establishesIdentity = provider.kind === 'posthog' || (provider.kind === 'oauth2' && !!provider.userinfo_url)+ if (!establishesIdentity) {+ ctx.addIssue({+ code: 'custom',+ path: ['authoritative_provider'],+ message: `authoritative_provider "${spec.authoritative_provider}" must establish identity (kind posthog, or oauth2 with userinfo_url)`,+ })+ }+ // Fail-closed: refuse specs that combine an authoritative provider with a+ // trigger whose ingress path does not yet call admission. Otherwise those+ // triggers would enqueue sessions using the transport claim as the identity+ // and bypass the gate. Loosen this as each trigger's ingress wires+ // `buildAdmission()`.+ const unsupported = spec.triggers.filter((t) => !ADMISSION_WIRED_TRIGGER_TYPES.includes(t.type))+ if (unsupported.length > 0) {+ const types = [...new Set(unsupported.map((t) => t.type))].sort().join(', ')+ ctx.addIssue({+ code: 'custom',+ path: ['authoritative_provider'],+ message: `authoritative_provider is not yet enforced on trigger types: ${types}. Supported: ${ADMISSION_WIRED_TRIGGER_TYPES.join(', ')}.`,+ })+ }+})+export type AgentSpec = z.infer<typeof AgentSpecSchema>export type ModelEntry = z.infer<typeof ModelEntrySchema>export type ModelLevel = z.infer<typeof ModelLevelSchema>@@ -1147,11 +1219,24 @@ export function principalsMatch(stored: SessionPrincipal | null, incoming: Sessicase 'jwt':return incoming.kind === 'jwt' && stored.sub === incoming.subcase 'slack':- return (- incoming.kind === 'slack' &&- stored.workspace_id === incoming.workspace_id &&- stored.slack_user_id === incoming.slack_user_id- )+ if (+ incoming.kind !== 'slack' ||+ stored.workspace_id !== incoming.workspace_id ||+ stored.slack_user_id !== incoming.slack_user_id+ ) {+ 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 truecase 'posthog_internal':return incoming.kind === 'posthog_internal' && stored.team_id === incoming.team_idcase 'shared_secret':@@ -1259,6 +1344,9 @@ export type SessionPrincipal =workspace_id: stringslack_user_id: stringagent_user_id?: string+ /** Canonical identity (authoritative provider) set by edge admission;+ * keys secondary links when present. Absent on passthrough. */+ canonical_agent_user_id?: string}/** Internal / service-to-service caller (PostHog backend → ingress). */| { kind: 'posthog_internal'; team_id?: number }diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.tsindex 078cac55aa5e..88f0f043cfaa 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { AgentSpecSchema } from '../spec/spec'+import { AgentSpecObjectSchema } from '../spec/spec'import { deriveSkillDescription, TypedSpecSchema } from './typed-bundle'describe('deriveSkillDescription', () => {@@ -38,21 +38,22 @@ describe('TypedSpecSchema ↔ AgentSpec key parity', () => {// superset) catches drift in both directions:// - a new canonical field with no author passthrough → PUT /spec strict-// rejects it with "Unrecognized key" and the runtime never sees a valid- // spec;+ // spec (the failure `authoritative_provider` hit);// - a stray author-only key with no canonical counterpart → dead cruft// that freeze silently strips anyway (the `auth` field that used to be// here).const SERVER_DERIVED = new Set(['skills', 'tools'])it('carries exactly the canonical author-facing top-level fields', () => {- const canonicalAuthorKeys = Object.keys(AgentSpecSchema.shape)+ const canonicalAuthorKeys = Object.keys(AgentSpecObjectSchema.shape).filter((k) => !SERVER_DERIVED.has(k)).sort()const authorKeys = Object.keys(TypedSpecSchema.shape).sort()expect(authorKeys).toEqual(canonicalAuthorKeys)})- it('still rejects unknown keys', () => {+ it('accepts authoritative_provider and still rejects unknown keys', () => {+ expect(TypedSpecSchema.safeParse({ authoritative_provider: 'posthog' }).success).toBe(true)expect(TypedSpecSchema.safeParse({ not_a_real_field: 1 }).success).toBe(false)})})diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.tsindex f1a80c7d47f7..6a8fd90b4448 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts@@ -135,6 +135,7 @@ export const TypedSpecSchema = ztriggers: z.array(z.unknown()).optional(),mcps: z.array(z.unknown()).optional(),identity_providers: z.array(z.unknown()).optional(),+ authoritative_provider: z.string().optional(),// The canonical secret shape: a bare key string OR a host-scoped// `{ name, allowed_hosts }` object. Reuse `SecretRefSchema` (the single// source of truth) rather than re-spelling it — the old string-onlydiff --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.tsnew file mode 100644index 000000000000..bf18a4387ca3--- /dev/null+++ b/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts@@ -0,0 +1,214 @@+/**+ * Full hermetic e2e of EDGE ADMISSION through the real ingress + worker + PG ++ * the real `dogs` IdP; only the model is scripted.+ *+ * An agent declares `authoritative_provider: dogs`. A Slack user mentions it:+ * 1. unbound → the ingress returns auth_required and runs NO session+ * 2. the user completes OAuth (browser → /link/dogs/callback → admission writes+ * a canonical identity + transport binding)+ * 3. next mention → admitted → the agent actually runs and replies+ *+ * Plus a passthrough agent (no authoritative_provider) that runs immediately,+ * proving backward-compatibility through the same path.+ */++import request from 'supertest'+import { afterEach, beforeAll, describe, expect, it } from 'vitest'++import { canonicalKind, HttpClient, PgTransportBindingStore } from '@posthog/agent-shared'++import { buildCluster, Cluster, fauxText } from '../harness'+import { DogServer, startDogServer } from '../harness/dog-oauth-server'++const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'+const SLACK_SECRET = 'test-slack-secret'+const SLACK_ENV = { SLACK_SIGNING_SECRET: SLACK_SECRET, SLACK_BOT_TOKEN: 'xoxb-test' }++async function reachable(): Promise<boolean> {+ const { Pool } = await import('pg')+ const probe = new Pool({ connectionString: TEST_DB_URL, max: 1 })+ try {+ await probe.query('SELECT 1')+ return true+ } catch {+ return false+ } finally {+ await probe.end().catch(() => undefined)+ }+}++// Swallow slack.com (the auth-link DM); pass the dog IdP/API through for real.+function recorderHttp(): { fetch: HttpClient['fetch'] } {+ const real = new HttpClient()+ return {+ fetch: (input, init) => {+ const url = typeof input === 'string' ? input : input.toString()+ if (url.includes('slack.com/api/')) {+ return Promise.resolve(new Response(JSON.stringify({ ok: true, ts: '1.0' }), { status: 200 }))+ }+ return real.fetch(input, init)+ },+ }+}++function slackMention(opts: { text: string; ts: string; thread_ts?: string; user?: string }): Record<string, unknown> {+ return {+ type: 'event_callback',+ event_id: `Ev_${opts.ts}`,+ team_id: 'T_DOGS',+ event: {+ type: 'app_mention',+ channel: 'C01',+ user: opts.user ?? 'U_ALICE',+ text: opts.text,+ ts: opts.ts,+ thread_ts: opts.thread_ts,+ team: 'T_DOGS',+ },+ }+}++function assistantText(conversation: unknown[]): string {+ const parts: string[] = []+ for (const m of conversation as Array<{ role?: string; content?: unknown }>) {+ if (m.role !== 'assistant') {+ continue+ }+ if (typeof m.content === 'string') {+ parts.push(m.content)+ } else if (Array.isArray(m.content)) {+ for (const b of m.content as Array<{ type?: string; text?: string }>) {+ if (b.type === 'text' && b.text) {+ parts.push(b.text)+ }+ }+ }+ }+ return parts.join('\n')+}++const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe++maybeDescribe('edge admission e2e (Slack, 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)+ })++ // 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+ }+ dog = await startDogServer({ userSub: 'alice-canonical' })+ c = await buildCluster({ http: recorderHttp() })+ await c.deployAgent({+ slug: 'gatedbot',+ spec: {+ triggers: [{ type: 'slack', config: { trusted_workspaces: '*' } }],+ authoritative_provider: 'dogs',+ identity_providers: [+ {+ kind: 'oauth2',+ id: 'dogs',+ authorize_url: dog.authorizeUrl,+ token_url: dog.tokenUrl,+ userinfo_url: dog.userinfoUrl, // lets dogs prove a subject+ client_id: 'dogs-client',+ scopes: ['read:dog'],+ },+ ],+ },+ encrypted_env: SLACK_ENV,+ })++ // Turn 1: unbound → auth_required, NO session enqueued.+ c.setScript([fauxText('should not run yet')])+ const first = await c.slackPost(+ 'gatedbot',+ 'events',+ slackMention({ text: '<@U0BOT> hi', ts: '100.0' }),+ SLACK_SECRET+ )+ expect(first.body.auth_required).toBe(true)+ expect(first.body.provider).toBe('dogs')+ expect(first.body.session_id).toBeUndefined()+ const authorizeUrl = first.body.authorize_url as string+ expect(authorizeUrl).toContain(dog.baseUrl)+ await c.drain() // nothing queued; a no-op++ // Complete the link → admission writes the binding + canonical identity.+ await completeLink(authorizeUrl)+ const bindings = new PgTransportBindingStore(c.pool)++ // Turn 2: same user → admitted → the agent actually runs and replies.+ c.setScript([fauxText('woof, how can I help?')])+ const second = await c.slackPost(+ 'gatedbot',+ 'events',+ slackMention({ text: '<@U0BOT> still there?', ts: '101.0', thread_ts: '100.0' }),+ SLACK_SECRET+ )+ expect(second.body.auth_required).toBeUndefined()+ expect(second.body.session_id).toBeTruthy()+ await c.drain()++ const s2 = await c.queue.get(second.body.session_id)+ expect(s2).toBeTruthy()+ expect(assistantText(s2!.conversation)).toContain('woof')++ // A transport binding now exists for this app/canonical identity.+ const cano = await c.identities.find({+ application_id: s2!.application_id,+ principal_kind: canonicalKind('dogs'),+ principal_id: 'alice-canonical',+ })+ expect(cano).toBeTruthy()+ const all = await bindings.listForCanonical(s2!.application_id, cano!.id)+ expect(all.length).toBeGreaterThanOrEqual(1)+ })++ it('passthrough: no authoritative_provider → the agent runs immediately', async () => {+ if (!ok) {+ return+ }+ dog = await startDogServer()+ c = await buildCluster({ http: recorderHttp() })+ await c.deployAgent({+ slug: 'openbot',+ spec: { triggers: [{ type: 'slack', config: { trusted_workspaces: '*' } }] },+ encrypted_env: SLACK_ENV,+ })+ c.setScript([fauxText('hello right away')])+ const res = await c.slackPost(+ 'openbot',+ 'events',+ slackMention({ text: '<@U0BOT> hi', ts: '200.0' }),+ SLACK_SECRET+ )+ expect(res.body.auth_required).toBeUndefined()+ expect(res.body.session_id).toBeTruthy()+ await c.drain()+ const s = await c.queue.get(res.body.session_id)+ expect(assistantText(s!.conversation)).toContain('hello right away')+ })+})diff --git a/products/agent_platform/services/agent-tests/src/cases/admission-e2e.test.ts b/products/agent_platform/services/agent-tests/src/cases/admission-e2e.test.tsnew file mode 100644index 000000000000..f618eb7bdb2a--- /dev/null+++ b/products/agent_platform/services/agent-tests/src/cases/admission-e2e.test.ts@@ -0,0 +1,228 @@+/**+ * Admission e2e — the authoritative-provider model end to end against REAL+ * Postgres + the REAL `dogs` OAuth server. Proves the rebuilt identity arc with+ * actual durable bindings, canonical identities, and credentials in the DB:+ *+ * Slack claim → auth_required → real /authorize → complete → binding + canonical+ * identity + authoritative credential persisted → re-resolve is admitted+ * (durable) → a Discord claim for the SAME person binds to the SAME canonical+ * identity → the authoritative credential actually calls the protected API.+ *+ * No Express/queue: this exercises the AdmissionService + PG stores + a real IdP,+ * which is the architecture the ingress edge will call. Wiring the ingress routes+ * onto this is the next step.+ */++import { randomUUID } from 'node:crypto'+import { Pool } from 'pg'+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'++import {+ AdmissionService,+ canonicalKind,+ HttpClient,+ MapIdentityProviderRegistry,+ Oauth2AuthProvider,+ PgIdentityCredentialStore,+ PgIdentityLinkStateStore,+ PgIdentityStore,+ PgTransportBindingStore,+} from '@posthog/agent-shared'+import type { AgentApplication, AgentRevision, AgentSpec, TransportClaim } from '@posthog/agent-shared'+import { isReachable, reset } from '@posthog/agent-shared/testing'++import { DogServer, startDogServer } from '../harness/dog-oauth-server'++const TEST_DB_URL =+ process.env.AGENT_TEST_DB_URL ?? 'postgres://posthog:posthog@localhost:5432/agent_runtime_queue_test'+const KEY = '01234567890123456789012345678901'+const REDIRECT = (p: string): string => `http://callback.test/link/${p}/callback`++const maybeDescribe = process.env.SKIP_PG_TESTS === '1' ? describe.skip : describe++maybeDescribe('Admission e2e (authoritative provider × dogs IdP × real PG)', () => {+ let pool: Pool+ let reachable = false+ let dog: DogServer++ beforeAll(async () => {+ reachable = await isReachable(TEST_DB_URL)+ if (reachable) {+ pool = new Pool({ connectionString: TEST_DB_URL, max: 4 })+ }+ })++ beforeEach(async () => {+ if (reachable) {+ await reset({ databaseUrl: TEST_DB_URL })+ }+ })++ afterAll(async () => {+ await pool?.end().catch(() => undefined)+ })++ // ---- harness wiring: real PG stores + real Oauth2 provider for `dogs` ----++ function build(): {+ admission: AdmissionService+ identities: PgIdentityStore+ bindings: PgTransportBindingStore+ credentials: PgIdentityCredentialStore+ provider: Oauth2AuthProvider+ } {+ const links = new PgIdentityLinkStateStore(pool)+ const credentials = new PgIdentityCredentialStore(pool, { encryptionSaltKeys: KEY })+ const identities = new PgIdentityStore(pool)+ const bindings = new PgTransportBindingStore(pool)+ const provider = new Oauth2AuthProvider({+ config: {+ id: 'dogs',+ authorizeUrl: dog.authorizeUrl,+ tokenUrl: dog.tokenUrl,+ userinfoUrl: dog.userinfoUrl, // lets the provider derive a subject+ clientId: 'dogs-client',+ scopes: ['read:dog'],+ },+ links,+ credentials,+ http: new HttpClient({}),+ })+ const admission = new AdmissionService({+ registry: new MapIdentityProviderRegistry([provider]),+ identities,+ bindings,+ credentials,+ redirectUriFor: REDIRECT,+ })+ return { admission, identities, bindings, credentials, provider }+ }++ const APP = (): AgentApplication => ({+ id: randomUUID(),+ team_id: 1,+ slug: 'bot',+ name: 'Bot',+ description: '',+ live_revision_id: null,+ archived: false,+ })++ const revFor = (app: AgentApplication, authoritative?: string): AgentRevision => ({+ id: randomUUID(),+ application_id: app.id,+ parent_revision_id: null,+ created_by_id: null,+ created_at: '2026-01-01T00:00:00Z',+ state: 'live',+ bundle_uri: 's3://x',+ bundle_sha256: null,+ spec: { authoritative_provider: authoritative } as AgentSpec,+ encrypted_env: null,+ })++ // Simulate the browser leg: visit /authorize, capture ?code&state.+ async function visitAuthorize(authorizeUrl: string): Promise<{ code: string; state: string }> {+ const res = await fetch(authorizeUrl, { redirect: 'manual' })+ expect(res.status).toBe(302)+ const loc = new URL(res.headers.get('location') ?? '')+ return { code: loc.searchParams.get('code') ?? '', state: loc.searchParams.get('state') ?? '' }+ }++ it('full arc: Slack unbound → link → durable admit; Discord binds to the SAME identity; cred calls the API', async () => {+ if (!reachable) {+ return+ }+ dog = await startDogServer({ userSub: 'employee-7' })+ try {+ const { admission, identities, bindings, credentials, provider } = build()+ const app = APP()+ const rev = revFor(app, 'dogs')+ const slack: TransportClaim = { transport: 'slack', subjectId: 'T01:U01' }++ // 1. First contact: not authenticated → auth_required.+ const first = await admission.resolve(slack, { application: app, revision: rev })+ expect(first.kind).toBe('auth_required')+ if (first.kind !== 'auth_required') {+ return+ }+ expect(first.provider).toBe('dogs')+ expect(first.authorizeUrl).toContain(dog.baseUrl)++ // 2. Browser authenticates; callback completes the link.+ const { code, state } = await visitAuthorize(first.authorizeUrl)+ const verified = await admission.complete('dogs', state, { code })+ expect(verified.subject).toBe('employee-7')++ // 3. Persistence: canonical identity, binding, authoritative credential.+ const canonical = await identities.find({+ application_id: app.id,+ principal_kind: canonicalKind('dogs'),+ principal_id: 'employee-7',+ })+ expect(canonical?.id).toBe(verified.canonicalId)+ const binding = await bindings.find(app.id, verified.transportAgentUserId)+ expect(binding?.canonicalAgentUserId).toBe(verified.canonicalId)+ const stored = await credentials.get(verified.canonicalId, 'dogs')+ expect(stored).not.toBeNull()++ // 4. Next turn: durable binding admits with no link.+ const second = await admission.resolve(slack, { application: app, revision: rev })+ expect(second.kind).toBe('admitted')+ if (second.kind === 'admitted') {+ expect(second.identity.canonicalId).toBe(verified.canonicalId)+ }++ // 5. Same person via Discord → auth_required, then SAME canonical identity.+ const discord: TransportClaim = { transport: 'discord', subjectId: 'G:UD' }+ const dFirst = await admission.resolve(discord, { application: app, revision: rev })+ expect(dFirst.kind).toBe('auth_required')+ if (dFirst.kind !== 'auth_required') {+ return+ }+ const dAuth = await visitAuthorize(dFirst.authorizeUrl)+ const dVerified = await admission.complete('dogs', dAuth.state, { code: dAuth.code })+ expect(dVerified.canonicalId).toBe(verified.canonicalId) // one identity, two transports+ expect(dVerified.transportAgentUserId).not.toBe(verified.transportAgentUserId)++ const allBindings = await bindings.listForCanonical(app.id, verified.canonicalId)+ expect(allBindings).toHaveLength(2)++ // 6. The payoff: the authoritative credential actually works against the API.+ const cred = await provider.resolve({+ agentUserId: verified.canonicalId,+ teamId: 1,+ applicationId: app.id,+ scopes: [],+ })+ const token = cred?.kind === 'oauth_bearer' ? cred.token : ''+ const api = await fetch(dog.apiUrl, { headers: { Authorization: `Bearer ${token}` } })+ expect(api.status).toBe(200)+ expect((await api.json()) as { breed: string }).toMatchObject({ breed: 'corgi' })+ } finally {+ await dog.close()+ }+ })++ it('passthrough: no authoritative provider → transport claim is the identity (no link)', async () => {+ if (!reachable) {+ return+ }+ dog = await startDogServer()+ try {+ const { admission, identities } = build()+ const app = APP()+ const res = await admission.resolve(+ { transport: 'slack', subjectId: 'T:U' },+ { application: app, revision: revFor(app, undefined) }+ )+ expect(res.kind).toBe('passthrough')+ if (res.kind === 'passthrough') {+ const u = await identities.getById(res.transportAgentUserId)+ expect(u?.principal_kind).toBe('slack')+ }+ } finally {+ await dog.close()+ }+ })+})diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.tsindex 96aed6be444a..592e869fde8e 100644--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts@@ -48,6 +48,7 @@ import {PgIdentityCredentialStore,PgIdentityLinkStateStore,PgIdentityStore,+ PgTransportBindingStore,PgRevisionStore,PgSandboxInstanceStore,PgSessionQueue,@@ -463,11 +464,14 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster// Identity-linking callback route (`GET /link/:provider/callback`).identityCredentials,identityLinks,+ // Edge admission: durable transport→canonical bindings.+ transportBindings: new PgTransportBindingStore(pool),+ posthogApiBaseUrl: 'http://localhost:8010',envEncryption: encryption,// Same `http` the worker uses, so tests asserting on outbound// slack.com calls from the ingress (ack_reaction, identity bridge)// can route them through a single recorder.- http: opts.http,+ http: harnessHttp,// Wire the JWT gate so preview-mode tests exercise the real claim// verification (audience, signature, app/rev binding). Without this the// resolver short-circuits and a non-live revision routes without a