Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/docs/openapi-v2-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down
10 changes: 10 additions & 0 deletions apps/sim/app/api/auth/sso/register/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
19 changes: 19 additions & 0 deletions apps/sim/lib/api/contracts/v2/sso.test.ts
Original file line number Diff line number Diff line change
@@ -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)
}
)
})
10 changes: 4 additions & 6 deletions apps/sim/lib/api/contracts/v2/sso.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
11 changes: 4 additions & 7 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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')
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
const admission = await admitSsoUser.execute({
principal: {
kind: 'session',
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/lib/auth/lifecycle-audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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)
Expand Down
16 changes: 10 additions & 6 deletions apps/sim/lib/auth/sso/callback-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '/subscription/upgrade' },
{ path: '/sso/callback/:providerId' },
{ path: '/sso/callback/:providerId', routeProviderId: '' },
{ path: '/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()
})
})
34 changes: 20 additions & 14 deletions apps/sim/lib/auth/sso/callback-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, and `.`/`..` are dot-segments a URL collapses.
*/
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)\/([^/]+)$/

/**
Expand All @@ -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 === '/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])
}
6 changes: 6 additions & 0 deletions apps/sim/lib/auth/sso/provider-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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<string>([
...BUILT_IN_PROVIDER_IDS,
...configuration.reservedProviderIds,
Expand Down
12 changes: 10 additions & 2 deletions apps/sim/lib/auth/sso/registration-input.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
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(
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
SSO_PROVIDER_ID_PATTERN,
'Provider ID may only contain letters, numbers, dashes, underscores, periods, and colons (up to 128 characters)'
)

const ssoMappingSchema = z
.object({
Expand All @@ -17,7 +25,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),
Expand Down Expand Up @@ -45,7 +53,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),
Expand Down
Loading