Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

fix: pick redirect URL from session (#789)

Heer Ambavi13da4797ab83
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts b/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
index 7ae4e7fca..40dd5d150 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryAuthenticator.ts
@@ -36,6 +36,7 @@ export class TrueFoundryAuthenticator implements Authenticator {
},
roles: session.user.roles,
user_credential: token,
+ public_base_url: session.public_base_url,
});
}
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
index 73e80f02a..d07629ee3 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -3,7 +3,7 @@ import { HTTPException } from 'hono/http-exception';
import type { Logger } from 'winston';
import type { RequestContext, RequestSubject } from '../auth/identity';
import { safeReturnTo } from '../auth/safeReturnTo';
-import { getPublicBaseUrl } from '../config';
+import { getPublicUiBasePath } from '../config';
import type { AgentRecord } from '../db/agentStore';
import {
McpServerNotFoundError,
@@ -49,12 +49,21 @@ function withoutAuthorization(headers: Record<string, string> | undefined): Reco
return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'authorization'));
}
-/** Absolute FE landing for the upstream authorize `redirectURL`. `return_to` is a browser path. */
-export function resolveAuthorizeRedirectURL(input: { returnTo?: string }): string {
+/**
+ * Absolute FE landing for the upstream authorize `redirectURL`.
+ * Origin from the tenant session `public_base_url`; UI path prefix from process
+ * `PUBLIC_BASE_URL` via {@link getPublicUiBasePath}. `return_to` is a browser path.
+ *
+ * TODO: add an env var for the public UI path prefix (do not keep deriving mount path from
+ * `PUBLIC_BASE_URL`) so tenant origin and path are independently configurable.
+ */
+export function resolveAuthorizeRedirectURL(input: { returnTo?: string; publicBaseUrl: string }): string {
try {
- return new URL(safeReturnTo(input.returnTo), `${new URL(getPublicBaseUrl()).origin}/`).href;
+ const origin = new URL(input.publicBaseUrl).origin;
+ const publicBase = new URL(getPublicUiBasePath(), `${origin}/`);
+ return new URL(safeReturnTo(input.returnTo), publicBase).href;
} catch (error) {
- throw new McpConnectionError('PUBLIC_BASE_URL is required for TrueFoundry MCP OAuth but was empty', 500, {
+ throw new McpConnectionError('Tenant public base URL from session is required for TrueFoundry MCP OAuth', 500, {
cause: error,
});
}
@@ -66,6 +75,7 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
readonly #asAgent: ResolveAccessToken;
readonly #asUser: ResolveAccessToken;
readonly #subject: RequestSubject;
+ readonly #publicBaseUrl: string | undefined;
readonly #perServerHeaders: PerServerMcpHeaders;
#gatewayUrl: string | undefined;
@@ -77,15 +87,17 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
logger: Logger;
}) {
this.#client = input.client;
+ const requestContext = asTrueFoundryRequestContext(input.requestContext);
const tokens = accessTokenForRequest({
client: input.client,
- requestContext: asTrueFoundryRequestContext(input.requestContext),
+ requestContext,
agent: input.agent,
logger: input.logger,
});
this.#asAgent = tokens.asAgent;
this.#asUser = tokens.asUser;
- this.#subject = input.requestContext.subject;
+ this.#subject = requestContext.subject;
+ this.#publicBaseUrl = requestContext.public_base_url;
this.#perServerHeaders = input.perServerHeaders ?? {};
}
@@ -218,10 +230,15 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
if (record === undefined) {
throw new McpServerNotFoundError(input.name);
}
+ const publicBaseUrl = this.#publicBaseUrl;
+ if (publicBaseUrl === undefined || publicBaseUrl.trim() === '') {
+ throw new McpConnectionError('Tenant public base URL from session is required for TrueFoundry MCP OAuth', 500);
+ }
return this.#client.getMcpAuthorize({
accessToken: await this.#asUser(),
mcpServerId: record.id,
redirectURL: resolveAuthorizeRedirectURL({
+ publicBaseUrl,
...(input.returnTo !== undefined ? { returnTo: input.returnTo } : {}),
}),
});
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
index d627f8d9d..fc330f259 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
@@ -41,14 +41,21 @@ const GetSessionUserSchema = z.object({
subject: SessionSubjectSchema,
});
-const GetSessionWireSchema = z.object({
- user: GetSessionUserSchema.nullable(),
+const GetSessionUnauthenticatedSchema = z.object({
+ user: z.null(),
});
-/** Authenticated session payload (`user` is non-null after {@link TrueFoundryServiceFoundryServerClient.getSession}). */
-export interface GetSessionResponse {
- user: z.infer<typeof GetSessionUserSchema>;
-}
+const GetSessionAuthenticatedSchema = z
+ .object({
+ user: GetSessionUserSchema,
+ controlPlaneURL: z.url(),
+ })
+ .transform(({ user, controlPlaneURL: public_base_url }) => ({ user, public_base_url }));
+
+const GetSessionWireSchema = z.union([GetSessionUnauthenticatedSchema, GetSessionAuthenticatedSchema]);
+
+/** Authenticated session payload returned by {@link TrueFoundryServiceFoundryServerClient.getSession}. */
+export type GetSessionResponse = z.infer<typeof GetSessionAuthenticatedSchema>;
const ListResponseSchema = z.union([
z.array(z.unknown()),
@@ -472,8 +479,8 @@ export class TrueFoundryServiceFoundryServerClient {
}
/**
- * `GET v1/session` for RequestContext mapping.
- * `user: null` (invalid/missing auth on a 200) → 401; all other failures → 500.
+ * `GET v1/session` for RequestContext mapping (always called with a bearer token).
+ * SFY optional-auth soft failure (`user: null` on 200) → 401; malformed → 500.
*/
async getSession(accessToken: string): Promise<GetSessionResponse> {
let payload: unknown;
@@ -502,7 +509,7 @@ export class TrueFoundryServiceFoundryServerClient {
if (parsed.data.user === null) {
throw new HTTPException(401, { message: 'Authentication required' });
}
- return { user: parsed.data.user };
+ return parsed.data;
}
async getAgentPermissions(input: {
diff --git a/packages/trueforge/src/truefoundry/accessToken.ts b/packages/trueforge/src/truefoundry/accessToken.ts
index 8f2d42ff4..95088fd55 100644
--- a/packages/trueforge/src/truefoundry/accessToken.ts
+++ b/packages/trueforge/src/truefoundry/accessToken.ts
@@ -32,9 +32,17 @@ const accessTokenCache: unique symbol = Symbol('truefoundryAccessTokenCache');
*/
export type TrueFoundryRequestContext = RequestContext & {
readonly [accessTokenCache]: Map<string, AccessTokens>;
+ /**
+ * Tenant public base URL from ServiceFoundry session (`controlPlaneURL`).
+ * Set by {@link TrueFoundryAuthenticator}; may be absent on synthetic contexts
+ * (e.g. schedule impersonation). Used as the MCP OAuth FE redirect origin.
+ */
+ public_base_url?: string;
};
-export function createTrueFoundryRequestContext(base: RequestContext): TrueFoundryRequestContext {
+export function createTrueFoundryRequestContext(
+ base: RequestContext & { public_base_url?: string },
+): TrueFoundryRequestContext {
return { ...base, [accessTokenCache]: new Map() };
}
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAuthenticator.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAuthenticator.test.ts
new file mode 100644
index 000000000..c18417216
--- /dev/null
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAuthenticator.test.ts
@@ -0,0 +1,37 @@
+import type { Context } from 'hono';
+import { TrueFoundryAuthenticator } from '../../../src/truefoundry/TrueFoundryAuthenticator';
+
+describe('TrueFoundryAuthenticator', () => {
+ it('stores public_base_url from GET /v1/session on request context', async () => {
+ const getSession = jest.fn().mockResolvedValue({
+ user: {
+ tenantName: 'internal',
+ roles: ['tenant-admin'],
+ subject: {
+ subjectId: 'user-1',
+ subjectType: 'user',
+ subjectDisplayName: 'Alice',
+ subjectSlug: '[email protected]',
+ },
+ },
+ public_base_url: 'https://tenant.example.com',
+ });
+ const authenticator = new TrueFoundryAuthenticator({ getSession });
+ const context = {
+ req: {
+ header: (name: string) => (name.toLowerCase() === 'authorization' ? 'Bearer tok' : undefined),
+ },
+ } as unknown as Context;
+
+ const requestContext = await authenticator.authenticate(context);
+
+ expect(getSession).toHaveBeenCalledWith('tok');
+ expect(requestContext).toMatchObject({
+ tenant_id: 'internal',
+ subject: { id: 'user-1', type: 'user', display_name: 'Alice' },
+ roles: ['tenant-admin'],
+ user_credential: 'tok',
+ public_base_url: 'https://tenant.example.com',
+ });
+ });
+});
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
index 5bd0ace3c..8173d726f 100644
--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
@@ -1,6 +1,5 @@
import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
import { createLogger } from 'winston';
-import { getPublicBaseUrl } from '../../../src/config';
import type { AgentRecord } from '../../../src/db/agentStore';
import { McpServerNotFoundError, type McpServerRecord } from '../../../src/db/mcpServerStore';
import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken';
@@ -15,6 +14,7 @@ const TENANT = 'default';
const ACCESS_TOKEN = 'caller-access-token';
const SUBJECT_TOKEN = 'subject-token';
const ACTOR_TOKEN = 'actor-token';
+const PUBLIC_BASE_URL = 'https://tenant.example.com';
const AGENT: AgentRecord = {
id: 'agent-1',
@@ -60,6 +60,7 @@ function createStore(input?: {
client?: MockClient;
subject?: { id: string; type: string; display_name: string };
agent?: AgentRecord;
+ publicBaseUrl?: string;
}) {
const client = input?.client ?? createMockClient();
client.getMcpServerByName.mockResolvedValue(SFY_ROW);
@@ -78,6 +79,7 @@ function createStore(input?: {
subject: input?.subject ?? { id: 'user-1', type: 'user', display_name: 'user-1' },
roles: [],
user_credential: input?.accessToken ?? ACCESS_TOKEN,
+ public_base_url: input?.publicBaseUrl ?? PUBLIC_BASE_URL,
}),
agent: input?.agent,
logger: createLogger({ silent: true }),
@@ -121,9 +123,18 @@ function truefoundryRecordWithoutAuth(overrides: { name?: string; id?: string }
}
describe('resolveAuthorizeRedirectURL', () => {
- it('builds an absolute FE landing from return_to', () => {
- const returnTo = '/?screenType=mcp-auth&pUid=popup-1';
- expect(resolveAuthorizeRedirectURL({ returnTo })).toBe(new URL(returnTo, `${getPublicBaseUrl()}/`).href);
+ it('builds an absolute FE landing from return_to on the tenant public base URL origin', () => {
+ const returnTo = '/trueforge/?screenType=mcp-auth&pUid=popup-1';
+ expect(resolveAuthorizeRedirectURL({ returnTo, publicBaseUrl: PUBLIC_BASE_URL })).toBe(
+ `${PUBLIC_BASE_URL}${returnTo}`,
+ );
+ });
+
+ it('keeps path and query from return_to on the session origin', () => {
+ const returnTo = '/trueforge/sessions/abc?screenType=mcp-auth&pUid=popup-1';
+ expect(resolveAuthorizeRedirectURL({ returnTo, publicBaseUrl: PUBLIC_BASE_URL })).toBe(
+ `${PUBLIC_BASE_URL}${returnTo}`,
+ );
});
});
@@ -148,14 +159,22 @@ describe('TrueFoundryMcpServerStore', () => {
});
describe('authorize', () => {
- it('derives upstream redirectURL from return_to', async () => {
+ it('derives upstream redirectURL from return_to and session public base URL', async () => {
const { store, client } = createStore();
- const returnTo = '/?screenType=mcp-auth&pUid=popup-1';
+ const returnTo = '/trueforge/?screenType=mcp-auth&pUid=popup-1';
await store.authorize({ tenant_id: TENANT, name: 'github', userRef: 'user-1', returnTo });
expect(client.getMcpAuthorize).toHaveBeenCalledWith({
accessToken: ACCESS_TOKEN,
mcpServerId: 'mcp-id-1',
- redirectURL: resolveAuthorizeRedirectURL({ returnTo }),
+ redirectURL: resolveAuthorizeRedirectURL({ returnTo, publicBaseUrl: PUBLIC_BASE_URL }),
+ });
+ });
+
+ it('throws when session public base URL is missing', async () => {
+ const { store } = createStore({ publicBaseUrl: '' });
+ await expect(store.authorize({ tenant_id: TENANT, name: 'github', userRef: 'user-1' })).rejects.toMatchObject({
+ message: 'Tenant public base URL from session is required for TrueFoundry MCP OAuth',
+ statusCode: 500,
});
});
diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
index 2266ee017..d84709fbb 100644
--- a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
@@ -50,6 +50,7 @@ const storeWith = (perServerHeaders: Record<string, Record<string, string>>): Tr
subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
roles: [],
user_credential: 'caller-token',
+ public_base_url: 'https://tenant.example.com',
}),
agent: undefined,
logger: createLogger({ silent: true }),