🪢 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
fix(sso): strip openid scope on custom save when idToken is false (#13659)
Steffen Schmitzd8d1fe232eba
diff --git a/web/src/__tests__/server/ssoConfigRouter.servertest.ts b/web/src/__tests__/server/ssoConfigRouter.servertest.tsindex 5ae27be4a7..413d723143 100644--- a/web/src/__tests__/server/ssoConfigRouter.servertest.ts+++ b/web/src/__tests__/server/ssoConfigRouter.servertest.ts@@ -430,6 +430,84 @@ describe("ssoConfigRouter.save", () => {);});+ it("normalizes the stored scope when custom idToken is false", async () => {+ // The self-service form doesn't surface `scope`, so a fresh custom config+ // with idToken: false would otherwise inherit the runtime default+ // `openid email profile` and fail at sign-in with+ // "id_token detected in the response..." Persist a stripped scope.+ const { org, caller } = await prepare();+ const domain = `scope-strip-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);++ await caller.ssoConfig.save({+ orgId: org.id,+ payload: sampleCustomPayload(domain, false),+ });++ const stored = await prisma.ssoConfig.findUniqueOrThrow({+ where: { domain },+ });+ expect((stored.authConfig as Record<string, unknown>).scope).toBe(+ "email profile",+ );+ });++ it("keeps the OIDC scope when custom idToken is true", async () => {+ const { org, caller } = await prepare();+ const domain = `scope-keep-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);++ await caller.ssoConfig.save({+ orgId: org.id,+ payload: sampleCustomPayload(domain, true),+ });++ const stored = await prisma.ssoConfig.findUniqueOrThrow({+ where: { domain },+ });+ // No `scope` should be set; NextAuth falls back to the OIDC default at runtime.+ expect(+ (stored.authConfig as Record<string, unknown>).scope,+ ).toBeUndefined();+ });++ it("strips openid from a preserved legacy scope when idToken is flipped to false", async () => {+ // Mirrors the production trigger: a config first written via the legacy+ // admin endpoint with `scope: "openid email profile"`, then re-saved+ // through the self-service UI with idToken toggled off. The merge keeps+ // the legacy scope, so the normalizer has to strip `openid` from it.+ const { org, caller } = await prepare();+ const domain = `legacy-merge-${uuidv4().slice(0, 8)}.com`;+ await addVerifiedDomain(org.id, domain);++ await prisma.ssoConfig.create({+ data: {+ domain,+ authProvider: "custom",+ authConfig: {+ name: "Legacy Custom",+ clientId: "legacy-client",+ clientSecret: encrypt("legacy-secret"),+ issuer: "https://example.okta.com",+ scope: "openid email profile",+ idToken: true,+ },+ },+ });++ await caller.ssoConfig.save({+ orgId: org.id,+ payload: sampleCustomPayload(domain, false),+ });++ const stored = await prisma.ssoConfig.findUniqueOrThrow({+ where: { domain },+ });+ const cfg = stored.authConfig as Record<string, unknown>;+ expect(cfg.idToken).toBe(false);+ expect(cfg.scope).toBe("email profile");+ });+it("resets authConfig fields when the provider changes", async () => {// Switching providers is an explicit reset — Custom-only fields like// `name`/`scope` aren't valid in another provider's schema and shouldn'tdiff --git a/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts b/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.tsindex de426ac462..79ec28139f 100644--- a/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts+++ b/web/src/ee/features/multi-tenant-sso/server/ssoConfigRouter.ts@@ -33,6 +33,23 @@ const maskAuthConfig = (return rest;};+// Drop the OIDC `openid` token from a scope string and fall back to a baseline+// OAuth2 scope when stripping would otherwise leave the IdP with no claims to+// release. See the call site in `save` for the full rationale.+const withOauth2Scope = (+ authConfig: Record<string, unknown>,+): Record<string, unknown> => {+ const requestedScope =+ typeof authConfig.scope === "string"+ ? authConfig.scope+ : "openid email profile";+ const stripped = requestedScope+ .split(/\s+/)+ .filter((token) => token.length > 0 && token !== "openid")+ .join(" ");+ return { ...authConfig, scope: stripped || "email profile" };+};+export const ssoConfigRouter = createTRPCRouter({get: protectedOrganizationProcedure.input(z.object({ orgId: z.string() }))@@ -135,11 +152,29 @@ export const ssoConfigRouter = createTRPCRouter({}: authConfig;- const encryptedAuthConfig = mergedAuthConfig+ // NextAuth picks between client.callback() (OIDC) and+ // client.oauthCallback() (OAuth2-only) based on the provider's+ // `idToken` flag. openid-client's oauthCallback throws+ // "id_token detected in the response, you must use client.callback()+ // instead of client.oauthCallback()"+ // mid-flow if the IdP returns an id_token — which any OIDC server does+ // whenever `openid` is in scope. The self-service form only exposes+ // `idToken` (not `scope`), so admins toggling `idToken: false` would+ // otherwise pair it with our default `openid email profile` scope and+ // hit this contradiction. Normalize the stored scope here so the+ // runtime callback flow matches the IdP response shape.+ const normalizedAuthConfig =+ authProvider === "custom" &&+ mergedAuthConfig &&+ (mergedAuthConfig as { idToken?: unknown }).idToken === false+ ? withOauth2Scope(mergedAuthConfig as Record<string, unknown>)+ : mergedAuthConfig;++ const encryptedAuthConfig = normalizedAuthConfig? {- ...mergedAuthConfig,+ ...normalizedAuthConfig,clientSecret: encrypt(- (mergedAuthConfig as { clientSecret: string }).clientSecret,+ (normalizedAuthConfig as { clientSecret: string }).clientSecret,),}: null;