Skip to content

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

AGE-1623: Implement OIDC authentication flow (#74)

Sujai Kumar Gupta91a7263bb8f7
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.json
index af7e962ba..514ec92b1 100644
--- a/fern/openapi/openapi.json
+++ b/fern/openapi/openapi.json
@@ -334,28 +334,6 @@
},
"type": "object"
},
- "AuthMeResponse": {
- "properties": {
- "role": {
- "$ref": "#/components/schemas/AuthRole"
- },
- "user_ref": {
- "type": "string"
- }
- },
- "required": [
- "user_ref",
- "role"
- ],
- "type": "object"
- },
- "AuthRole": {
- "enum": [
- "admin",
- "user"
- ],
- "type": "string"
- },
"BaseMCPAuthRequiredEvent": {
"properties": {
"created_at": {
@@ -4053,7 +4031,7 @@
],
"responses": {
"302": {
- "description": "Redirect back into the app on success, or to /login?error=... on failure."
+ "description": "Redirect back into the app on success, or to /?error=login_failed on failure."
}
},
"summary": "Login callback",
@@ -4108,41 +4086,6 @@
"x-fern-sdk-method-name": "logout"
}
},
- "/api/v1/auth/me": {
- "get": {
- "description": "Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.",
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/AuthMeResponse"
- }
- }
- },
- "description": "The caller's identity."
- },
- "401": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/RequestErrorResponse"
- }
- }
- },
- "description": "Not authenticated."
- }
- },
- "summary": "Get the current identity",
- "tags": [
- "Auth"
- ],
- "x-fern-sdk-group-name": [
- "auth"
- ],
- "x-fern-sdk-method-name": "me"
- }
- },
"/api/v1/capabilities": {
"get": {
"description": "Report optional runtime capabilities available for this tenant.",
diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.json
index 54eb8d43d..f287be4ae 100644
--- a/packages/sdk/.fern/metadata.json
+++ b/packages/sdk/.fern/metadata.json
@@ -27,9 +27,10 @@
"streamType": "web",
"useDefaultRequestParameterValues": true
},
- "originGitCommit": "3c673adf5e6b96c84cd953498f10a3d42a6f948e",
+ "originGitCommit": "f9fa6c7fb2c1d3d394b36f57118c99c3cf755b8c",
"originGitCommitIsDirty": true,
- "invokedBy": "manual",
+ "invokedBy": "ci",
"requestedVersion": "0.0.0",
+ "ciProvider": "github",
"sdkVersion": "0.0.0"
}
diff --git a/packages/sdk/reference.md b/packages/sdk/reference.md
index a4665b2e2..4ea906ac7 100644
--- a/packages/sdk/reference.md
+++ b/packages/sdk/reference.md
@@ -313,61 +313,6 @@ await client.auth.logout();
</dl>
-</dd>
-</dl>
-</details>
-
-<details><summary><code>client.auth.<a href="/src/api/resources/auth/client/Client.ts">me</a>() -> TrueForge.AuthMeResponse</code></summary>
-<dl>
-<dd>
-
-#### πŸ“ Description
-
-<dl>
-<dd>
-
-<dl>
-<dd>
-
-Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.
-</dd>
-</dl>
-</dd>
-</dl>
-
-#### πŸ”Œ Usage
-
-<dl>
-<dd>
-
-<dl>
-<dd>
-
-```typescript
-await client.auth.me();
-
-```
-</dd>
-</dl>
-</dd>
-</dl>
-
-#### βš™οΈ Parameters
-
-<dl>
-<dd>
-
-<dl>
-<dd>
-
-**requestOptions:** `AuthClient.RequestOptions`
-
-</dd>
-</dl>
-</dd>
-</dl>
-
-
</dd>
</dl>
</details>
diff --git a/packages/sdk/src/api/resources/auth/client/Client.ts b/packages/sdk/src/api/resources/auth/client/Client.ts
index d00559e8c..d1ba6a25c 100644
--- a/packages/sdk/src/api/resources/auth/client/Client.ts
+++ b/packages/sdk/src/api/resources/auth/client/Client.ts
@@ -6,8 +6,6 @@ import { mergeHeaders } from "../../../../core/headers.js";
import * as core from "../../../../core/index.js";
import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
import * as errors from "../../../../errors/index.js";
-import * as serializers from "../../../../serialization/index.js";
-import * as TrueForge from "../../../index.js";
export declare namespace AuthClient {
export type Options = BaseClientOptions;
@@ -68,77 +66,4 @@ export class AuthClient {
return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/auth/logout");
}
-
- /**
- * Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.
- *
- * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
- *
- * @throws {@link TrueForge.UnauthorizedError}
- * @throws {@link errors.TrueForgeError}
- * @throws {@link errors.TrueForgeTimeoutError}
- *
- * @example
- * await client.auth.me()
- */
- public me(requestOptions?: AuthClient.RequestOptions): core.HttpResponsePromise<TrueForge.AuthMeResponse> {
- return core.HttpResponsePromise.fromPromise(this.__me(requestOptions));
- }
-
- private async __me(
- requestOptions?: AuthClient.RequestOptions,
- ): Promise<core.WithRawResponse<TrueForge.AuthMeResponse>> {
- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
- const _response = await (this._options.fetcher ?? core.fetcher)({
- url: core.url.join(
- (await core.Supplier.get(this._options.baseUrl)) ??
- (await core.Supplier.get(this._options.environment)),
- "api/v1/auth/me",
- ),
- method: "GET",
- headers: _headers,
- queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
- timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
- maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
- abortSignal: requestOptions?.abortSignal,
- fetchFn: this._options?.fetch,
- logging: this._options.logging,
- });
- if (_response.ok) {
- return {
- data: serializers.AuthMeResponse.parseOrThrow(_response.body, {
- unrecognizedObjectKeys: "passthrough",
- allowUnrecognizedUnionMembers: true,
- allowUnrecognizedEnumValues: true,
- skipValidation: true,
- breadcrumbsPrefix: ["response"],
- }),
- rawResponse: _response.rawResponse,
- };
- }
-
- if (_response.error.reason === "status-code") {
- switch (_response.error.statusCode) {
- case 401:
- throw new TrueForge.UnauthorizedError(
- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
- unrecognizedObjectKeys: "passthrough",
- allowUnrecognizedUnionMembers: true,
- allowUnrecognizedEnumValues: true,
- skipValidation: true,
- breadcrumbsPrefix: ["response"],
- }),
- _response.rawResponse,
- );
- default:
- throw new errors.TrueForgeError({
- statusCode: _response.error.statusCode,
- body: _response.error.body,
- rawResponse: _response.rawResponse,
- });
- }
- }
-
- return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/auth/me");
- }
}
diff --git a/packages/sdk/src/api/types/AuthMeResponse.ts b/packages/sdk/src/api/types/AuthMeResponse.ts
deleted file mode 100644
index c68ca9132..000000000
--- a/packages/sdk/src/api/types/AuthMeResponse.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// This file was auto-generated by Fern from our API Definition.
-
-import type * as TrueForge from "../index.js";
-
-export interface AuthMeResponse {
- role: TrueForge.AuthRole;
- userRef: string;
-}
diff --git a/packages/sdk/src/api/types/AuthRole.ts b/packages/sdk/src/api/types/AuthRole.ts
deleted file mode 100644
index 738757338..000000000
--- a/packages/sdk/src/api/types/AuthRole.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// This file was auto-generated by Fern from our API Definition.
-
-export const AuthRole = {
- Admin: "admin",
- User: "user",
-} as const;
-export type AuthRole = (typeof AuthRole)[keyof typeof AuthRole];
diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.ts
index e3c5ba184..a5bc9a0f8 100644
--- a/packages/sdk/src/api/types/index.ts
+++ b/packages/sdk/src/api/types/index.ts
@@ -11,8 +11,6 @@ export * from "./ApprovalAllow.js";
export * from "./ApprovalDecision.js";
export * from "./ApprovalDeny.js";
export * from "./AskUserQuestionsConfig.js";
-export * from "./AuthMeResponse.js";
-export * from "./AuthRole.js";
export * from "./BaseMcpAuthRequiredEvent.js";
export * from "./BaseThreadDoneEvent.js";
export * from "./CancelSessionResponse.js";
diff --git a/packages/sdk/src/serialization/types/AuthMeResponse.ts b/packages/sdk/src/serialization/types/AuthMeResponse.ts
deleted file mode 100644
index e47c5b9a5..000000000
--- a/packages/sdk/src/serialization/types/AuthMeResponse.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-// This file was auto-generated by Fern from our API Definition.
-
-import type * as TrueForge from "../../api/index.js";
-import * as core from "../../core/index.js";
-import type * as serializers from "../index.js";
-import { AuthRole } from "./AuthRole.js";
-
-export const AuthMeResponse: core.serialization.ObjectSchema<serializers.AuthMeResponse.Raw, TrueForge.AuthMeResponse> =
- core.serialization.object({
- role: AuthRole,
- userRef: core.serialization.property("user_ref", core.serialization.string()),
- });
-
-export declare namespace AuthMeResponse {
- export interface Raw {
- role: AuthRole.Raw;
- user_ref: string;
- }
-}
diff --git a/packages/sdk/src/serialization/types/AuthRole.ts b/packages/sdk/src/serialization/types/AuthRole.ts
deleted file mode 100644
index 9b64cbf46..000000000
--- a/packages/sdk/src/serialization/types/AuthRole.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// This file was auto-generated by Fern from our API Definition.
-
-import type * as TrueForge from "../../api/index.js";
-import * as core from "../../core/index.js";
-import type * as serializers from "../index.js";
-
-export const AuthRole: core.serialization.Schema<serializers.AuthRole.Raw, TrueForge.AuthRole> =
- core.serialization.enum_(["admin", "user"]);
-
-export declare namespace AuthRole {
- export type Raw = "admin" | "user";
-}
diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.ts
index e3c5ba184..a5bc9a0f8 100644
--- a/packages/sdk/src/serialization/types/index.ts
+++ b/packages/sdk/src/serialization/types/index.ts
@@ -11,8 +11,6 @@ export * from "./ApprovalAllow.js";
export * from "./ApprovalDecision.js";
export * from "./ApprovalDeny.js";
export * from "./AskUserQuestionsConfig.js";
-export * from "./AuthMeResponse.js";
-export * from "./AuthRole.js";
export * from "./BaseMcpAuthRequiredEvent.js";
export * from "./BaseThreadDoneEvent.js";
export * from "./CancelSessionResponse.js";
diff --git a/packages/sdk/tests/wire/auth.test.ts b/packages/sdk/tests/wire/auth.test.ts
index e7bed7104..064f26f16 100644
--- a/packages/sdk/tests/wire/auth.test.ts
+++ b/packages/sdk/tests/wire/auth.test.ts
@@ -1,6 +1,5 @@
// This file was auto-generated by Fern from our API Definition.
-import * as TrueForgeTypes from "../../src/api/index";
import { TrueForge } from "../../src/Client";
import { mockServerPool } from "../mock-server/MockServerPool";
@@ -14,32 +13,4 @@ describe("AuthClient", () => {
const response = await client.auth.logout();
expect(response).toEqual(undefined);
});
-
- test("me (1)", async () => {
- const server = mockServerPool.createServer();
- const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
-
- const rawResponseBody = { role: "admin", user_ref: "user_ref" };
-
- server.mockEndpoint().get("/api/v1/auth/me").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
-
- const response = await client.auth.me();
- expect(response).toEqual({
- role: "admin",
- userRef: "user_ref",
- });
- });
-
- test("me (2)", async () => {
- const server = mockServerPool.createServer();
- const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
-
- const rawResponseBody = { error: { message: "message" } };
-
- server.mockEndpoint().get("/api/v1/auth/me").respondWith().statusCode(401).jsonBody(rawResponseBody).build();
-
- await expect(async () => {
- return await client.auth.me();
- }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
- });
});
diff --git a/packages/server/package.json b/packages/server/package.json
index d72857162..7c5544752 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -42,6 +42,7 @@
"env-paths": "^4.0.0",
"hono": "^4.12.34",
"kysely": "^0.29.4",
+ "openid-client": "^6.8.4",
"pg": "^8.22.0",
"redis": "^5.10.0",
"ulid": "^3.0.2",
@@ -57,6 +58,7 @@
"@types/node": "^24.12.0",
"@types/pg": "^8.20.0",
"jest": "^29.7.0",
+ "jose": "^6.2.8",
"tsup": "^8.5.0",
"tsx": "^4.16.2",
"typescript": "^7.0.2"
diff --git a/packages/server/scripts/write-openapi.ts b/packages/server/scripts/write-openapi.ts
index 3b48e2804..1a2799035 100644
--- a/packages/server/scripts/write-openapi.ts
+++ b/packages/server/scripts/write-openapi.ts
@@ -65,6 +65,7 @@ const app = createServerApp({
requestReplyRouter: new RequestReplyRouter(),
eventSubscriptions: new EventSubscriptionRegistry<TurnStreamingEvent>(undefined),
logger: winston.createLogger({ silent: true }),
+ oidcClient: undefined,
});
const document = buildOpenApiDocument(app);
diff --git a/packages/server/src/apis/auth.ts b/packages/server/src/apis/auth.ts
index 4ee25fe77..b651db5ed 100644
--- a/packages/server/src/apis/auth.ts
+++ b/packages/server/src/apis/auth.ts
@@ -1,51 +1,73 @@
-/**
- * Auth API (mounted at /api/v1/auth).
- *
- * For the no-identity-provider (local/single-binary) case,
- * `/me` always succeeds with a fixed local identity.
- */
import { OpenAPIHono } from '@hono/zod-openapi';
-import { isOidcConfigured } from '../config';
-import { authLoginRoute, authLogoutRoute, authMeRoute, oAuthCallbackRoute } from '../routes/authRoutes';
-import type { AuthMeResponse } from '../schemas/auth';
+import type { Configuration } from 'openid-client';
+import type { Logger } from 'winston';
+import { clearAuthCookie, ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, readOAuthStateCookie } from '../auth/cookies';
+import { buildLoginAuthorization, exchangeAuthorizationCode, safeReturnTo } from '../auth/oidc';
+import { authLoginRoute, authLogoutRoute, oAuthCallbackRoute } from '../routes/authRoutes';
-/** Fixed identity used when no identity provider is configured. */
-const LOCAL_USER: AuthMeResponse = {
- user_ref: 'trueforge-default',
- role: 'admin',
-};
+const LOGIN_ERROR_PATH = '/?error=login_failed';
-export function createAuthRouter() {
+export function createAuthRouter(params: { oidcClient: Configuration | undefined; logger: Logger }) {
const router = new OpenAPIHono();
- router.openapi(authLoginRoute, c => {
- if (!isOidcConfigured()) {
+ router.openapi(authLoginRoute, async c => {
+ // TODO: remove this checks once the middleware is implemented
+ if (!params.oidcClient) {
return c.redirect('/', 302);
}
- // TODO: Implement the actual login redirect to the identity provider.
- return c.redirect('/', 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', {
+ error: error instanceof Error ? error.message : error,
+ });
+ return c.redirect(LOGIN_ERROR_PATH, 302);
+ }
});
- router.openapi(oAuthCallbackRoute, c => {
- if (!isOidcConfigured()) {
+ router.openapi(oAuthCallbackRoute, async c => {
+ if (!params.oidcClient) {
return c.redirect('/', 302);
}
- // TODO: Implement the actual OIDC callback (code exchange, session cookie).
- return c.redirect('/', 302);
+
+ const query = c.req.valid('query');
+ const pending = readOAuthStateCookie({ context: c, logger: params.logger });
+ clearAuthCookie({ context: c, name: OAUTH_STATE_COOKIE });
+
+ if (pending?.state !== query.state || query.error || !query.code) {
+ // TODO: handle the error here once frontend error page is implemented
+ return c.redirect(LOGIN_ERROR_PATH, 302);
+ }
+
+ try {
+ await exchangeAuthorizationCode({
+ context: c,
+ client: params.oidcClient,
+ callbackParams: new URL(c.req.url).searchParams,
+ codeVerifier: pending.code_verifier,
+ state: pending.state,
+ });
+ return c.redirect(safeReturnTo(pending.return_to), 302);
+ } catch (error) {
+ params.logger.error('Failed to exchange authorization code', {
+ error: error instanceof Error ? error.message : error,
+ });
+ // TODO: handle the error here once frontend error page is implemented
+ return c.redirect(LOGIN_ERROR_PATH, 302);
+ }
});
router.openapi(authLogoutRoute, c => {
- // No real session in either mode yet β€” always a no-op.
+ // Cookie deletion is idempotent, so logout also succeeds when no cookie exists.
+ clearAuthCookie({ context: c, name: ID_TOKEN_COOKIE });
return c.body(null, 204);
});
- router.openapi(authMeRoute, c => {
- if (!isOidcConfigured()) {
- return c.json(LOCAL_USER, 200);
- }
- // TODO: Resolve the caller's verified identity from their session cookie.
- return c.json({ error: { message: 'Not authenticated' } }, 401);
- });
-
return router;
}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index c19e16f1a..2e68e5c88 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -5,6 +5,7 @@ import type { ISessionStore, Sessions, TurnStreamingEvent } from '@truefoundry/u
import type { RequestReplyRouter } from '@truefoundry/utils-core/request-reply';
import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
+import type { Configuration } from 'openid-client';
import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
import { createAgentsRouter } from './apis/agents';
@@ -70,6 +71,8 @@ export interface ServerDeps {
/** Hands out each turn's resumable event stream to the create and subscribe handlers. */
eventSubscriptions: EventSubscriptionRegistry<TurnStreamingEvent>;
logger: Logger;
+ /** Discovered openid-client configuration; undefined when browser login is disabled. */
+ oidcClient: Configuration | undefined;
}
export function createServerApp(deps: ServerDeps) {
@@ -77,7 +80,7 @@ export function createServerApp(deps: ServerDeps) {
app.get('/healthz', c => c.text('OK!'));
- app.route('/api/v1/auth', createAuthRouter());
+ app.route('/api/v1/auth', createAuthRouter({ oidcClient: deps.oidcClient, logger: deps.logger }));
app.route('/api/v1/capabilities', createCapabilitiesRouter({ sandboxProviderStore: deps.sandboxProviderStore }));
app.route('/api/v1/models', createModelsRouter(deps.modelProviderStore));
app.route(
diff --git a/packages/server/src/auth/cookies.ts b/packages/server/src/auth/cookies.ts
new file mode 100644
index 000000000..a7bf79373
--- /dev/null
+++ b/packages/server/src/auth/cookies.ts
@@ -0,0 +1,55 @@
+import type { Context } from 'hono';
+import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
+import type { Logger } from 'winston';
+import { z } from 'zod';
+import configuration from '../config';
+
+export const OAUTH_STATE_COOKIE = 'oauth_state';
+export const ID_TOKEN_COOKIE = 'id_token';
+
+const OAuthStateSchema = z.object({
+ state: z.string(),
+ code_verifier: z.string(),
+ return_to: z.string(),
+});
+
+export type OAuthState = z.infer<typeof OAuthStateSchema>;
+
+const AUTH_COOKIE_ATTRIBUTES = {
+ httpOnly: true,
+ sameSite: 'Lax' as const,
+ secure: configuration.PUBLIC_BASE_URL.startsWith('https://'),
+ path: '/',
+};
+
+export function setAuthCookie(params: { context: Context; name: string; value: string; maxAgeSeconds: number }): void {
+ setCookie(params.context, params.name, params.value, {
+ ...AUTH_COOKIE_ATTRIBUTES,
+ maxAge: params.maxAgeSeconds,
+ });
+}
+
+export function readOAuthStateCookie(params: { context: Context; logger: Logger }): OAuthState | undefined {
+ const raw = getCookie(params.context, OAUTH_STATE_COOKIE);
+ if (!raw) {
+ return undefined;
+ }
+ try {
+ // JSON.parse throws SyntaxError when the cookie value is not JSON.
+ const result = OAuthStateSchema.safeParse(JSON.parse(raw));
+ if (!result.success) {
+ params.logger.warn('oauth_state cookie failed schema validation', { error: result.error.message });
+ return undefined;
+ }
+ return result.data;
+ } catch (error) {
+ params.logger.warn('oauth_state cookie is not valid JSON', {
+ error: error instanceof Error ? error.message : error,
+ });
+ return undefined;
+ }
+}
+
+export function clearAuthCookie(params: { context: Context; name: string }): void {
+ deleteCookie(params.context, params.name, AUTH_COOKIE_ATTRIBUTES);
+}
diff --git a/packages/server/src/auth/oidc.ts b/packages/server/src/auth/oidc.ts
new file mode 100644
index 000000000..75961c5dc
--- /dev/null
+++ b/packages/server/src/auth/oidc.ts
@@ -0,0 +1,101 @@
+import type { Context } from 'hono';
+import {
+ authorizationCodeGrant,
+ buildAuthorizationUrl,
+ calculatePKCECodeChallenge,
+ type Configuration,
+ discovery,
+ randomPKCECodeVerifier,
+ randomState,
+} from 'openid-client';
+import configuration, { type OIDCConfig } from '../config';
+import { ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, setAuthCookie } from './cookies';
+
+const CALLBACK_PATH = '/api/v1/auth/callback';
+const OAUTH_STATE_MAX_AGE_SECONDS = 10 * 60;
+const ID_TOKEN_COOKIE_MAX_AGE_SECONDS = 24 * 60 * 60;
+// TODO: use dynamic claims/scopes when we add RBAC
+const OIDC_SCOPES = 'openid email profile';
+
+/** Discover the IdP once at process startup when OIDC is configured. */
+export async function initOidc(oidc: OIDCConfig | undefined): Promise<Configuration | undefined> {
+ if (!oidc) {
+ return undefined;
+ }
+
+ return discovery(new URL(oidc.OIDC_ISSUER_URL), oidc.OIDC_CLIENT_ID, oidc.OIDC_CLIENT_SECRET);
+}
+
+function authCallbackUrl(): string {
+ return `${configuration.PUBLIC_BASE_URL}${CALLBACK_PATH}`;
+}
+
+/**
+ * Same-origin relative path only.
+ * - starts with `/`
+ * - not `//…` (open redirect)
+ * - not `/api` or `/api/…`
+ */
+const SAFE_RETURN_TO = /^\/(?!\/|api(?:\/|$)).*/;
+
+export function safeReturnTo(value: string | undefined): string {
+ if (value && SAFE_RETURN_TO.test(value)) {
+ return value;
+ }
+ return '/';
+}
+
+export async function buildLoginAuthorization(params: {
+ context: Context;
+ client: Configuration;
+ returnTo: string | undefined;
+}): Promise<string> {
+ const returnTo = safeReturnTo(params.returnTo);
+ const codeVerifier = randomPKCECodeVerifier();
+ const state = randomState();
+ const authorizationUrl = buildAuthorizationUrl(params.client, {
+ redirect_uri: authCallbackUrl(),
+ scope: OIDC_SCOPES,
+ code_challenge: await calculatePKCECodeChallenge(codeVerifier),
+ code_challenge_method: 'S256',
+ state,
+ });
+ setAuthCookie({
+ context: params.context,
+ name: OAUTH_STATE_COOKIE,
+ value: JSON.stringify({
+ state,
+ code_verifier: codeVerifier,
+ return_to: returnTo,
+ }),
+ maxAgeSeconds: OAUTH_STATE_MAX_AGE_SECONDS,
+ });
+ return authorizationUrl.href;
+}
+
+export async function exchangeAuthorizationCode(params: {
+ context: Context;
+ client: Configuration;
+ /** Whole IdP response query: openid-client validates `state`, `error` and `iss` from it. */
+ callbackParams: URLSearchParams;
+ codeVerifier: string;
+ state: string;
+}): Promise<void> {
+ // Origin and path come from config so redirect_uri matches the one registered with the IdP.
+ const callbackUrl = new URL(authCallbackUrl());
+ callbackUrl.search = params.callbackParams.toString();
+ const tokens = await authorizationCodeGrant(params.client, callbackUrl, {
+ pkceCodeVerifier: params.codeVerifier,
+ expectedState: params.state,
+ });
+ const idToken = tokens.id_token;
+ if (!idToken) {
+ throw new Error('Token response missing id_token');
+ }
+ setAuthCookie({
+ context: params.context,
+ name: ID_TOKEN_COOKIE,
+ value: idToken,
+ maxAgeSeconds: ID_TOKEN_COOKIE_MAX_AGE_SECONDS,
+ });
+}
diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts
index da273474c..60931d34f 100644
--- a/packages/server/src/config.ts
+++ b/packages/server/src/config.ts
@@ -409,8 +409,7 @@ export type DistributedServerConfiguration = SharedServerConfiguration & {
REDIS_URL: string;
/**
* OIDC configuration for server authentication.
- * Undefined = every request resolves to a fixed
- * local admin identity instead of a real IdP session.
+ * Undefined means browser login is disabled.
*/
OIDC: OIDCConfig | undefined;
};
@@ -534,9 +533,10 @@ const configuration: ServerConfiguration = standalone
OIDC: resolveOIDCConfig(),
};
-/** True when a real identity provider is configured */
-export function isOidcConfigured(): boolean {
- return !configuration.STANDALONE && configuration.OIDC !== undefined;
+export function isOidcConfigured(
+ value: ServerConfiguration,
+): value is DistributedServerConfiguration & { OIDC: OIDCConfig } {
+ return !value.STANDALONE && value.OIDC !== undefined;
}
export default configuration;
diff --git a/packages/server/src/main.ts b/packages/server/src/main.ts
index b4c45ded7..35d2612ac 100644
--- a/packages/server/src/main.ts
+++ b/packages/server/src/main.ts
@@ -13,9 +13,10 @@ import { mkdir } from 'node:fs/promises';
import path from 'node:path';
let configuration: typeof import('./config').default;
+let isOidcConfigured: typeof import('./config').isOidcConfigured;
try {
- ({ default: configuration } = await import('./config'));
+ ({ default: configuration, isOidcConfigured } = await import('./config'));
} catch (error) {
console.error(
'Failed to start server: Failed to load configuration:',
@@ -36,6 +37,7 @@ import type { RedisClientType } from 'redis';
import winston, { type Logger } from 'winston';
import { createServerApp } from './app';
+import { initOidc } from './auth/oidc';
import { McpCatalog } from './catalog/McpCatalog';
import { ModelCatalog } from './catalog/ModelCatalog';
import { SandboxCatalog } from './catalog/SandboxCatalog';
@@ -200,6 +202,14 @@ try {
const requestReplyRouter = new RequestReplyRouter();
const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(redis);
+ const oidc = isOidcConfigured(configuration) ? configuration.OIDC : undefined;
+ if (oidc) {
+ logger.info('OIDC is configured', { issuer: oidc.OIDC_ISSUER_URL });
+ } else {
+ logger.warn('OIDC is not configured; browser login is disabled');
+ }
+ const oidcClient = await initOidc(oidc);
+
const app = createServerApp({
modelCatalog: ModelCatalog.load(),
mcpCatalog: McpCatalog.load(),
@@ -218,6 +228,7 @@ try {
requestReplyRouter,
eventSubscriptions,
logger,
+ oidcClient,
});
if (mountFrontend(app, configuration.FRONTEND_DIR)) {
diff --git a/packages/server/src/routes/authRoutes.ts b/packages/server/src/routes/authRoutes.ts
index 00d0fdbed..d237ef9ce 100644
--- a/packages/server/src/routes/authRoutes.ts
+++ b/packages/server/src/routes/authRoutes.ts
@@ -3,12 +3,10 @@
*
* `login`/`callback` are browser-redirect targets, never called by SDK
* consumers β€” both carry `x-fern-ignore`, the same convention used for the
- * MCP OAuth callback in mcpOAuthRoutes.ts. `me`/`logout` are real JSON
- * endpoints and generate normally.
+ * MCP OAuth callback in mcpOAuthRoutes.ts. `logout` generates normally.
*/
import { createRoute } from '@hono/zod-openapi';
-import { AuthLoginQuerySchema, AuthMeResponseSchema, OAuthCallbackQuerySchema } from '../schemas/auth';
-import { RequestErrorResponseSchema } from '../schemas/errors';
+import { AuthLoginQuerySchema, OAuthCallbackQuerySchema } from '../schemas/auth';
const AUTH_TAG = 'Auth';
@@ -38,7 +36,7 @@ export const oAuthCallbackRoute = createRoute({
'x-fern-ignore': true,
request: { query: OAuthCallbackQuerySchema },
responses: {
- 302: { description: 'Redirect back into the app on success, or to /login?error=... on failure.' },
+ 302: { description: 'Redirect back into the app on success, or to /?error=login_failed on failure.' },
},
});
@@ -56,24 +54,3 @@ export const authLogoutRoute = createRoute({
204: { description: 'Session cookie cleared.' },
},
});
-
-export const authMeRoute = createRoute({
- method: 'get',
- path: '/me',
- tags: [AUTH_TAG],
- summary: 'Get the current identity',
- description:
- "Returns the fixed local identity in local/single-binary mode; otherwise the caller's verified identity.",
- 'x-fern-sdk-group-name': ['auth'],
- 'x-fern-sdk-method-name': 'me',
- responses: {
- 200: {
- content: { 'application/json': { schema: AuthMeResponseSchema } },
- description: "The caller's identity.",
- },
- 401: {
- content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Not authenticated.',
- },
- },
-});
diff --git a/packages/server/src/schemas/auth.ts b/packages/server/src/schemas/auth.ts
index f243ec248..94b903ca2 100644
--- a/packages/server/src/schemas/auth.ts
+++ b/packages/server/src/schemas/auth.ts
@@ -1,17 +1,6 @@
/** Auth wire schemas. */
import { z } from '@hono/zod-openapi';
-export const AuthRoleSchema = z.enum(['admin', 'user']).openapi('AuthRole');
-
-export const AuthMeResponseSchema = z
- .object({
- user_ref: z.string(),
- role: AuthRoleSchema,
- })
- .openapi('AuthMeResponse');
-
-export type AuthMeResponse = z.infer<typeof AuthMeResponseSchema>;
-
export const AuthLoginQuerySchema = z.object({
return_to: z
.string()
diff --git a/packages/server/tests/unit/apis/auth.test.ts b/packages/server/tests/unit/apis/auth.test.ts
index bb05fa4f5..171703736 100644
--- a/packages/server/tests/unit/apis/auth.test.ts
+++ b/packages/server/tests/unit/apis/auth.test.ts
@@ -1,20 +1,47 @@
+import { exportJWK, generateKeyPair, type JWK, SignJWT } from 'jose';
+import { createHash } from 'node:crypto';
+import type { Configuration } from 'openid-client';
+import winston from 'winston';
import { createAuthRouter } from '../../../src/apis/auth';
+import { initOidc } from '../../../src/auth/oidc';
+import configuration from '../../../src/config';
-describe('auth router (no identity provider configured)', () => {
- it('GET /me returns the fixed local identity', async () => {
- const router = createAuthRouter();
+jest.mock('../../../src/config', () => {
+ const OIDC = {
+ OIDC_ISSUER_URL: 'https://issuer.example.com/',
+ OIDC_CLIENT_ID: 'harness-client',
+ OIDC_CLIENT_SECRET: 'harness-secret',
+ OIDC_USER_REFERENCE_CLAIM: 'sub',
+ OIDC_USER_ROLE_CLAIM: 'groups',
+ OIDC_ADMIN_ROLE_VALUE: 'admin',
+ };
+ return {
+ __esModule: true,
+ default: {
+ STANDALONE: false,
+ PUBLIC_BASE_URL: 'https://harness.example.com',
+ OIDC,
+ PORT: 8790,
+ },
+ };
+});
- const res = await router.request('/me');
+if (configuration.STANDALONE || !configuration.OIDC) {
+ throw new Error('OIDC test configuration is missing');
+}
- expect(res.status).toBe(200);
- expect(await res.json()).toEqual({
- user_ref: 'trueforge-default',
- role: 'admin',
- });
- });
+const ISSUER = 'https://issuer.example.com';
+const CLIENT_ID = 'harness-client';
+const STATE_COOKIE = 'oauth_state';
+const ID_TOKEN_COOKIE = 'id_token';
+const configuredOidc = configuration.OIDC;
+const logger = winston.createLogger({ silent: true });
+
+const ACCESS_TOKEN = 'access-1';
+describe('auth router (no identity provider configured)', () => {
it('GET /login redirects home β€” there is nothing to log into', async () => {
- const router = createAuthRouter();
+ const router = createAuthRouter({ oidcClient: undefined, logger });
const res = await router.request('/login', { redirect: 'manual' });
@@ -23,7 +50,7 @@ describe('auth router (no identity provider configured)', () => {
});
it('GET /callback redirects home β€” there is nothing to complete', async () => {
- const router = createAuthRouter();
+ const router = createAuthRouter({ oidcClient: undefined, logger });
const res = await router.request('/callback?state=abc', { redirect: 'manual' });
@@ -32,10 +59,159 @@ describe('auth router (no identity provider configured)', () => {
});
it('POST /logout is a no-op 204 β€” there is no real session to clear', async () => {
- const router = createAuthRouter();
+ const router = createAuthRouter({ oidcClient: undefined, logger });
const res = await router.request('/logout', { method: 'POST' });
expect(res.status).toBe(204);
});
});
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function setCookies(res: Response): string[] {
+ return res.headers.getSetCookie();
+}
+
+function cookieValue(cookies: string[], name: string): string | undefined {
+ const prefix = `${name}=`;
+ for (const entry of cookies) {
+ const first = entry.split(';')[0];
+ if (first?.startsWith(prefix)) {
+ return first.slice(prefix.length);
+ }
+ }
+ return undefined;
+}
+
+describe('auth router (OIDC configured)', () => {
+ const realFetch = globalThis.fetch;
+ let privateKey: Awaited<ReturnType<typeof generateKeyPair>>['privateKey'];
+ let publicJwk: JWK;
+ let oidcClient: Configuration;
+
+ beforeAll(async () => {
+ const keyPair = await generateKeyPair('RS256');
+ privateKey = keyPair.privateKey;
+ publicJwk = await exportJWK(keyPair.publicKey);
+ publicJwk.kid = 'test-kid';
+ publicJwk.alg = 'RS256';
+ publicJwk.use = 'sig';
+ });
+
+ beforeEach(async () => {
+ stubOidcFetch();
+ const client = await initOidc(configuredOidc);
+ if (!client) {
+ throw new Error('OIDC client was not initialized');
+ }
+ oidcClient = client;
+ });
+
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ });
+
+ async function createIdToken(): Promise<string> {
+ const digest = createHash('sha256').update(ACCESS_TOKEN).digest();
+ return new SignJWT({
+ email: '[email protected]',
+ at_hash: digest.subarray(0, digest.length / 2).toString('base64url'),
+ })
+ .setProtectedHeader({ alg: 'RS256', kid: 'test-kid' })
+ .setIssuer(ISSUER)
+ .setAudience(CLIENT_ID)
+ .setSubject('user-1')
+ .setIssuedAt()
+ .setExpirationTime('48h')
+ .sign(privateKey);
+ }
+
+ function stubOidcFetch(): void {
+ const fetchStub: typeof fetch = async (input, init) => {
+ const url = String(input);
+
+ if (url === `${ISSUER}/.well-known/openid-configuration`) {
+ return json({
+ issuer: ISSUER,
+ authorization_endpoint: `${ISSUER}/authorize`,
+ token_endpoint: `${ISSUER}/token`,
+ jwks_uri: `${ISSUER}/jwks`,
+ response_types_supported: ['code'],
+ code_challenge_methods_supported: ['S256'],
+ grant_types_supported: ['authorization_code'],
+ token_endpoint_auth_methods_supported: ['client_secret_post'],
+ id_token_signing_alg_values_supported: ['RS256'],
+ subject_types_supported: ['public'],
+ authorization_response_iss_parameter_supported: true,
+ });
+ }
+
+ if (url === `${ISSUER}/jwks`) {
+ return json({ keys: [publicJwk] });
+ }
+
+ if (url === `${ISSUER}/token` && init?.method === 'POST') {
+ return json({
+ access_token: ACCESS_TOKEN,
+ id_token: await createIdToken(),
+ token_type: 'Bearer',
+ expires_in: 3600,
+ });
+ }
+
+ return new Response(`unexpected url: ${url}`, { status: 404 });
+ };
+ globalThis.fetch = fetchStub;
+ }
+
+ it('GET /login redirects to the IdP and stores state', async () => {
+ const res = await createAuthRouter({ oidcClient, logger }).request('/login?return_to=/sessions/abc123', {
+ redirect: 'manual',
+ });
+
+ expect(res.status).toBe(302);
+ const location = res.headers.get('location') ?? '';
+ const authUrl = new URL(location);
+ expect(authUrl.origin + authUrl.pathname).toBe(`${ISSUER}/authorize`);
+ expect(authUrl.searchParams.get('client_id')).toBe(CLIENT_ID);
+ expect(authUrl.searchParams.get('redirect_uri')).toBe('https://harness.example.com/api/v1/auth/callback');
+ expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');
+ expect(cookieValue(setCookies(res), STATE_COOKIE)).toBeTruthy();
+ });
+
+ // `iss` is forwarded verbatim: IdPs advertising it reject an exchange that drops it.
+ it('GET /callback exchanges the code and sets id_token', async () => {
+ const router = createAuthRouter({ oidcClient, logger });
+ const loginRes = await router.request('/login?return_to=/sessions/abc123', { redirect: 'manual' });
+ const stateCookieRaw = cookieValue(setCookies(loginRes), STATE_COOKIE) ?? '';
+ const authorizationUrl = new URL(loginRes.headers.get('location') ?? '');
+ const state = authorizationUrl.searchParams.get('state') ?? '';
+
+ const callbackRes = await router.request(`/callback?code=abc123&state=${state}&iss=${encodeURIComponent(ISSUER)}`, {
+ redirect: 'manual',
+ headers: { Cookie: `${STATE_COOKIE}=${stateCookieRaw}` },
+ });
+
+ expect(callbackRes.status).toBe(302);
+ expect(callbackRes.headers.get('location')).toBe('/sessions/abc123');
+ const idTokenCookie = setCookies(callbackRes).find(cookie => cookie.startsWith(`${ID_TOKEN_COOKIE}=`));
+ expect(idTokenCookie).toContain('Max-Age=86400');
+ });
+
+ it('POST /logout clears id_token even when no cookie is present', async () => {
+ const res = await createAuthRouter({ oidcClient, logger }).request('/logout', {
+ method: 'POST',
+ });
+
+ expect(res.status).toBe(204);
+ expect(
+ setCookies(res).some(cookie => cookie.startsWith(`${ID_TOKEN_COOKIE}=`) && cookie.includes('Max-Age=0')),
+ ).toBe(true);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f3e815d85..2a05bd6ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -233,6 +233,9 @@ importers:
kysely:
specifier: ^0.29.4
version: 0.29.4
+ openid-client:
+ specifier: ^6.8.4
+ version: 6.8.4
pg:
specifier: ^8.22.0
version: 8.22.0
@@ -273,6 +276,9 @@ importers:
jest:
specifier: ^29.7.0
+ jose:
+ specifier: ^6.2.8
+ version: 6.2.8
tsup:
specifier: ^8.5.0
@@ -5054,8 +5060,8 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
- resolution: {integrity: sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==}
+ resolution: {integrity: sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ==}
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
@@ -5593,6 +5599,9 @@ packages:
resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==}
+ resolution: {integrity: sha512-iwemM91xz8nryHti2yTmg5fhyEMVOkOXwHNqbvcATjyajb5oQxCQzrNOA6uElRHuMhQQTKUyFKV9y/CNyg25BQ==}
+
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
@@ -5647,6 +5656,9 @@ packages:
resolution: {integrity: sha512-a4sfn6L2sIShhtzJqmjGrARvxAW/3F2BJDdyRVvNF9VhAsZSh5hSyI3a9TNvmzBxXmq66nY5LNT5bQcBxYAZZg==}
+ resolution: {integrity: sha512-QSw0BA08piujetEwfZsHoTrDpMEha7GDZDicQqVwX4u0ChCjefvjDB++TZ8BTg76UpwhzIQgdvvfgfl3HpCSAw==}
+
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@@ -8216,7 +8228,7 @@ snapshots:
express: 5.2.1([email protected])
hono: 4.13.0
- jose: 6.2.4
+ jose: 6.2.8
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
raw-body: 3.0.2
@@ -12118,7 +12130,7 @@ snapshots:
@@ -12841,6 +12853,8 @@ snapshots:
+
@@ -12878,6 +12892,11 @@ snapshots:
dependencies:
yaml: 2.9.0
+ dependencies:
+ jose: 6.2.8
+ oauth4webapi: 3.8.6
+
dependencies:
deep-is: 0.1.4