Skip to content

Commit 473338a

Browse files
authored
fix(sso): admit callbacks under the provider id the plugin resolved (#10054)
* 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 * fix(sso): reject dot-segment provider ids and regenerate v2 openapi * docs(sso): document the shared provider id schema
1 parent a76c545 commit 473338a

10 files changed

Lines changed: 87 additions & 39 deletions

File tree

‎apps/docs/openapi-v2-resources.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24861,7 +24861,7 @@
2486124861
"providerId": {
2486224862
"type": "string",
2486324863
"minLength": 1,
24864-
"maxLength": 255,
24864+
"pattern": "^(?!\\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$",
2486524865
"description": "Globally unique provider ID; saving an existing provider replaces its supplied configuration."
2486624866
},
2486724867
"issuer": {
@@ -25002,7 +25002,7 @@
2500225002
"providerId": {
2500325003
"type": "string",
2500425004
"minLength": 1,
25005-
"maxLength": 255,
25005+
"pattern": "^(?!\\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$",
2500625006
"description": "Globally unique provider ID; saving an existing provider replaces its supplied configuration."
2500725007
},
2500825008
"issuer": {

‎apps/sim/app/api/auth/sso/register/route.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,16 @@ describe('POST /api/auth/sso/register', () => {
171171
expect((await res.json()).error).toContain('Organization ID is required')
172172
})
173173

174+
it.each(['acme%2Fidp', 'acme/idp', 'acme idp'])(
175+
'refuses a providerId that does not survive a URL path unchanged (%s)',
176+
async (providerId) => {
177+
queueMembers([{ organizationId: 'org1', role: 'owner' }])
178+
const res = await POST(request({ ...OIDC_BODY, providerId }))
179+
expect(res.status).toBe(400)
180+
expect((await res.json()).error).toContain('Provider ID may only contain')
181+
}
182+
)
183+
174184
it("refuses a second provider on a domain the caller's own org-less provider signs in", async () => {
175185
queueMembers([{ organizationId: 'org1', role: 'owner' }])
176186
queueProviders([
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { v2SaveSsoProviderContract } from '@/lib/api/contracts/v2/sso'
3+
4+
describe('v2 save SSO provider contract', () => {
5+
const body = {
6+
providerType: 'oidc',
7+
domain: 'acme.com',
8+
issuer: 'https://idp.acme.com',
9+
clientId: 'client-id',
10+
clientSecret: 'client-secret',
11+
}
12+
13+
it.each(['acme%2Fidp', 'acme/idp', 'acme idp', '.', '..'])(
14+
'rejects a provider ID that does not survive a URL path unchanged (%s)',
15+
(providerId) => {
16+
expect(v2SaveSsoProviderContract.body?.safeParse({ ...body, providerId }).success).toBe(false)
17+
}
18+
)
19+
})

‎apps/sim/lib/api/contracts/v2/sso.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
v2SortFields,
1313
v2TimestampSchema,
1414
} from '@/lib/api/contracts/v2/shared'
15-
import { ssoRegistrationInputSchema } from '@/lib/auth/sso/registration-input'
15+
import { ssoProviderIdSchema, ssoRegistrationInputSchema } from '@/lib/auth/sso/registration-input'
1616
import { addOrganizationDomainBodySchema } from '@/lib/organizations/domain-validation'
1717

1818
const v2SsoOrganizationParamsSchema = z
@@ -92,11 +92,9 @@ const mapping = z
9292
.default({ id: 'sub', email: 'email', name: 'name', image: 'picture' })
9393
.describe('Identity-provider claims mapped to user fields.')
9494
const shared = {
95-
providerId: nonEmptyIdSchema
96-
.max(255)
97-
.describe(
98-
'Globally unique provider ID; saving an existing provider replaces its supplied configuration.'
99-
),
95+
providerId: ssoProviderIdSchema.describe(
96+
'Globally unique provider ID; saving an existing provider replaces its supplied configuration.'
97+
),
10098
domain: z
10199
.string()
102100
.trim()

‎apps/sim/lib/auth/auth.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ import { getActiveOrganizationId } from '@/lib/auth/session-response'
7676
import { createSimAuthAdapter } from '@/lib/auth/sim-auth-adapter'
7777
import { admitSsoUser } from '@/lib/auth/sso/application/admit-sso-user'
7878
import { refuseSsoCallbackEmailOutsideProviderDomain } from '@/lib/auth/sso/callback-email-domain'
79-
import { resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider'
79+
import { isSsoCallbackPath, resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider'
8080
import { configuredSsoPlugin } from '@/lib/auth/sso/plugin'
8181
import {
8282
assertPersonalCheckoutAllowed,
@@ -1311,19 +1311,16 @@ export const auth = betterAuth({
13111311
routeProviderId: ctx.params?.providerId,
13121312
stateProviderId: oauthState?.ssoProviderId,
13131313
})
1314-
if (!providerId) {
1315-
await recordFinalAuthenticationResult()
1316-
return
1317-
}
1318-
13191314
const newSession = ctx.context.newSession
1320-
if (!newSession?.session || !newSession.user) {
1315+
if (!isSsoCallbackPath(ctx.path) || !newSession?.session || !newSession.user) {
13211316
await recordFinalAuthenticationResult(providerId)
13221317
return
13231318
}
13241319

13251320
let admissionErrorCode: string | null = null
13261321
try {
1322+
if (!providerId)
1323+
throw new Error('SSO callback minted a session without a resolvable provider')
13271324
const admission = await admitSsoUser.execute({
13281325
principal: {
13291326
kind: 'session',

‎apps/sim/lib/auth/lifecycle-audit.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { createLogger } from '@sim/logger'
55
import { isAPIError } from 'better-auth/api'
66
import { and, count, eq, gt, ne } from 'drizzle-orm'
77
import { isSignInProviderAllowed } from '@/lib/auth/constants'
8-
import { isSsoCallbackPath } from '@/lib/auth/sso/callback-provider'
8+
import { isSsoCallbackPath, SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider'
99

1010
const logger = createLogger('AuthenticationAudit')
1111

@@ -127,7 +127,7 @@ export async function recordAuthenticationAudit(input: AuthenticationAuditInput)
127127
if (!subject && outcome !== 'failure') return
128128
let organizationId = subject?.organizationId
129129
let providerId = isSignInProviderAllowed(input.providerId) ? input.providerId : undefined
130-
if (method === 'sso' && input.providerId && /^[a-zA-Z0-9_.:-]{1,128}$/.test(input.providerId)) {
130+
if (method === 'sso' && input.providerId && SSO_PROVIDER_ID_PATTERN.test(input.providerId)) {
131131
const [provider] = await db
132132
.select({ organizationId: ssoProvider.organizationId, providerId: ssoProvider.providerId })
133133
.from(ssoProvider)

‎apps/sim/lib/auth/sso/callback-provider.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,21 @@ describe('SSO callback provider resolution', () => {
1919
).toBe('acme-shared-sso')
2020
})
2121

22-
it('supports a concrete callback path when the runtime exposes it', () => {
23-
expect(resolveSsoCallbackProviderId({ path: '/sso/callback/acme%2Dsso' })).toBe('acme-sso')
22+
it.each([
23+
{ path: '/sso/callback/:providerId', routeProviderId: 'acme%2Fidp', expected: 'acme%2Fidp' },
24+
{ path: '/sso/callback/:providerId', routeProviderId: 'acme%2Dsso', expected: 'acme%2Dsso' },
25+
{ path: '/sso/callback/acme%2Fidp', expected: 'acme%2Fidp' },
26+
{ path: '/sso/callback/acme%2Dsso', expected: 'acme%2Dsso' },
27+
])('returns the undecoded id the plugin looked up for $path', ({ expected, ...context }) => {
28+
expect(resolveSsoCallbackProviderId(context)).toBe(expected)
2429
})
2530

2631
it.each([
2732
{ path: '/subscription/upgrade' },
2833
{ path: '/sso/callback/:providerId' },
34+
{ path: '/sso/callback/:providerId', routeProviderId: '' },
2935
{ path: '/sso/callback', stateProviderId: null },
30-
{ path: '/sso/callback/acme%2Fsso' },
31-
{ path: '/sso/callback/%E0%A4%A' },
32-
])('rejects a callback context without a safe provider identity', (context) => {
33-
expect(resolveSsoCallbackProviderId(context)).toBeNull()
36+
])('returns no provider for a context without a provider identity', (context) => {
37+
expect(resolveSsoCallbackProviderId(context)).toBeUndefined()
3438
})
3539
})

‎apps/sim/lib/auth/sso/callback-provider.ts‎

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ const DYNAMIC_SSO_CALLBACK_PATHS = new Set([
44
'/sso/saml2/sp/acs/:providerId',
55
])
66

7+
/**
8+
* Provider IDs travel unescaped in callback URLs (`/sso/callback/{providerId}`),
9+
* so they are limited to characters that survive a URL path unchanged. A
10+
* percent-escape would let the plugin and the admission hook disagree on which
11+
* provider a sign-in came from, and `.`/`..` are dot-segments a URL collapses.
12+
*/
13+
export const SSO_PROVIDER_ID_PATTERN = /^(?!\.{1,2}$)[a-zA-Z0-9_.:-]{1,128}$/
14+
715
const CONCRETE_SSO_CALLBACK_PATH = /^\/sso\/(?:callback|saml2\/callback|saml2\/sp\/acs)\/([^/]+)$/
816

917
/**
@@ -25,29 +33,27 @@ export interface SsoCallbackProviderContext {
2533
stateProviderId?: unknown
2634
}
2735

28-
function decodeProviderId(value: unknown): string | null {
29-
if (typeof value !== 'string' || !value) return null
30-
try {
31-
const providerId = decodeURIComponent(value)
32-
return providerId && !providerId.includes('/') && !providerId.includes('\\') ? providerId : null
33-
} catch {
34-
return null
35-
}
36+
function providerIdFrom(value: unknown): string | undefined {
37+
return typeof value === 'string' && value ? value : undefined
3638
}
3739

38-
/** Resolves the provider identity from Better Auth's callback route context. */
40+
/**
41+
* Resolves the provider identity from Better Auth's callback route context.
42+
* Returns the value exactly as the SSO plugin used it for its own provider
43+
* lookup and account linking (route params are not percent-decoded), so the
44+
* admission check always names the provider that actually minted the session.
45+
*/
3946
export function resolveSsoCallbackProviderId({
4047
path,
4148
routeProviderId,
4249
stateProviderId,
43-
}: SsoCallbackProviderContext): string | null {
50+
}: SsoCallbackProviderContext): string | undefined {
4451
if (DYNAMIC_SSO_CALLBACK_PATHS.has(path)) {
45-
return decodeProviderId(routeProviderId)
52+
return providerIdFrom(routeProviderId)
4653
}
4754
if (path === '/sso/callback') {
48-
return decodeProviderId(stateProviderId)
55+
return providerIdFrom(stateProviderId)
4956
}
5057

51-
const concreteMatch = CONCRETE_SSO_CALLBACK_PATH.exec(path)
52-
return decodeProviderId(concreteMatch?.[1])
58+
return providerIdFrom(CONCRETE_SSO_CALLBACK_PATH.exec(path)?.[1])
5359
}

‎apps/sim/lib/auth/sso/provider-repository.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { filterUndefined, sortObjectKeysDeep, toRecord } from '@sim/utils/object
1111
import { APIError } from 'better-auth/api'
1212
import { and, count, eq } from 'drizzle-orm'
1313
import type { auth } from '@/lib/auth'
14+
import { SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider'
1415
import type { SsoProviderConfig } from '@/lib/auth/sso/provider-adapter'
1516
import { lockSsoProvider } from '@/lib/auth/sso/provider-lock'
1617
import type { DbOrTx } from '@/lib/db/types'
@@ -150,6 +151,11 @@ export function createSsoProviderRepository(
150151
message: 'Provider organization does not match its authorized scope',
151152
})
152153
validateConfig(body)
154+
if (!SSO_PROVIDER_ID_PATTERN.test(body.providerId))
155+
throw new APIError('BAD_REQUEST', {
156+
message:
157+
'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons',
158+
})
153159
const reserved = new Set<string>([
154160
...BUILT_IN_PROVIDER_IDS,
155161
...configuration.reservedProviderIds,

‎apps/sim/lib/auth/sso/registration-input.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
11
import { z } from 'zod'
2+
import { requiredFieldSchema } from '@/lib/api/contracts/primitives'
3+
import { SSO_PROVIDER_ID_PATTERN } from '@/lib/auth/sso/callback-provider'
4+
5+
/** SSO provider ID limited to {@link SSO_PROVIDER_ID_PATTERN}, shared by every provider write. */
6+
export const ssoProviderIdSchema = requiredFieldSchema('Provider ID is required').regex(
7+
SSO_PROVIDER_ID_PATTERN,
8+
'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons (up to 128 characters)'
9+
)
210

311
const ssoMappingSchema = z
412
.object({
@@ -17,7 +25,7 @@ const ssoMappingSchema = z
1725
export const ssoRegistrationInputSchema = z.discriminatedUnion('providerType', [
1826
z.object({
1927
providerType: z.literal('oidc'),
20-
providerId: z.string().min(1, 'Provider ID is required').max(255),
28+
providerId: ssoProviderIdSchema,
2129
issuer: z.string().url('Issuer must be a valid URL'),
2230
domain: z.string().min(1, 'Domain is required'),
2331
organizationId: z.string().min(1).max(255),
@@ -45,7 +53,7 @@ export const ssoRegistrationInputSchema = z.discriminatedUnion('providerType', [
4553
}),
4654
z.object({
4755
providerType: z.literal('saml'),
48-
providerId: z.string().min(1, 'Provider ID is required').max(255),
56+
providerId: ssoProviderIdSchema,
4957
issuer: z.string().url('Issuer must be a valid URL'),
5058
domain: z.string().min(1, 'Domain is required'),
5159
organizationId: z.string().min(1).max(255),

0 commit comments

Comments
 (0)