Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(agent-platform): land oauth link callback on the agent's own host (#71535)

Ben Whited6f3dafe5294
diff --git a/products/agent_platform/backend/logic/posthog_identity_app.py b/products/agent_platform/backend/logic/posthog_identity_app.py
index 0938e11ba562..cbcb9a0f4ba7 100644
--- a/products/agent_platform/backend/logic/posthog_identity_app.py
+++ b/products/agent_platform/backend/logic/posthog_identity_app.py
@@ -17,6 +17,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
import structlog
@@ -29,13 +30,30 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
-# Fallback when AGENT_INGRESS_PUBLIC_URL is unset — matches the runner's
-# linkRedirectBaseUrl default so the registered redirect URI lines up.
-_DEFAULT_INGRESS_BASE = "https://agents.posthog.com"
+def build_link_callback_url(slug: str, provider_id: str) -> str | None:
+ """OAuth link callback URL for an agent + provider, matching what the deployed
+ ingress serves in each routing mode.
-def _ingress_base() -> str:
- return (settings.AGENT_INGRESS_PUBLIC_URL or _DEFAULT_INGRESS_BASE).rstrip("/")
+ MIRROR of ``buildLinkCallbackUrl`` in
+ services/agent-shared/src/runtime/link-callback-url.ts — the two MUST produce
+ byte-identical strings: this is registered as the OAuthApplication
+ ``redirect_uri`` here, the runner sends the same value at authorize time, and
+ the IdP rejects the exchange on any mismatch.
+
+ domain -> ``https://<slug><suffix>/link/<provider>/callback`` (slug in host)
+ path -> ``<public_url>/link/<provider>/callback`` (dev: single host)
+
+ Returns None when the active mode's required setting is unset (domain mode
+ without a suffix, path mode without a public URL) or ``slug`` is empty.
+ """
+ if not slug:
+ return None
+ if settings.AGENT_INGRESS_ROUTING_MODE == "domain":
+ suffix = (settings.AGENT_INGRESS_DOMAIN_SUFFIX or "").strip()
+ return f"https://{slug}{suffix}/link/{provider_id}/callback" if suffix else None
+ base = (settings.AGENT_INGRESS_PUBLIC_URL or "").rstrip("/")
+ return f"{base}/link/{provider_id}/callback" if base else None
def _ensure_oauth_app(
@@ -91,12 +109,18 @@ def provision_posthog_identity_apps(
return False
organization = Team.objects.get(pk=application.team_id).organization
- base = _ingress_base()
mutated = False
for entry in posthog_entries:
provider_id = entry.get("id") or "posthog"
- redirect_uri = f"{base}/link/{provider_id}/callback"
+ redirect_uri = build_link_callback_url(application.slug, provider_id)
+ if not redirect_uri:
+ # A posthog-identity agent can't link without a reachable callback host.
+ # Fail the promote loudly rather than register a wrong/empty redirect URI.
+ raise ImproperlyConfigured(
+ "Cannot provision the PostHog identity app: no agent-ingress callback URL is configured "
+ "(set AGENT_INGRESS_DOMAIN_SUFFIX in domain mode, or AGENT_INGRESS_PUBLIC_URL in path mode)."
+ )
scopes = list(entry.get("scopes") or [])
# Stable, readable, org-unique per (agent, provider).
name = f"Agent identity · {application.slug} · {provider_id}"
diff --git a/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py
index 99532b27c773..75cb155f2bda 100644
--- a/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py
+++ b/products/agent_platform/backend/tests/test_posthog_identity_provisioning.py
@@ -11,12 +11,14 @@ from __future__ import annotations
from posthog.test.base import APIBaseTest
+from django.core.exceptions import ImproperlyConfigured
from django.test import override_settings
from rest_framework import status
from posthog.models.oauth import OAuthApplication
+from ..logic.posthog_identity_app import provision_posthog_identity_apps
from ..models import AgentApplication, AgentRevision
POSTHOG_SPEC = {
@@ -94,3 +96,23 @@ class TestPostHogIdentityProvisioning(APIBaseTest):
revision = self._ready_revision({"model": "anthropic/claude-sonnet-4-6"})
self._promote(revision)
self.assertEqual(len(self._identity_apps()), 0)
+
+ @override_settings(
+ AGENT_INGRESS_ROUTING_MODE="domain",
+ AGENT_INGRESS_DOMAIN_SUFFIX=".agents.us.posthog.com",
+ )
+ def test_domain_mode_registers_per_agent_callback_host(self) -> None:
+ revision = self._ready_revision(POSTHOG_SPEC)
+ self._promote(revision)
+
+ app = self._identity_apps()[0]
+ # In domain mode the callback lands on the agent's own env-specific host,
+ # not a flat/shared one — this is the redirect that must match what the
+ # runner sends at authorize time (build_link_callback_url mirror).
+ self.assertEqual(app.redirect_uris, "https://dog-bot.agents.us.posthog.com/link/posthog/callback")
+
+ @override_settings(AGENT_INGRESS_ROUTING_MODE="domain", AGENT_INGRESS_DOMAIN_SUFFIX="")
+ def test_missing_callback_host_fails_loudly(self) -> None:
+ revision = self._ready_revision(POSTHOG_SPEC)
+ with self.assertRaises(ImproperlyConfigured):
+ provision_posthog_identity_apps(application=self.application, revision=revision, acting_user=self.user)
diff --git a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
index 367745a8e989..ec3709245b94 100644
--- a/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
+++ b/products/agent_platform/services/agent-ingress/src/enqueue/admission-gate.ts
@@ -11,12 +11,14 @@
import {
AdmissionService,
buildIdentityRegistry,
+ buildLinkCallbackUrl,
type AgentRevision,
type EncryptedFields,
type HttpFetcher,
type IdentityCredentialStore,
type IdentityLinkStateStore,
type IdentityStore,
+ type IngressRoutingMode,
type TransportBindingStore,
} from '@posthog/agent-shared'
@@ -28,18 +30,22 @@ export interface AdmissionDepsBundle {
envEncryption: EncryptedFields
http: HttpFetcher
posthogApiBaseUrl?: string
+ /** Ingress routing mode; builds the OAuth callback host (`domain` → per-agent, `path` → flat). */
+ routingMode?: IngressRoutingMode
+ /** Domain suffix for domain mode (e.g. `.agents.us.posthog.com`). */
+ domainSuffix?: string
+ /** Flat ingress base URL for the OAuth callback in `path` mode (dev). */
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 {
+ * no authoritative provider (passthrough). `slug` is the agent's slug — in
+ * domain mode the OAuth callback lands on that agent's own host. */
+export function buildAdmission(
+ deps: AdmissionDepsBundle,
+ revision: AgentRevision,
+ slug: string
+): AdmissionService | null {
if (!revision.spec.authoritative_provider) {
return null
}
@@ -56,6 +62,18 @@ export function buildAdmission(deps: AdmissionDepsBundle, revision: AgentRevisio
identities: deps.identities,
bindings: deps.transportBindings,
credentials: deps.identityCredentials,
- redirectUriFor: (p) => admissionRedirectUri(deps.publicBaseUrl, p),
+ redirectUriFor: (p) => {
+ const url = buildLinkCallbackUrl({
+ routingMode: deps.routingMode ?? 'path',
+ domainSuffix: deps.domainSuffix,
+ publicBaseUrl: deps.publicBaseUrl,
+ slug,
+ provider: p,
+ })
+ if (!url) {
+ throw new Error('link_callback_url_unconfigured')
+ }
+ return url
+ },
})
}
diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.ts
index b014ff65d197..b0a0cb809c32 100644
--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts
+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts
@@ -321,7 +321,7 @@ export function buildApp(opts: BuildAppOpts): Express {
// 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)
+ const admission = buildAdmission(opts, revision, application?.slug ?? '')
if (admission && providerId === revision.spec.authoritative_provider) {
await admission.complete(providerId, stateId, { code, error: errorParam })
} else {
diff --git a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
index a0774ba2c0a3..2f3362b1f02d 100644
--- a/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
+++ b/products/agent_platform/services/agent-ingress/src/triggers/slack.ts
@@ -230,7 +230,7 @@ async function slackEventsHandler(ctx: RouteCtx): Promise<void> {
// 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)
+ const admission = buildAdmission(deps, resolved.revision, resolved.application.slug)
if (admission) {
const result = await admission.resolve(
{
diff --git a/products/agent_platform/services/agent-runner/src/config.ts b/products/agent_platform/services/agent-runner/src/config.ts
index a9b831571c08..a8ec75640deb 100644
--- a/products/agent_platform/services/agent-runner/src/config.ts
+++ b/products/agent_platform/services/agent-runner/src/config.ts
@@ -239,12 +239,25 @@ export const AgentRunnerConfigSchema = PlatformConfigSchema.extend({
.describe(
'Comma-separated CIDRs the Modal custom-tool sandbox may reach outbound. Empty (default) → the sandbox has NO outbound internet (Modal `block_network`). Custom tools compute and return; the runner makes any egress through smokescreen. Set only if a custom tool genuinely needs direct egress to a known range.'
),
+ routingMode: z
+ .enum(['path', 'domain'])
+ .default('path')
+ .describe(
+ 'Ingress routing mode; must match the ingress `ROUTING_MODE`. In `domain` mode the OAuth link callback host is the agent‑specific `<slug><domainSuffix>`; `path` (dev) uses `linkRedirectBaseUrl`.'
+ ),
+ domainSuffix: z
+ .string()
+ .optional()
+ .describe(
+ 'Domain suffix for `domain` mode (e.g. `.agents.us.posthog.com`); mirrors the ingress `DOMAIN_SUFFIX`. Builds the per-agent OAuth link callback host (`https://<slug><domainSuffix>/link/<provider>/callback`).'
+ ),
linkRedirectBaseUrl: z
.string()
.url()
- .default(() => (isDev() ? 'http://localhost:3030' : 'https://agents.posthog.com'))
+ .optional()
+ .transform((v): string | undefined => v ?? (isDev() ? 'http://localhost:3030' : undefined))
.describe(
- 'Public base URL of the ingress, used to build OAuth callback redirect URIs for identity linking (`<base>/link/<provider>/callback`). Dev defaults to the local ingress; prod sets the deployed ingress URL.'
+ 'Flat ingress base URL used to build OAuth link callback URIs (`<base>/link/<provider>/callback`) in `path` mode (dev). Dev defaults to the local ingress. In `domain` mode (prod) the callback host is derived from the agent slug + `domainSuffix`, so this is unused.'
),
webSearchProvider: z
.enum(WEB_SEARCH_PROVIDER_NAMES)
@@ -318,6 +331,8 @@ const ENV_KEY_MAP = extendEnvKeyMap<AgentRunnerConfig>(PLATFORM_ENV_KEY_MAP, {
SANDBOX_OUTBOUND_CIDR_ALLOWLIST: 'sandboxOutboundCidrAllowlist',
MODAL_APP_NAME: 'modalAppName',
MODAL_REGION: 'modalRegion',
+ ROUTING_MODE: 'routingMode',
+ DOMAIN_SUFFIX: 'domainSuffix',
AGENT_INGRESS_PUBLIC_URL: 'linkRedirectBaseUrl',
AGENT_WEB_SEARCH_PROVIDER: 'webSearchProvider',
AGENT_WEB_SEARCH_FALLBACKS: 'webSearchFallbacks',
diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.ts
index f1161623ea1e..885358d32035 100644
--- a/products/agent_platform/services/agent-runner/src/index.ts
+++ b/products/agent_platform/services/agent-runner/src/index.ts
@@ -379,6 +379,8 @@ async function main(): Promise<void> {
identityCredentials,
identityLinks: new PgIdentityLinkStateStore(agentDb),
identities,
+ routingMode: config.routingMode,
+ domainSuffix: config.domainSuffix,
linkRedirectBaseUrl: config.linkRedirectBaseUrl,
mcpConnections,
devMcpBearerToken: config.devMcpBearerToken,
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index 0dad216d4e06..eee28b05f12c 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -50,6 +50,7 @@ import {
BundleStore,
buildSystemPrompt,
buildAskerIdentity,
+ type IngressRoutingMode,
ConversationMessage,
CredentialBroker,
createLogger,
@@ -262,7 +263,13 @@ export interface RunSessionDeps {
identityLinks?: IdentityLinkStateStore
/** Resolves a non-slack principal to its AgentUser id for linking. */
identities?: IdentityStore
- /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ /** Agent slug — the OAuth link callback host in domain mode is `<slug><domainSuffix>`. */
+ applicationSlug?: string
+ /** Ingress routing mode; mirrors the ingress `ROUTING_MODE`. Defaults to `path`. */
+ routingMode?: IngressRoutingMode
+ /** Domain suffix for domain mode (e.g. `.agents.us.posthog.com`). */
+ domainSuffix?: string
+ /** Flat ingress base URL for the OAuth link callback in `path` mode (dev). */
linkRedirectBaseUrl?: string
}
@@ -469,6 +476,9 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
http: deps.http,
secret: (name) => deps.secrets[name],
posthogApiBaseUrl: deps.posthogApiBaseUrl,
+ slug: deps.applicationSlug ?? '',
+ routingMode: deps.routingMode,
+ domainSuffix: deps.domainSuffix,
linkRedirectBaseUrl: deps.linkRedirectBaseUrl,
log,
})
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.ts
index 5d02c417b58d..4af6cbb9a6b6 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts
@@ -29,6 +29,7 @@ import {
buildAskerIdentity,
BundleStore,
categorize,
+ type IngressRoutingMode,
createLogger,
CredentialBroker,
IdentityCredentialStore,
@@ -191,7 +192,11 @@ export interface WorkerDeps {
identityCredentials?: IdentityCredentialStore
identityLinks?: IdentityLinkStateStore
identities?: IdentityStore
- /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ /** Ingress routing mode; mirrors the ingress `ROUTING_MODE`. Defaults to `path`. */
+ routingMode?: IngressRoutingMode
+ /** Domain suffix for domain mode (e.g. `.agents.us.posthog.com`); builds the per-agent OAuth link callback host. */
+ domainSuffix?: string
+ /** Flat ingress base URL for the OAuth link callback in `path` mode (dev). */
linkRedirectBaseUrl?: string
/**
* Override the MCP transport factory. Defaults to
@@ -495,6 +500,9 @@ export class Worker {
http: this.deps.http,
secret: (name) => secrets[name],
posthogApiBaseUrl: this.deps.posthogApiBaseUrl,
+ slug: application?.slug ?? '',
+ routingMode: this.deps.routingMode,
+ domainSuffix: this.deps.domainSuffix,
linkRedirectBaseUrl: this.deps.linkRedirectBaseUrl,
log: (level, msg, meta) => sLog[level](meta ?? {}, msg),
})
@@ -612,6 +620,9 @@ export class Worker {
identityCredentials: this.deps.identityCredentials,
identityLinks: this.deps.identityLinks,
identities: this.deps.identities,
+ applicationSlug: application?.slug,
+ routingMode: this.deps.routingMode,
+ domainSuffix: this.deps.domainSuffix,
linkRedirectBaseUrl: this.deps.linkRedirectBaseUrl,
mcpClients: openedMcpClients,
mcpFailures,
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index 7151250f2b76..24148f0b0f5c 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -60,6 +60,7 @@ 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/link-callback-url'
export * from './runtime/transport'
export * from './runtime/transport-binding-store'
export * from './runtime/admission'
diff --git a/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts b/products/agent_platform/services/agent-shared/src/runtime/identity-gate.ts
index a69799aef9a1..521bf7290167 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
@@ -12,6 +12,7 @@ import type { HttpFetcher } from './http-client'
import type { IdentityCredentialStore } from './identity-credential-store'
import type { IdentityLinkStateStore } from './identity-link-state-store'
import { type IdentityProvider, type IdentityProviderRegistry, MapIdentityProviderRegistry } from './identity-provider'
+import { buildLinkCallbackUrl, type IngressRoutingMode } from './link-callback-url'
import { Oauth2AuthProvider } from './oauth2-identity-provider'
import { PostHogAuthProvider, SeedOnlyPostHogProvider } from './posthog-identity-provider'
@@ -302,7 +303,13 @@ export interface BuildAskerIdentityDeps {
/** PostHog instance base URL — builds the managed posthog provider + the
* implicit seed-only fallback. */
posthogApiBaseUrl: string
- /** OAuth callback base; `/link/<provider>/callback` is appended. */
+ /** The agent's slug — the callback host in domain mode is `<slug><domainSuffix>`. */
+ slug: string
+ /** Ingress routing mode; mirrors the ingress's own `ROUTING_MODE`. Defaults to `path`. */
+ routingMode?: IngressRoutingMode
+ /** Domain suffix for domain mode (e.g. `.agents.us.posthog.com`). */
+ domainSuffix?: string
+ /** Flat ingress base URL, used to build the callback in `path` mode (dev). */
linkRedirectBaseUrl?: string
log?: IdentityLog
}
@@ -347,13 +354,24 @@ export async function buildAskerIdentity(
applicationId: rev.application_id,
teamId: session.team_id,
})
- const base = deps.linkRedirectBaseUrl ?? 'https://agents.posthog.com'
return createToolIdentity({
registry,
agentUserId,
teamId: session.team_id,
applicationId: rev.application_id,
- redirectUriFor: (p) => `${base}/link/${p}/callback`,
+ redirectUriFor: (p) => {
+ const url = buildLinkCallbackUrl({
+ routingMode: deps.routingMode ?? 'path',
+ domainSuffix: deps.domainSuffix,
+ publicBaseUrl: deps.linkRedirectBaseUrl,
+ slug: deps.slug,
+ provider: p,
+ })
+ if (!url) {
+ throw new Error('link_callback_url_unconfigured')
+ }
+ return url
+ },
unavailableReason: sharedSession ? 'shared_session_unsupported' : undefined,
seed: deps.credentialBroker ? { resolve: (t) => deps.credentialBroker!.resolve(session.id, t) } : undefined,
log: deps.log,
diff --git a/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.test.ts b/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.test.ts
new file mode 100644
index 000000000000..e1b403e4849a
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.test.ts
@@ -0,0 +1,50 @@
+import { buildLinkCallbackUrl } from './link-callback-url'
+
+describe('buildLinkCallbackUrl', () => {
+ it('domain mode lands on the agent’s own per-slug host', () => {
+ expect(
+ buildLinkCallbackUrl({
+ routingMode: 'domain',
+ domainSuffix: '.agents.us.posthog.com',
+ slug: 'weekly-digest',
+ provider: 'posthog',
+ })
+ ).toBe('https://weekly-digest.agents.us.posthog.com/link/posthog/callback')
+ })
+
+ it('path mode uses the flat public base URL with no slug', () => {
+ expect(
+ buildLinkCallbackUrl({
+ routingMode: 'path',
+ publicBaseUrl: 'http://localhost:3030',
+ slug: 'weekly-digest',
+ provider: 'posthog',
+ })
+ ).toBe('http://localhost:3030/link/posthog/callback')
+ })
+
+ it('path mode trims a trailing slash on the base URL', () => {
+ expect(
+ buildLinkCallbackUrl({
+ routingMode: 'path',
+ publicBaseUrl: 'https://x.trycloudflare.com/',
+ slug: 'a',
+ provider: 'slack',
+ })
+ ).toBe('https://x.trycloudflare.com/link/slack/callback')
+ })
+
+ // Null (rather than a wrong/hardcoded host) is what makes the caller fail the
+ // link loudly instead of silently redirecting to the wrong place — the bug
+ // this builder replaced.
+ it.each([
+ ['domain mode without a suffix', { routingMode: 'domain' as const, slug: 's', provider: 'p' }],
+ ['path mode without a base URL', { routingMode: 'path' as const, slug: 's', provider: 'p' }],
+ [
+ 'an empty slug in domain mode',
+ { routingMode: 'domain' as const, domainSuffix: '.agents.us.posthog.com', slug: '', provider: 'p' },
+ ],
+ ])('returns null for %s', (_label, opts) => {
+ expect(buildLinkCallbackUrl(opts)).toBeNull()
+ })
+})
diff --git a/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.ts b/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.ts
new file mode 100644
index 000000000000..d5cb54a8156d
--- /dev/null
+++ b/products/agent_platform/services/agent-shared/src/runtime/link-callback-url.ts
@@ -0,0 +1,44 @@
+/**
+ * The ingress OAuth link-callback URL for an agent + provider, matching what the
+ * deployed ingress actually serves in each routing mode.
+ *
+ * MIRROR: `agent_link_callback_url` in
+ * products/agent_platform/backend/logic/posthog_identity_app.py. The two MUST
+ * produce byte-identical strings — Django registers this as the
+ * OAuthApplication `redirect_uri` at promote, the runner sends the same value at
+ * authorize time, and the IdP rejects the exchange on any mismatch.
+ *
+ * domain → `https://<slug><domainSuffix>/link/<provider>/callback` (slug in host)
+ * path → `<publicBaseUrl>/link/<provider>/callback` (dev: single ingress host)
+ *
+ * The callback route is registered at the ROOT of the ingress app in both modes
+ * (`agent-ingress/src/routing/server.ts` — it recovers the agent from the OAuth
+ * `state`, not the host), so the only per-mode difference is how the base host
+ * is built: domain mode addresses the agent's own `<slug>` host; path mode (dev)
+ * has a single flat ingress host with no slug in the URL.
+ *
+ * Returns null when the active mode's required input is missing (domain mode
+ * without a suffix, path mode without a public base URL, or an empty slug) —
+ * the caller then has no reachable callback to offer and should fail the link
+ * rather than send the IdP a wrong host.
+ */
+export type IngressRoutingMode = 'domain' | 'path'
+
+export function buildLinkCallbackUrl(opts: {
+ routingMode: IngressRoutingMode
+ domainSuffix?: string
+ publicBaseUrl?: string
+ slug: string
+ provider: string
+}): string | null {
+ const { routingMode, domainSuffix, publicBaseUrl, slug, provider } = opts
+ if (!slug) {
+ return null
+ }
+ if (routingMode === 'domain') {
+ const suffix = domainSuffix?.trim()
+ return suffix ? `https://${slug}${suffix}/link/${provider}/callback` : null
+ }
+ const base = (publicBaseUrl ?? '').replace(/\/+$/, '')
+ return base ? `${base}/link/${provider}/callback` : null
+}
diff --git a/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts b/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
index bf18a4387ca3..e7c2d54d5237 100644
--- a/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/admission-cluster-e2e.test.ts
@@ -154,6 +154,10 @@ maybeDescribe('edge admission e2e (Slack, authoritative provider, mocked inferen
expect(first.body.session_id).toBeUndefined()
const authorizeUrl = first.body.authorize_url as string
expect(authorizeUrl).toContain(dog.baseUrl)
+ // The callback the IdP bounces back to must be the configured ingress
+ // base, not a hardcoded fallback host — this is what broke when the base
+ // was unset in prod.
+ expect(new URL(authorizeUrl).searchParams.get('redirect_uri')).toBe('http://callback.test/link/dogs/callback')
await c.drain() // nothing queued; a no-op
// Complete the link → admission writes the binding + canonical identity.
diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
index 592e869fde8e..4c418edfe105 100644
--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts
+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
@@ -419,6 +419,8 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
identityCredentials,
identityLinks,
identities,
+ routingMode: opts.routingMode ?? 'path',
+ domainSuffix: opts.domainSuffix,
linkRedirectBaseUrl: 'http://callback.test',
bus,
logs: logSink,
@@ -457,6 +459,10 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
routingMode: opts.routingMode ?? 'path',
pathPrefix: '/agents',
domainSuffix: opts.domainSuffix,
+ // OAuth link-callback base for `path` mode (dev/harness). In `domain`
+ // mode the callback host is derived from the slug + domainSuffix instead.
+ // Matches the worker's linkRedirectBaseUrl so both sides agree.
+ publicBaseUrl: 'http://callback.test',
slackSigningSecretResolver,
authProvider: opts.authProvider,
identities,