From ee745f9ebef9997aa1bfc180ad8e0be1b6b7c3b3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 14 Nov 2026 14:06:27 -0800 Subject: [PATCH 1/3] fix(sso): admit callbacks under the provider id the plugin resolved The SSO plugin looks a callback's provider up by the raw route segment, while the admission hook percent-decoded it and dropped anything containing a separator. A provider id like `acme%2Fidp` therefore minted a session the hook could not name, so admission (domain check, JIT/seat policy, audit) never ran. - Resolve the callback provider from the exact, undecoded value the plugin used - Fail closed when an SSO callback mints a session without a resolvable provider - Restrict provider ids to URL-path-safe characters on v1, v2, and the repository write --- .../app/api/auth/sso/register/route.test.ts | 10 ++++++ apps/sim/lib/api/contracts/v2/sso.test.ts | 19 +++++++++++ apps/sim/lib/api/contracts/v2/sso.ts | 10 +++--- apps/sim/lib/auth/auth.ts | 11 +++--- apps/sim/lib/auth/lifecycle-audit.ts | 4 +-- .../lib/auth/sso/callback-provider.test.ts | 16 +++++---- apps/sim/lib/auth/sso/callback-provider.ts | 34 +++++++++++-------- apps/sim/lib/auth/sso/provider-repository.ts | 6 ++++ apps/sim/lib/auth/sso/registration-input.ts | 11 ++++-- 9 files changed, 84 insertions(+), 37 deletions(-) create mode 100644 apps/sim/lib/api/contracts/v2/sso.test.ts diff --git a/apps/sim/app/api/auth/sso/register/route.test.ts b/apps/sim/app/api/auth/sso/register/route.test.ts index 382848e5449..5c356b797cb 100644 --- a/apps/sim/app/api/auth/sso/register/route.test.ts +++ b/apps/sim/app/api/auth/sso/register/route.test.ts @@ -171,6 +171,16 @@ describe('POST /api/auth/sso/register', () => { expect((await res.json()).error).toContain('Organization ID is required') }) + it.each(['acme%2Fidp', 'acme/idp', 'acme idp'])( + 'refuses a providerId that does not survive a URL path unchanged (%s)', + async (providerId) => { + queueMembers([{ organizationId: 'org1', role: 'owner' }]) + const res = await POST(request({ ...OIDC_BODY, providerId })) + expect(res.status).toBe(400) + expect((await res.json()).error).toContain('Provider ID may only contain') + } + ) + it("refuses a second provider on a domain the caller's own org-less provider signs in", async () => { queueMembers([{ organizationId: 'org1', role: 'owner' }]) queueProviders([ diff --git a/apps/sim/lib/api/contracts/v2/sso.test.ts b/apps/sim/lib/api/contracts/v2/sso.test.ts new file mode 100644 index 00000000000..e7cd6ceba95 --- /dev/null +++ b/apps/sim/lib/api/contracts/v2/sso.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { v2SaveSsoProviderContract } from '@/lib/api/contracts/v2/sso' + +describe('v2 save SSO provider contract', () => { + const body = { + providerType: 'oidc', + domain: 'acme.com', + issuer: 'https://idp.acme.com', + clientId: 'client-id', + clientSecret: 'client-secret', + } + + it.each(['acme%2Fidp', 'acme/idp', 'acme idp'])( + 'rejects a provider ID that does not survive a URL path unchanged (%s)', + (providerId) => { + expect(v2SaveSsoProviderContract.body.safeParse({ ...body, providerId }).success).toBe(false) + } + ) +}) diff --git a/apps/sim/lib/api/contracts/v2/sso.ts b/apps/sim/lib/api/contracts/v2/sso.ts index 44a0152a388..817c0540c53 100644 --- a/apps/sim/lib/api/contracts/v2/sso.ts +++ b/apps/sim/lib/api/contracts/v2/sso.ts @@ -12,7 +12,7 @@ import { v2SortFields, v2TimestampSchema, } from '@/lib/api/contracts/v2/shared' -import { ssoRegistrationInputSchema } from '@/lib/auth/sso/registration-input' +import { ssoProviderIdSchema, ssoRegistrationInputSchema } from '@/lib/auth/sso/registration-input' import { addOrganizationDomainBodySchema } from '@/lib/organizations/domain-validation' const v2SsoOrganizationParamsSchema = z @@ -92,11 +92,9 @@ const mapping = z .default({ id: 'sub', email: 'email', name: 'name', image: 'picture' }) .describe('Identity-provider claims mapped to user fields.') const shared = { - providerId: nonEmptyIdSchema - .max(255) - .describe( - 'Globally unique provider ID; saving an existing provider replaces its supplied configuration.' - ), + providerId: ssoProviderIdSchema.describe( + 'Globally unique provider ID; saving an existing provider replaces its supplied configuration.' + ), domain: z .string() .trim() diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 658d48d3cc1..88fb804a718 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -76,7 +76,7 @@ import { getActiveOrganizationId } from '@/lib/auth/session-response' import { createSimAuthAdapter } from '@/lib/auth/sim-auth-adapter' import { admitSsoUser } from '@/lib/auth/sso/application/admit-sso-user' import { refuseSsoCallbackEmailOutsideProviderDomain } from '@/lib/auth/sso/callback-email-domain' -import { resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider' +import { isSsoCallbackPath, resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider' import { configuredSsoPlugin } from '@/lib/auth/sso/plugin' import { assertPersonalCheckoutAllowed, @@ -1311,19 +1311,16 @@ export const auth = betterAuth({ routeProviderId: ctx.params?.providerId, stateProviderId: oauthState?.ssoProviderId, }) - if (!providerId) { - await recordFinalAuthenticationResult() - return - } - const newSession = ctx.context.newSession - if (!newSession?.session || !newSession.user) { + if (!isSsoCallbackPath(ctx.path) || !newSession?.session || !newSession.user) { await recordFinalAuthenticationResult(providerId) return } let admissionErrorCode: string | null = null try { + if (!providerId) + throw new Error('SSO callback minted a session without a resolvable provider') const admission = await admitSsoUser.execute({ principal: { kind: 'session', diff --git a/apps/sim/lib/auth/lifecycle-audit.ts b/apps/sim/lib/auth/lifecycle-audit.ts index a1f015c2074..29253fd6717 100644 --- a/apps/sim/lib/auth/lifecycle-audit.ts +++ b/apps/sim/lib/auth/lifecycle-audit.ts @@ -5,7 +5,7 @@ import { createLogger } from '@sim/logger' import { isAPIError } from 'better-auth/api' import { and, count, eq, gt, ne } from 'drizzle-orm' import { isSignInProviderAllowed } from '@/lib/auth/constants' -import { isSsoCallbackPath } from '@/lib/auth/sso/callback-provider' +import { isSsoCallbackPath, SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider' const logger = createLogger('AuthenticationAudit') @@ -127,7 +127,7 @@ export async function recordAuthenticationAudit(input: AuthenticationAuditInput) if (!subject && outcome !== 'failure') return let organizationId = subject?.organizationId let providerId = isSignInProviderAllowed(input.providerId) ? input.providerId : undefined - if (method === 'sso' && input.providerId && /^[a-zA-Z0-9_.:-]{1,128}$/.test(input.providerId)) { + if (method === 'sso' && input.providerId && SSO_PROVIDER_ID_PATTERN.test(input.providerId)) { const [provider] = await db .select({ organizationId: ssoProvider.organizationId, providerId: ssoProvider.providerId }) .from(ssoProvider) diff --git a/apps/sim/lib/auth/sso/callback-provider.test.ts b/apps/sim/lib/auth/sso/callback-provider.test.ts index cf2225b7993..15390e7adb9 100644 --- a/apps/sim/lib/auth/sso/callback-provider.test.ts +++ b/apps/sim/lib/auth/sso/callback-provider.test.ts @@ -19,17 +19,21 @@ describe('SSO callback provider resolution', () => { ).toBe('acme-shared-sso') }) - it('supports a concrete callback path when the runtime exposes it', () => { - expect(resolveSsoCallbackProviderId({ path: '/sso/callback/acme%2Dsso' })).toBe('acme-sso') + it.each([ + { path: '/sso/callback/:providerId', routeProviderId: 'acme%2Fidp', expected: 'acme%2Fidp' }, + { path: '/sso/callback/:providerId', routeProviderId: 'acme%2Dsso', expected: 'acme%2Dsso' }, + { path: '/sso/callback/acme%2Fidp', expected: 'acme%2Fidp' }, + { path: '/sso/callback/acme%2Dsso', expected: 'acme%2Dsso' }, + ])('returns the undecoded id the plugin looked up for $path', ({ expected, ...context }) => { + expect(resolveSsoCallbackProviderId(context)).toBe(expected) }) it.each([ { path: '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/subscription/upgrade' }, { path: '/sso/callback/:providerId' }, + { path: '/sso/callback/:providerId', routeProviderId: '' }, { path: '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/sso/callback', stateProviderId: null }, - { path: '/sso/callback/acme%2Fsso' }, - { path: '/sso/callback/%E0%A4%A' }, - ])('rejects a callback context without a safe provider identity', (context) => { - expect(resolveSsoCallbackProviderId(context)).toBeNull() + ])('returns no provider for a context without a provider identity', (context) => { + expect(resolveSsoCallbackProviderId(context)).toBeUndefined() }) }) diff --git a/apps/sim/lib/auth/sso/callback-provider.ts b/apps/sim/lib/auth/sso/callback-provider.ts index 733fd6cd297..3f193a4ce4d 100644 --- a/apps/sim/lib/auth/sso/callback-provider.ts +++ b/apps/sim/lib/auth/sso/callback-provider.ts @@ -4,6 +4,14 @@ const DYNAMIC_SSO_CALLBACK_PATHS = new Set([ '/sso/saml2/sp/acs/:providerId', ]) +/** + * Provider IDs travel unescaped in callback URLs (`/sso/callback/{providerId}`), + * so they are limited to characters that survive a URL path unchanged. A + * percent-escape would let the plugin and the admission hook disagree on which + * provider a sign-in came from. + */ +export const SSO_PROVIDER_ID_PATTERN = /^[a-zA-Z0-9_.:-]{1,128}$/ + const CONCRETE_SSO_CALLBACK_PATH = /^\/sso\/(?:callback|saml2\/callback|saml2\/sp\/acs)\/([^/]+)$/ /** @@ -25,29 +33,27 @@ export interface SsoCallbackProviderContext { stateProviderId?: unknown } -function decodeProviderId(value: unknown): string | null { - if (typeof value !== 'string' || !value) return null - try { - const providerId = decodeURIComponent(value) - return providerId && !providerId.includes('/') && !providerId.includes('\\') ? providerId : null - } catch { - return null - } +function providerIdFrom(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined } -/** Resolves the provider identity from Better Auth's callback route context. */ +/** + * Resolves the provider identity from Better Auth's callback route context. + * Returns the value exactly as the SSO plugin used it for its own provider + * lookup and account linking (route params are not percent-decoded), so the + * admission check always names the provider that actually minted the session. + */ export function resolveSsoCallbackProviderId({ path, routeProviderId, stateProviderId, -}: SsoCallbackProviderContext): string | null { +}: SsoCallbackProviderContext): string | undefined { if (DYNAMIC_SSO_CALLBACK_PATHS.has(path)) { - return decodeProviderId(routeProviderId) + return providerIdFrom(routeProviderId) } if (path === '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/sso/callback') { - return decodeProviderId(stateProviderId) + return providerIdFrom(stateProviderId) } - const concreteMatch = CONCRETE_SSO_CALLBACK_PATH.exec(path) - return decodeProviderId(concreteMatch?.[1]) + return providerIdFrom(CONCRETE_SSO_CALLBACK_PATH.exec(path)?.[1]) } diff --git a/apps/sim/lib/auth/sso/provider-repository.ts b/apps/sim/lib/auth/sso/provider-repository.ts index 06e377cb366..d442f9105a6 100644 --- a/apps/sim/lib/auth/sso/provider-repository.ts +++ b/apps/sim/lib/auth/sso/provider-repository.ts @@ -11,6 +11,7 @@ import { filterUndefined, sortObjectKeysDeep, toRecord } from '@sim/utils/object import { APIError } from 'better-auth/api' import { and, count, eq } from 'drizzle-orm' import type { auth } from '@/lib/auth' +import { SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider' import type { SsoProviderConfig } from '@/lib/auth/sso/provider-adapter' import { lockSsoProvider } from '@/lib/auth/sso/provider-lock' import type { DbOrTx } from '@/lib/db/types' @@ -150,6 +151,11 @@ export function createSsoProviderRepository( message: 'Provider organization does not match its authorized scope', }) validateConfig(body) + if (!SSO_PROVIDER_ID_PATTERN.test(body.providerId)) + throw new APIError('BAD_REQUEST', { + message: + 'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons', + }) const reserved = new Set([ ...BUILT_IN_PROVIDER_IDS, ...configuration.reservedProviderIds, diff --git a/apps/sim/lib/auth/sso/registration-input.ts b/apps/sim/lib/auth/sso/registration-input.ts index 8ffab48cf41..062edd2f927 100644 --- a/apps/sim/lib/auth/sso/registration-input.ts +++ b/apps/sim/lib/auth/sso/registration-input.ts @@ -1,4 +1,11 @@ import { z } from 'zod' +import { requiredFieldSchema } from '@/lib/api/contracts/primitives' +import { SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider' + +export const ssoProviderIdSchema = requiredFieldSchema('Provider ID is required').regex( + SSO_PROVIDER_ID_PATTERN, + 'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons (up to 128 characters)' +) const ssoMappingSchema = z .object({ @@ -17,7 +24,7 @@ const ssoMappingSchema = z export const ssoRegistrationInputSchema = z.discriminatedUnion('providerType', [ z.object({ providerType: z.literal('oidc'), - providerId: z.string().min(1, 'Provider ID is required').max(255), + providerId: ssoProviderIdSchema, issuer: z.string().url('Issuer must be a valid URL'), domain: z.string().min(1, 'Domain is required'), organizationId: z.string().min(1).max(255), @@ -45,7 +52,7 @@ export const ssoRegistrationInputSchema = z.discriminatedUnion('providerType', [ }), z.object({ providerType: z.literal('saml'), - providerId: z.string().min(1, 'Provider ID is required').max(255), + providerId: ssoProviderIdSchema, issuer: z.string().url('Issuer must be a valid URL'), domain: z.string().min(1, 'Domain is required'), organizationId: z.string().min(1).max(255), From 03312122316fb083d10fb62d8b973f8208823906 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 14 Nov 2026 14:18:33 -0800 Subject: [PATCH 2/3] fix(sso): reject dot-segment provider ids and regenerate v2 openapi --- apps/docs/openapi-v2-resources.json | 4 ++-- apps/sim/lib/api/contracts/v2/sso.test.ts | 4 ++-- apps/sim/lib/auth/sso/callback-provider.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 367c869b0ad..5350eac6cd8 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -24861,7 +24861,7 @@ "providerId": { "type": "string", "minLength": 1, - "maxLength": 255, + "pattern": "^(?!\\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$", "description": "Globally unique provider ID; saving an existing provider replaces its supplied configuration." }, "issuer": { @@ -25002,7 +25002,7 @@ "providerId": { "type": "string", "minLength": 1, - "maxLength": 255, + "pattern": "^(?!\\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$", "description": "Globally unique provider ID; saving an existing provider replaces its supplied configuration." }, "issuer": { diff --git a/apps/sim/lib/api/contracts/v2/sso.test.ts b/apps/sim/lib/api/contracts/v2/sso.test.ts index e7cd6ceba95..c67ac214090 100644 --- a/apps/sim/lib/api/contracts/v2/sso.test.ts +++ b/apps/sim/lib/api/contracts/v2/sso.test.ts @@ -10,10 +10,10 @@ describe('v2 save SSO provider contract', () => { clientSecret: 'client-secret', } - it.each(['acme%2Fidp', 'acme/idp', 'acme idp'])( + it.each(['acme%2Fidp', 'acme/idp', 'acme idp', '.', '..'])( 'rejects a provider ID that does not survive a URL path unchanged (%s)', (providerId) => { - expect(v2SaveSsoProviderContract.body.safeParse({ ...body, providerId }).success).toBe(false) + expect(v2SaveSsoProviderContract.body?.safeParse({ ...body, providerId }).success).toBe(false) } ) }) diff --git a/apps/sim/lib/auth/sso/callback-provider.ts b/apps/sim/lib/auth/sso/callback-provider.ts index 3f193a4ce4d..64ab67a8dd5 100644 --- a/apps/sim/lib/auth/sso/callback-provider.ts +++ b/apps/sim/lib/auth/sso/callback-provider.ts @@ -8,9 +8,9 @@ const DYNAMIC_SSO_CALLBACK_PATHS = new Set([ * Provider IDs travel unescaped in callback URLs (`/sso/callback/{providerId}`), * so they are limited to characters that survive a URL path unchanged. A * percent-escape would let the plugin and the admission hook disagree on which - * provider a sign-in came from. + * provider a sign-in came from, and `.`/`..` are dot-segments a URL collapses. */ -export const SSO_PROVIDER_ID_PATTERN = /^[a-zA-Z0-9_.:-]{1,128}$/ +export const SSO_PROVIDER_ID_PATTERN = /^(?!\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$/ const CONCRETE_SSO_CALLBACK_PATH = /^\/sso\/(?:callback|saml2\/callback|saml2\/sp\/acs)\/([^/]+)$/ From 64f2e8964561e5476286d353b3ab0b6e46526489 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 14 Nov 2026 14:29:17 -0800 Subject: [PATCH 3/3] docs(sso): document the shared provider id schema --- apps/sim/lib/auth/sso/registration-input.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/sim/lib/auth/sso/registration-input.ts b/apps/sim/lib/auth/sso/registration-input.ts index 062edd2f927..2ac535aeb91 100644 --- a/apps/sim/lib/auth/sso/registration-input.ts +++ b/apps/sim/lib/auth/sso/registration-input.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { requiredFieldSchema } from '@/lib/api/contracts/primitives' import { SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider' +/** SSO provider ID limited to {@link SSO_PROVIDER_ID_PATTERN}, shared by every provider write. */ export const ssoProviderIdSchema = requiredFieldSchema('Provider ID is required').regex( SSO_PROVIDER_ID_PATTERN, 'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons (up to 128 characters)'