🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(auth): read custom OIDC profile from the userinfo endpoint (#16607)
Steffen Schmitz40922fa36271
diff --git a/.env.prod.example b/.env.prod.exampleindex f960160e90..b2da902036 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -142,6 +142,7 @@ OTEL_SERVICE_NAME="langfuse"# AUTH_CUSTOM_CLIENT_AUTH_METHOD="client_secret_basic" # optional# AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING=false# AUTH_CUSTOM_ID_TOKEN=false # optional, default is true+# AUTH_CUSTOM_FETCH_USERINFO=true # optional, default is false. Read the profile from the userinfo endpoint if your IdP omits email/name from the ID token.# AUTH_CUSTOM_CLIENT_AUTH_METHOD=# AUTH_CUSTOM_CHECKS=# AUTH_CUSTOM_ID_TOKEN_SIGNED_RESPONSE_ALG=diff --git a/packages/shared/src/server/auth/customSsoProvider.test.ts b/packages/shared/src/server/auth/customSsoProvider.test.tsnew file mode 100644index 0000000000..a9bfc62420--- /dev/null+++ b/packages/shared/src/server/auth/customSsoProvider.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it, vi } from "vitest";++// The provider reads the claim-name overrides at import time; stub the env so+// this stays a unit test with the documented defaults.+vi.mock("../../env", () => ({+ env: {+ LANGFUSE_CUSTOM_SSO_EMAIL_CLAIM: "email",+ LANGFUSE_CUSTOM_SSO_NAME_CLAIM: "name",+ LANGFUSE_CUSTOM_SSO_SUB_CLAIM: "sub",+ LANGFUSE_CUSTOM_SSO_IMAGE_CLAIM: "picture",+ },+}));++import { CustomSSOProvider } from "./customSsoProvider";++const baseOptions = {+ clientId: "client-id",+ clientSecret: "client-secret",+ issuer: "https://idp.example.com/oidc",+};++// An IdP that keeps `email`/`name` out of the ID token and only serves them+// from the userinfo endpoint, e.g. Oracle IAM.+const idTokenClaims = { sub: "user-1", iss: baseOptions.issuer };+const userinfoResponse = {+ sub: "user-1",+ email: "[email protected]",+ name: "Some User",+};++function fakeTokenSet(+ overrides: {+ id_token?: string;+ claims?: () => Record<string, unknown>;+ } = {},+) {+ return {+ id_token: "signed.id.token" as string | undefined,+ access_token: "access-token",+ claims: () => idTokenClaims as Record<string, unknown>,+ ...overrides,+ };+}++/** Invokes the provider's `userinfo.request` handler with a stubbed client. */+async function requestProfile(+ provider: ReturnType<typeof CustomSSOProvider>,+ tokens: ReturnType<typeof fakeTokenSet>,+ userinfo: ReturnType<typeof vi.fn> = vi.fn(async () => userinfoResponse),+) {+ const handler = provider.userinfo;+ if (!handler || typeof handler === "string" || !handler.request) {+ throw new Error("provider does not fetch the profile from userinfo");+ }+ const profile = await handler.request({+ client: { userinfo } as any,+ tokens: tokens as any,+ provider: provider as any,+ });+ return { profile, userinfo };+}++describe("CustomSSOProvider", () => {+ it("reads the profile from the ID token claims by default", () => {+ expect(CustomSSOProvider(baseOptions).userinfo).toBeUndefined();+ });++ it("sources the profile from the userinfo endpoint when fetchUserInfo is set", async () => {+ const provider = CustomSSOProvider({ ...baseOptions, fetchUserInfo: true });++ const tokens = fakeTokenSet();+ const { profile, userinfo } = await requestProfile(provider, tokens);++ // Called with the whole token set so openid-client checks the userinfo+ // `sub` against the ID token's.+ expect(userinfo).toHaveBeenCalledWith(tokens);+ // Claims the ID token does not carry are picked up from userinfo.+ expect(provider.profile(profile as any, tokens as any)).toMatchObject({+ id: "user-1",+ email: "[email protected]",+ name: "Some User",+ });+ });++ it("keeps ID token claims that userinfo omits", async () => {+ const provider = CustomSSOProvider({ ...baseOptions, fetchUserInfo: true });++ const { profile } = await requestProfile(+ provider,+ fakeTokenSet(),+ vi.fn(async () => ({ sub: "user-1", email: "[email protected]" })),+ );++ expect(profile).toMatchObject({+ sub: "user-1",+ iss: baseOptions.issuer,+ email: "[email protected]",+ });+ });++ it("does not read ID token claims when the token response has none", async () => {+ const provider = CustomSSOProvider({ ...baseOptions, fetchUserInfo: true });++ // openid-client throws on `claims()` without an id_token, so it must not+ // be called on the plain OAuth2 path.+ const claims = vi.fn(() => {+ throw new Error("id_token not present in TokenSet");+ });++ const { profile } = await requestProfile(+ provider,+ fakeTokenSet({ id_token: undefined, claims }),+ );++ expect(claims).not.toHaveBeenCalled();+ expect(profile).toMatchObject({ email: "[email protected]" });+ });++ it("leaves the token exchange untouched and keeps fetchUserInfo out of the NextAuth options", () => {+ const provider = CustomSSOProvider({+ ...baseOptions,+ idToken: true,+ fetchUserInfo: true,+ });++ // `idToken: true` keeps NextAuth on client.callback(), which is the only+ // callback openid-client accepts once the token response has an id_token.+ expect(provider.options).toMatchObject({ idToken: true });+ expect(provider.options).not.toHaveProperty("fetchUserInfo");+ });+});diff --git a/packages/shared/src/server/auth/customSsoProvider.ts b/packages/shared/src/server/auth/customSsoProvider.tsindex 61e5f4419c..057e17308d 100644--- a/packages/shared/src/server/auth/customSsoProvider.ts+++ b/packages/shared/src/server/auth/customSsoProvider.ts@@ -1,4 +1,8 @@-import type { OAuthConfig, OAuthUserConfig } from "next-auth/providers/oauth";+import type {+ OAuthConfig,+ OAuthUserConfig,+ UserinfoEndpointHandler,+} from "next-auth/providers/oauth";import { env } from "../../env";const CUSTOM_EMAIL_CLAIM = env.LANGFUSE_CUSTOM_SSO_EMAIL_CLAIM;@@ -13,9 +17,51 @@ interface CustomSSOUser extends Record<string, any> {verified: boolean;}+export type CustomSSOProviderOptions<P> = OAuthUserConfig<P> & {+ /**+ * Read the profile from the IdP's userinfo endpoint instead of from the ID+ * token claims, while keeping the OIDC callback (`client.callback()`).+ *+ * Needed for IdPs that do not put `email`/`name` into the ID token. Turning+ * `idToken` off is not an alternative there: `openid-client` refuses the+ * plain OAuth2 callback ("id_token detected in the response, you must use+ * client.callback() instead of client.oauthCallback()") as soon as the token+ * response carries an `id_token`, which any provider returns for an `openid`+ * scope.+ */+ fetchUserInfo?: boolean;+};++/**+ * NextAuth prefers `userinfo.request` over the ID token claims when building+ * the profile, so this only moves the profile source and leaves the token+ * exchange (and thus ID token signature validation) untouched.+ */+const userinfoEndpointProfile: UserinfoEndpointHandler = {+ async request({ client, tokens }) {+ // NextAuth types `tokens` as plain token parameters, the value it passes is+ // an openid-client TokenSet.+ const tokenSet = tokens as typeof tokens & {+ claims: () => Record<string, unknown>;+ };+ // Merge so claims that only the ID token carries (typically `sub`) survive;+ // userinfo wins on conflicts. `openid-client` verifies that the userinfo+ // `sub` matches the one in the ID token.+ const idTokenClaims = tokenSet.id_token ? tokenSet.claims() : {};+ const userinfo = await client.userinfo(+ tokenSet as unknown as Parameters<typeof client.userinfo>[0],+ );+ return { ...idTokenClaims, ...userinfo };+ },+};+export function CustomSSOProvider<P extends CustomSSOUser>(- options: OAuthUserConfig<P>,+ options: CustomSSOProviderOptions<P>,): OAuthConfig<P> {+ // Keep `fetchUserInfo` out of the options that NextAuth merges into the+ // provider config, it is not part of the NextAuth provider contract.+ const { fetchUserInfo, ...oauthOptions } = options;+return {id: "custom",name: "CustomSSOProvider",@@ -23,6 +69,7 @@ export function CustomSSOProvider<P extends CustomSSOUser>(wellKnown: `${options.issuer}/.well-known/openid-configuration`,authorization: { params: { scope: "openid email profile" } }, // overridden by options.authorization to be able to set custom scopes, deep merged with this defaultchecks: ["pkce", "state"],+ ...(fetchUserInfo ? { userinfo: userinfoEndpointProfile } : {}),profile(profile) {const image = profile[CUSTOM_IMAGE_CLAIM];return {@@ -32,6 +79,6 @@ export function CustomSSOProvider<P extends CustomSSOUser>(image: typeof image === "string" && image.length > 0 ? image : null,};},- options,+ options: oauthOptions,};}diff --git a/web/src/ee/features/multi-tenant-sso/types.ts b/web/src/ee/features/multi-tenant-sso/types.tsindex b191abf993..370794f60b 100644--- a/web/src/ee/features/multi-tenant-sso/types.ts+++ b/web/src/ee/features/multi-tenant-sso/types.ts@@ -225,6 +225,11 @@ export const CustomProviderSchema = base.extend({issuer: oidcIssuer,scope: z.string().nullish(),idToken: z.boolean().optional().default(true),+ // Read the profile from the userinfo endpoint for IdPs that keep+ // email/name out of the ID token. Not surfaced in the self-service form,+ // so left without a default: a default would materialize on every form+ // save and clobber a value set through the support endpoint.+ fetchUserInfo: z.boolean().optional(),allowDangerousEmailAccountLinking: z.boolean().optional().default(false),tokenEndpointAuthMethod: tokenEndpointAuthMethod,idTokenSignedResponseAlg: idTokenSignedResponseAlg,diff --git a/web/src/env.mjs b/web/src/env.mjsindex bb8a024c23..4c0ddf6642 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -267,6 +267,10 @@ export const env = createEnv({AUTH_CUSTOM_ID_TOKEN_SIGNED_RESPONSE_ALG: zIdTokenAlg,AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING: z.enum(["true", "false"]).optional(),AUTH_CUSTOM_ID_TOKEN: z.enum(["true", "false"]).optional().default("true"),+ AUTH_CUSTOM_FETCH_USERINFO: z+ .enum(["true", "false"])+ .optional()+ .default("false"),AUTH_WORKOS_CLIENT_ID: z.string().optional(),AUTH_WORKOS_CLIENT_SECRET: z.string().optional(),AUTH_WORKOS_ALLOW_ACCOUNT_LINKING: z.enum(["true", "false"]).optional(),@@ -839,6 +843,7 @@ export const env = createEnv({AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING:process.env.AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING,AUTH_CUSTOM_ID_TOKEN: process.env.AUTH_CUSTOM_ID_TOKEN,+ AUTH_CUSTOM_FETCH_USERINFO: process.env.AUTH_CUSTOM_FETCH_USERINFO,AUTH_WORKOS_CLIENT_ID: process.env.AUTH_WORKOS_CLIENT_ID,AUTH_WORKOS_CLIENT_SECRET: process.env.AUTH_WORKOS_CLIENT_SECRET,AUTH_WORKOS_ALLOW_ACCOUNT_LINKING:diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 05981b3897..354c2caa55 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -187,6 +187,7 @@ if (clientSecret: env.AUTH_CUSTOM_CLIENT_SECRET,issuer: env.AUTH_CUSTOM_ISSUER,idToken: env.AUTH_CUSTOM_ID_TOKEN === "true",+ fetchUserInfo: env.AUTH_CUSTOM_FETCH_USERINFO === "true",allowDangerousEmailAccountLinking:env.AUTH_CUSTOM_ALLOW_ACCOUNT_LINKING === "true",authorization: {