Skip to content

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

Implement TrueFoundry external login redirection (#672)

Govinda Vashishtha5e68fa411eed
diff --git a/.changeset/tf-external-login.md b/.changeset/tf-external-login.md
new file mode 100644
index 000000000..14b2d59d0
--- /dev/null
+++ b/.changeset/tf-external-login.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+TrueFoundry-mode `/api/v1/auth/login` redirects to `PUBLIC_BASE_URL` origin + caller `return_to` (platform `/signin/external?redirectPath=…`).
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index b2e500f11..c2dfa1fd7 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -5907,22 +5907,22 @@
},
"/api/v1/auth/login": {
"get": {
- "description": "Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight back into the app — there is nothing to log into.",
+ "description": "Redirects the browser to begin authentication. Optional `return_to` is the same-origin path to land on afterward.",
"parameters": [
{
- "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
+ "description": "Same-origin path to land on after authentication.",
"in": "query",
"name": "return_to",
"required": false,
"schema": {
- "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
+ "description": "Same-origin path to land on after authentication.",
"type": "string"
}
}
],
"responses": {
"302": {
- "description": "Redirect to the IdP authorization endpoint."
+ "description": "Redirect to continue authentication."
}
},
"summary": "Start the login flow",
diff --git a/docs/openapi.json b/docs/openapi.json
index b2e500f11..c2dfa1fd7 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -5907,22 +5907,22 @@
},
"/api/v1/auth/login": {
"get": {
- "description": "Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight back into the app — there is nothing to log into.",
+ "description": "Redirects the browser to begin authentication. Optional `return_to` is the same-origin path to land on afterward.",
"parameters": [
{
- "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
+ "description": "Same-origin path to land on after authentication.",
"in": "query",
"name": "return_to",
"required": false,
"schema": {
- "description": "Path to return to after login. Same-origin relative path; otherwise the public UI home.",
+ "description": "Same-origin path to land on after authentication.",
"type": "string"
}
}
],
"responses": {
"302": {
- "description": "Redirect to the IdP authorization endpoint."
+ "description": "Redirect to continue authentication."
}
},
"summary": "Start the login flow",
diff --git a/packages/frontend/src/AuthErrorScreen.tsx b/packages/frontend/src/AuthErrorScreen.tsx
index e559580d0..ae7207731 100644
--- a/packages/frontend/src/AuthErrorScreen.tsx
+++ b/packages/frontend/src/AuthErrorScreen.tsx
@@ -1,5 +1,5 @@
import { BrandLogo } from '@truefoundry/trueforge-ui';
-import { AUTH_LOGIN_HREF } from './authFetch';
+import { buildLoginHref } from './authFetch';
import './authScreens.css';
/** OIDC / login failure status. Mirrors the welcome page layout. */
@@ -11,7 +11,7 @@ export function AuthErrorScreen({ reason }: { reason: string }) {
<BrandLogo className="auth-screen-logo" />
<h1 className="auth-screen-title">Sign-in failed</h1>
<p className="auth-screen-message">{message}</p>
- <a className="auth-screen-button" href={AUTH_LOGIN_HREF}>
+ <a className="auth-screen-button" href={buildLoginHref()}>
Try again
</a>
</div>
diff --git a/packages/frontend/src/authFetch.ts b/packages/frontend/src/authFetch.ts
index 2f75b89f6..4c512d166 100644
--- a/packages/frontend/src/authFetch.ts
+++ b/packages/frontend/src/authFetch.ts
@@ -1,20 +1,20 @@
/**
* Browser auth entry points. Login and logout are not SDK methods (cookie session).
- * On any HTTP 401, redirect to OIDC login (session required).
+ * On any HTTP 401, redirect to login (session required).
*
* Auth URLs share the public prefix with the UI (e.g. `/custom/proxy/path/api/v1/auth/...`).
- * A reverse proxy strips that prefix before Harness. Pass `return_to` so post-login
- * lands back under the UI path.
+ * A reverse proxy strips that prefix before Harness. Pass `return_to` as the post-login
+ * app path; the server applies TrueFoundry platform wrapping when needed.
*/
import { apiPath, UI_BASE_PATH } from './publicPath';
-/** Browser entry for OIDC login (not available as an SDK method). */
+/** Browser entry for login (not available as an SDK method). */
export const AUTH_LOGIN_HREF = apiPath('/api/v1/auth/login');
/** Clears the local session cookie (not available as an SDK method). */
export const AUTH_LOGOUT_HREF = apiPath('/api/v1/auth/logout');
-/** Login URL with a same-origin `return_to` (defaults to the UI home). */
+/** Login URL with a same-origin post-login `return_to` (defaults to the UI home). */
export function buildLoginHref(returnTo: string = UI_BASE_PATH): string {
const params = new URLSearchParams({ return_to: returnTo });
return `${AUTH_LOGIN_HREF}?${params.toString()}`;
diff --git a/packages/trueforge/src/apis/auth.ts b/packages/trueforge/src/apis/auth.ts
index cb501ad48..b1085dbcc 100644
--- a/packages/trueforge/src/apis/auth.ts
+++ b/packages/trueforge/src/apis/auth.ts
@@ -8,9 +8,10 @@ import { resolveRequestContext } from '../auth/identity';
import { resolveOidcRequestContext } from '../auth/middleware';
import { buildLoginAuthorization, exchangeAuthorizationCode } from '../auth/oidc';
import { safeReturnTo } from '../auth/safeReturnTo';
-import { getPublicUiBasePath } from '../config';
+import { getPublicUiBasePath, isTrueFoundryModeEnabled } from '../config';
import { authLoginRoute, authLogoutRoute, meRoute, oAuthCallbackRoute } from '../routes/authRoutes';
import type { GetMeResponse } from '../schemas/auth';
+import { buildTrueFoundryExternalLoginHref, resolveTrueFoundryLoginReturnTo } from '../truefoundry/externalLogin';
/** Login / OIDC failures land on the public UI home with `?error=<reason>`. */
function oauthErrorRedirect(reason: string): string {
@@ -49,22 +50,32 @@ export function createAuthRouter(params: {
const router = new OpenAPIHono();
router.openapi(authLoginRoute, async c => {
- // TODO: remove this checks once the middleware is implemented
- if (!params.oidcClient) {
- return c.redirect(getPublicUiBasePath(), 302);
+ const returnTo = c.req.valid('query').return_to;
+
+ if (params.oidcClient) {
+ try {
+ const authorizationUrl = await buildLoginAuthorization({
+ context: c,
+ client: params.oidcClient,
+ returnTo,
+ });
+ return c.redirect(authorizationUrl, 302);
+ } catch (error) {
+ params.logger.error('Failed to build login authorization', extractErrorLogFields(error));
+ return c.redirect(oauthErrorRedirect('login_failed'), 302);
+ }
}
- try {
- const authorizationUrl = await buildLoginAuthorization({
- context: c,
- client: params.oidcClient,
- returnTo: c.req.valid('query').return_to,
- });
- return c.redirect(authorizationUrl, 302);
- } catch (error) {
- params.logger.error('Failed to build login authorization', extractErrorLogFields(error));
- return c.redirect(oauthErrorRedirect('login_failed'), 302);
+ if (isTrueFoundryModeEnabled()) {
+ try {
+ return c.redirect(buildTrueFoundryExternalLoginHref(resolveTrueFoundryLoginReturnTo(returnTo)), 302);
+ } catch (error) {
+ params.logger.error('Failed to build TrueFoundry external login URL', extractErrorLogFields(error));
+ return c.redirect(oauthErrorRedirect('login_failed'), 302);
+ }
}
+
+ return c.redirect(getPublicUiBasePath(), 302);
});
router.openapi(oAuthCallbackRoute, async c => {
diff --git a/packages/trueforge/src/frontend.ts b/packages/trueforge/src/frontend.ts
index cbaf39041..9444d7626 100644
--- a/packages/trueforge/src/frontend.ts
+++ b/packages/trueforge/src/frontend.ts
@@ -26,7 +26,7 @@ function isAppShellPath(pathname: string): boolean {
return pathname === '/' || pathname === '/index.html';
}
-function applyPublicUiBase(options: { html: string; uiBasePath: string }): string {
+function applyShellTokens(options: { html: string; uiBasePath: string }): string {
return options.html.replaceAll(SHELL_BASE_TOKEN, options.uiBasePath);
}
@@ -52,7 +52,10 @@ export function mountFrontend(app: OpenAPIHono, options: { dir: string; uiBasePa
return false;
}
- const shellHtml = applyPublicUiBase({ html: readFileSync(indexPath, 'utf8'), uiBasePath: options.uiBasePath });
+ const shellHtml = applyShellTokens({
+ html: readFileSync(indexPath, 'utf8'),
+ uiBasePath: options.uiBasePath,
+ });
// serveStatic joins `root` with the request path, so an absolute dir is working-directory proof.
const serveFile = serveStatic({ root: options.dir, precompressed: true });
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index fe3102322..237263b60 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -537,7 +537,12 @@ try {
)
: await createServerRuntime(await createDistributedPersistence({ configuration, logger }), logger);
- if (mountFrontend(app, { dir: configuration.FRONTEND_DIR, uiBasePath: getPublicUiBasePath() })) {
+ if (
+ mountFrontend(app, {
+ dir: configuration.FRONTEND_DIR,
+ uiBasePath: getPublicUiBasePath(),
+ })
+ ) {
logger.info(`Serving frontend from ${configuration.FRONTEND_DIR}`);
} else {
logger.warn(
diff --git a/packages/trueforge/src/routes/authRoutes.ts b/packages/trueforge/src/routes/authRoutes.ts
index dc1314a02..6aca58896 100644
--- a/packages/trueforge/src/routes/authRoutes.ts
+++ b/packages/trueforge/src/routes/authRoutes.ts
@@ -16,13 +16,12 @@ export const authLoginRoute = createRoute({
tags: [OpenApiTag.AUTH],
summary: 'Start the login flow',
description:
- 'Redirects the browser to the configured identity provider. In local/single-binary mode, redirects straight ' +
- 'back into the app — there is nothing to log into.',
+ 'Redirects the browser to begin authentication. Optional `return_to` is the same-origin path to land on afterward.',
'x-fern-ignore': true,
'x-excluded': true,
request: { query: AuthLoginQuerySchema },
responses: {
- 302: { description: 'Redirect to the IdP authorization endpoint.' },
+ 302: { description: 'Redirect to continue authentication.' },
},
});
diff --git a/packages/trueforge/src/schemas/auth.ts b/packages/trueforge/src/schemas/auth.ts
index 763ee1aa4..a93eb2678 100644
--- a/packages/trueforge/src/schemas/auth.ts
+++ b/packages/trueforge/src/schemas/auth.ts
@@ -2,10 +2,7 @@
import { z } from '@hono/zod-openapi';
export const AuthLoginQuerySchema = z.object({
- return_to: z
- .string()
- .optional()
- .describe('Path to return to after login. Same-origin relative path; otherwise the public UI home.'),
+ return_to: z.string().optional().describe('Same-origin path to land on after authentication.'),
});
export const OAuthCallbackQuerySchema = z.object({
diff --git a/packages/trueforge/src/truefoundry/externalLogin.ts b/packages/trueforge/src/truefoundry/externalLogin.ts
new file mode 100644
index 000000000..488300cf3
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/externalLogin.ts
@@ -0,0 +1,27 @@
+import { safeReturnTo } from '../auth/safeReturnTo';
+import { getPublicBaseUrl, getPublicUiBasePath } from '../config';
+
+/** TrueFoundry platform browser login entry (same-origin path). */
+export const TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH = '/signin/external';
+
+/**
+ * Resolve the platform login path for TrueFoundry-mode `/auth/login`.
+ * `return_to` is the post-login app path; the server wraps it as
+ * `/signin/external?redirectPath=…`. Missing/unsafe → UI home.
+ */
+export function resolveTrueFoundryLoginReturnTo(returnTo: string | undefined): string {
+ const redirectPath =
+ returnTo !== undefined && returnTo !== '' && safeReturnTo(returnTo) === returnTo ? returnTo : getPublicUiBasePath();
+ return `${TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH}?${new URLSearchParams({ redirectPath }).toString()}`;
+}
+
+/**
+ * TrueFoundry platform browser login. Harness is mounted under the TF frontend
+ * origin (e.g. `https://app.example.com/trueforge`); `returnTo` is the
+ * same-origin `/signin/external?…` path produced by
+ * {@link resolveTrueFoundryLoginReturnTo}.
+ */
+export function buildTrueFoundryExternalLoginHref(returnTo: string): string {
+ const publicUrl = new URL(getPublicBaseUrl());
+ return `${publicUrl.origin}${returnTo}`;
+}
diff --git a/packages/trueforge/tests/unit/apis/auth.test.ts b/packages/trueforge/tests/unit/apis/auth.test.ts
index f04f035ea..fce05da27 100644
--- a/packages/trueforge/tests/unit/apis/auth.test.ts
+++ b/packages/trueforge/tests/unit/apis/auth.test.ts
@@ -8,7 +8,7 @@ import { createAuthMiddleware } from '../../../src/auth/middleware';
import { disableOidcAuth, initOidc } from '../../../src/auth/oidc';
import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
-import configuration from '../../../src/config';
+import configuration, { getPublicBaseUrl, getPublicUiBasePath, isTrueFoundryModeEnabled } from '../../../src/config';
jest.mock('../../../src/config', () => {
const actual = jest.requireActual<typeof import('../../../src/config')>('../../../src/config');
@@ -39,8 +39,9 @@ jest.mock('../../../src/config', () => {
...actual,
__esModule: true,
default: config,
- getPublicBaseUrl: () => actual.getPublicBaseUrl(publicBase),
- getPublicUiBasePath: () => actual.getPublicUiBasePath(publicBase),
+ getPublicBaseUrl: jest.fn(() => actual.getPublicBaseUrl(publicBase)),
+ getPublicUiBasePath: jest.fn(() => actual.getPublicUiBasePath(publicBase)),
+ isTrueFoundryModeEnabled: jest.fn(() => false),
};
});
@@ -114,6 +115,41 @@ describe('auth router (no identity provider configured)', () => {
});
});
+describe('auth router (TrueFoundry mode)', () => {
+ beforeEach(() => {
+ disableOidcAuth();
+ jest.mocked(isTrueFoundryModeEnabled).mockReturnValue(true);
+ jest.mocked(getPublicBaseUrl).mockReturnValue('https://app.example.com/trueforge');
+ jest.mocked(getPublicUiBasePath).mockReturnValue('/trueforge/');
+ });
+
+ afterEach(() => {
+ jest.mocked(isTrueFoundryModeEnabled).mockReturnValue(false);
+ jest.mocked(getPublicBaseUrl).mockReturnValue('https://harness.example.com');
+ jest.mocked(getPublicUiBasePath).mockReturnValue('/');
+ });
+
+ it('GET /auth/login redirects to TrueFoundry /signin/external by default', async () => {
+ const router = createTestAuthRouter({ oidcClient: undefined });
+
+ const res = await router.request('/login', { redirect: 'manual' });
+
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe('https://app.example.com/signin/external?redirectPath=%2Ftrueforge%2F');
+ });
+
+ it('GET /auth/login wraps return_to as platform redirectPath', async () => {
+ const router = createTestAuthRouter({ oidcClient: undefined });
+
+ const res = await router.request('/login?return_to=/trueforge/sessions/abc', { redirect: 'manual' });
+
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe(
+ 'https://app.example.com/signin/external?redirectPath=%2Ftrueforge%2Fsessions%2Fabc',
+ );
+ });
+});
+
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
diff --git a/packages/trueforge/tests/unit/frontend.test.ts b/packages/trueforge/tests/unit/frontend.test.ts
index 5c09da2fc..73f85787f 100644
--- a/packages/trueforge/tests/unit/frontend.test.ts
+++ b/packages/trueforge/tests/unit/frontend.test.ts
@@ -25,7 +25,10 @@ const HTML_ACCEPT = { accept: 'text/html,application/xhtml+xml' };
describe('mountFrontend', () => {
it('reports whether the directory holds a build', () => {
expect(
- mountFrontend(new OpenAPIHono(), { dir: path.join(tmpdir(), 'trueforge-missing-build'), uiBasePath: '/' }),
+ mountFrontend(new OpenAPIHono(), {
+ dir: path.join(tmpdir(), 'trueforge-missing-build'),
+ uiBasePath: '/',
+ }),
).toBe(false);
expect(mountFrontend(new OpenAPIHono(), { dir: buildDir(), uiBasePath: '/' })).toBe(true);
});
@@ -41,7 +44,8 @@ describe('mountFrontend', () => {
const response = await app.request('/', { headers: HTML_ACCEPT });
expect(response.status).toBe(200);
- await expect(response.text()).resolves.toContain("window.__TRUEFORGE_BASE_PATH__='/custom/proxy/path/'");
+ const html = await response.text();
+ expect(html).toContain("window.__TRUEFORGE_BASE_PATH__='/custom/proxy/path/'");
});
it('serves the app shell for client-only deep links', async () => {
diff --git a/packages/trueforge/tests/unit/truefoundry/externalLogin.test.ts b/packages/trueforge/tests/unit/truefoundry/externalLogin.test.ts
new file mode 100644
index 000000000..d089b904d
--- /dev/null
+++ b/packages/trueforge/tests/unit/truefoundry/externalLogin.test.ts
@@ -0,0 +1,48 @@
+import {
+ buildTrueFoundryExternalLoginHref,
+ resolveTrueFoundryLoginReturnTo,
+ TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH,
+} from '../../../src/truefoundry/externalLogin';
+
+jest.mock('../../../src/config', () => {
+ const actual = jest.requireActual<typeof import('../../../src/config')>('../../../src/config');
+ return {
+ ...actual,
+ getPublicBaseUrl: () => 'https://app.example.com/trueforge',
+ getPublicUiBasePath: () => '/trueforge/',
+ };
+});
+
+describe('buildTrueFoundryExternalLoginHref', () => {
+ it('prefixes PUBLIC_BASE_URL origin onto return_to', () => {
+ expect(buildTrueFoundryExternalLoginHref('/signin/external?redirectPath=%2Ftrueforge%2F')).toBe(
+ 'https://app.example.com/signin/external?redirectPath=%2Ftrueforge%2F',
+ );
+ });
+
+ it('preserves a deep-link redirectPath inside return_to', () => {
+ expect(buildTrueFoundryExternalLoginHref('/signin/external?redirectPath=%2Ftrueforge%2Fsessions%2Fabc')).toBe(
+ 'https://app.example.com/signin/external?redirectPath=%2Ftrueforge%2Fsessions%2Fabc',
+ );
+ });
+});
+
+describe('resolveTrueFoundryLoginReturnTo', () => {
+ it('wraps a safe app path as redirectPath', () => {
+ expect(resolveTrueFoundryLoginReturnTo('/trueforge/sessions/abc')).toBe(
+ `${TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH}?redirectPath=%2Ftrueforge%2Fsessions%2Fabc`,
+ );
+ });
+
+ it('defaults to platform login with UI home when return_to is missing', () => {
+ expect(resolveTrueFoundryLoginReturnTo(undefined)).toBe(
+ `${TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH}?redirectPath=%2Ftrueforge%2F`,
+ );
+ });
+
+ it('defaults when return_to is unsafe', () => {
+ expect(resolveTrueFoundryLoginReturnTo('//evil.example')).toBe(
+ `${TRUEFOUNDRY_EXTERNAL_SIGNIN_PATH}?redirectPath=%2Ftrueforge%2F`,
+ );
+ });
+});