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
6 changes: 6 additions & 0 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import { clampExpiryForSession } from '@/lib/auth/session-policy'
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 { configuredSsoPlugin } from '@/lib/auth/sso/plugin'
import {
Expand Down Expand Up @@ -386,6 +387,7 @@ export const auth = betterAuth({
throw new Error('Sign-ups from this email are not allowed.')
}
if (isHosted) await refuseDisposableAccountEmail(user.email, context?.path)
await refuseSsoCallbackEmailOutsideProviderDomain(user.email, context)
return { data: user }
},
after: async (user, context) => {
Expand Down Expand Up @@ -482,6 +484,10 @@ export const auth = betterAuth({
},
},
update: {
before: async (user, context) => {
if (user.email) await refuseSsoCallbackEmailOutsideProviderDomain(user.email, context)
return { data: user }
},
after: async (user) => {
if (user.banned) {
await disableUserResources(user.id)
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/auth/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ export const SSO_REQUIRED_ERROR_CODE = 'SSO_REQUIRED'
export const SSO_REQUIRED_MESSAGE =
'Your organization requires single sign-on. Sign in through your identity provider.'

/**
* How an SSO sign-in refused before any session exists identifies itself in the callback's error
* redirect, which the SSO sign-in page explains.
*/
export const SSO_PROVISIONING_FAILED_ERROR_CODE = 'sso_provisioning_failed'

/**
* How an account creation refused for a disposable email domain identifies itself, so the OAuth
* error page can name the way forward instead of telling the person to try again.
Expand Down
6 changes: 2 additions & 4 deletions apps/sim/lib/auth/sso/application/admit-sso-user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
workspace,
} from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { normalizeSSODomain } from '@sim/utils/sso-domain'
import { isEmailInSSODomain } from '@sim/utils/sso-domain'
import { normalizeEmail } from '@sim/utils/string'
import { and, eq, gt, isNull, sql } from 'drizzle-orm'
import { applySessionPolicyToNewMember } from '@/lib/auth/session-policy'
Expand Down Expand Up @@ -132,9 +132,7 @@ async function runAdmissionTransaction(
if (!linkedAccount) {
return { providerId, result: { kind: 'denied', reason: 'account-not-linked' } }
}
const userDomain = normalizeSSODomain(userRow.email)
const providerDomain = normalizeSSODomain(provider.domain)
if (!userDomain || !providerDomain || userDomain !== providerDomain) {
if (!isEmailInSSODomain(userRow.email, provider.domain)) {
return { providerId, result: { kind: 'denied', reason: 'domain-mismatch' } }
}

Expand Down
177 changes: 177 additions & 0 deletions apps/sim/lib/auth/sso/callback-email-domain.integration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { db } from '@sim/db'
import { account, ssoProvider, user } from '@sim/db/schema'
import { emailMailerMock } from '@sim/testing/mocks/email-mailer.mock'
import { emailTemplatesMock } from '@sim/testing/mocks/email-templates.mock'
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
import { generateId } from '@sim/utils/id'
import { eq, inArray } from 'drizzle-orm'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('@/lib/messaging/email/mailer', () => emailMailerMock)
vi.mock('@/components/emails', () => emailTemplatesMock)
vi.mock('@/lib/posthog/server', () => posthogServerMock)

const PROVIDER_DOMAIN = 'verified-tenant.test'

/**
* Drives a real OIDC sign-in through Better Auth's SSO callback against PostgreSQL, with a local
* IdP the tenant controls: whatever address its userinfo asserts is what the callback receives.
*/
describe('SSO callback user writes in PostgreSQL', () => {
let auth: typeof import('@/lib/auth/auth').auth
let idp: Server
let idpOrigin: string
let assertedEmail: string
let assertedSubject: string
let ownerId: string
let providerId: string
let createdEmails: string[]

beforeAll(async () => {
idp = createServer((request, response) => {
response.writeHead(200, { 'content-type': 'application/json' })
if (request.url === '/token') {
response.end(
JSON.stringify({
access_token: 'idp-access-token',
token_type: 'Bearer',
expires_in: 600,
})
)
return
}
response.end(JSON.stringify({ sub: assertedSubject, email: assertedEmail, name: 'Asserted' }))
})
await new Promise<void>((resolve) => idp.listen(0, '127.0.0.1', resolve))
idpOrigin = `http://127.0.0.1:${(idp.address() as AddressInfo).port}`
vi.stubEnv('SSO_ENABLED', 'true')
vi.stubEnv('TRUSTED_ORIGINS', idpOrigin)
;({ auth } = await import('@/lib/auth/auth'))
}, 90_000)

afterAll(async () => {
vi.unstubAllEnvs()
await new Promise((resolve) => idp.close(resolve))
})

beforeEach(async () => {
ownerId = generateId()
providerId = `tenant-idp-${generateId()}`
assertedSubject = generateId()
createdEmails = []
const now = new Date()
await db.insert(user).values({
id: ownerId,
name: 'Tenant administrator',
email: `${ownerId}@${PROVIDER_DOMAIN}`,
emailVerified: true,
createdAt: now,
updatedAt: now,
})
})

afterEach(async () => {
await db.delete(ssoProvider).where(eq(ssoProvider.providerId, providerId))
await db.delete(user).where(eq(user.id, ownerId))
if (createdEmails.length > 0) await db.delete(user).where(inArray(user.email, createdEmails))
})

async function registerProvider(options: { overrideUserInfo?: boolean } = {}) {
await db.insert(ssoProvider).values({
id: generateId(),
providerId,
userId: ownerId,
issuer: idpOrigin,
domain: PROVIDER_DOMAIN,
domainVerified: true,
oidcConfig: JSON.stringify({
issuer: idpOrigin,
clientId: 'tenant-client',
clientSecret: 'tenant-client-secret',
authorizationEndpoint: `${idpOrigin}/authorize`,
tokenEndpoint: `${idpOrigin}/token`,
userInfoEndpoint: `${idpOrigin}/userinfo`,
jwksEndpoint: `${idpOrigin}/jwks`,
pkce: false,
overrideUserInfo: options.overrideUserInfo ?? false,
}),
})
}

/** Starts the sign-in, then returns from the IdP to the callback as the browser would. */
async function signInAs(email: string) {
assertedEmail = email
createdEmails.push(email)
const started = await auth.handler(
new Request('http://localhost:3000/api/auth/sign-in/sso', {
method: 'POST',
headers: { 'content-type': 'application/json', origin: 'http://localhost:3000' },
body: JSON.stringify({ providerId, callbackURL: '/workspace', errorCallbackURL: '/sso' }),
})
)
expect(started.status).toBe(200)
const { url } = (await started.json()) as { url: string }
const state = new URL(url).searchParams.get('state') ?? ''
expect(state).not.toBe('')
const cookie = started.headers
.getSetCookie()
.map((value) => value.split(';')[0])
.join('; ')
const callback = new URL(`http://localhost:3000/api/auth/sso/callback/${providerId}`)
callback.searchParams.set('code', 'authorization-code')
callback.searchParams.set('state', state)
return auth.handler(new Request(callback, { headers: { cookie } }))
}

function redirectOf(response: Response) {
expect(response.status).toBe(302)
return new URL(response.headers.get('location') ?? '', 'http://localhost:3000')
}

async function userByEmail(email: string) {
const [row] = await db.select({ id: user.id }).from(user).where(eq(user.email, email))
return row
}

it('creates no user or account for an asserted address outside the verified domain', async () => {
await registerProvider()
const victim = `ceo-${generateId()}@unverified-victim.test`

const response = await signInAs(victim)

expect(redirectOf(response).searchParams.get('error')).toBe('sso_provisioning_failed')
expect(await userByEmail(victim)).toBeUndefined()
expect(
await db.select({ id: account.id }).from(account).where(eq(account.providerId, providerId))
).toHaveLength(0)
})

it('still creates the user for an asserted address inside the verified domain', async () => {
await registerProvider()
const member = `member-${generateId()}@${PROVIDER_DOMAIN}`

const response = await signInAs(member)

const redirect = redirectOf(response)
expect(redirect.pathname).toBe('/workspace')
expect(redirect.searchParams.has('error')).toBe(false)
expect(await userByEmail(member)).toBeDefined()
})

it('keeps a linked user’s email when the IdP later asserts an address outside the domain', async () => {
await registerProvider({ overrideUserInfo: true })
const member = `member-${generateId()}@${PROVIDER_DOMAIN}`
await signInAs(member)
const linked = await userByEmail(member)
expect(linked).toBeDefined()

const victim = `ceo-${generateId()}@unverified-victim.test`
const response = await signInAs(victim)

expect(redirectOf(response).searchParams.get('error')).toBe('sso_provisioning_failed')
expect(await userByEmail(member)).toEqual(linked)
expect(await userByEmail(victim)).toBeUndefined()
})
})
58 changes: 58 additions & 0 deletions apps/sim/lib/auth/sso/callback-email-domain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { createLogger } from '@sim/logger'
import { isEmailInSSODomain } from '@sim/utils/sso-domain'
import { type GenericEndpointContext, getCurrentAdapter } from 'better-auth'
import { APIError, getOAuthState } from 'better-auth/api'
import { SSO_PROVISIONING_FAILED_ERROR_CODE } from '@/lib/auth/constants'
import { isSsoCallbackPath, resolveSsoCallbackProviderId } from '@/lib/auth/sso/callback-provider'

const logger = createLogger('SsoCallbackEmailDomain')

/**
* Refuses writing a user email at an SSO callback unless the provider's domain is verified and the
* address belongs to it.
*
* Better Auth checks the provider's domain only before linking to an existing account. It creates a
* new user (and, with `overrideUserInfo`, rewrites a linked user's email) from whatever address the
* IdP asserts. The admission after-hook refuses such a sign-in, but only once the row has already
* been written, so the check has to run here, in the user write's `before` hook, to keep a tenant's
* IdP from claiming addresses in domains it never proved.
*
* @param context - the Better Auth endpoint context the write runs under; writes outside an SSO
* callback pass through untouched.
*/
export async function refuseSsoCallbackEmailOutsideProviderDomain(
email: string,
context: GenericEndpointContext | null
): Promise<void> {
if (!context || !isSsoCallbackPath(context.path)) return

const providerId = resolveSsoCallbackProviderId({
path: context.path,
routeProviderId: context.params?.providerId,
stateProviderId:
context.path === '/sso/callback' ? (await getOAuthState())?.ssoProviderId : undefined,
})
// The write runs inside Better Auth's transaction, so the lookup joins it through its adapter.
const adapter = await getCurrentAdapter(context.context.adapter)
const provider = providerId
? await adapter.findOne<{ domain: string; domainVerified: boolean }>({
model: 'ssoProvider',
where: [{ field: 'providerId', value: providerId }],
select: ['domain', 'domainVerified'],
})
: null

if (provider?.domainVerified && isEmailInSSODomain(email, provider.domain)) return

logger.warn('Refusing SSO user write for an email outside the provider domain', {
providerId,
path: context.path,
providerFound: Boolean(provider),
domainVerified: provider?.domainVerified ?? false,
})
// The callback redirects a refused creation with `message` and a refused update with `code`.
throw new APIError('FORBIDDEN', {
code: SSO_PROVISIONING_FAILED_ERROR_CODE,
message: SSO_PROVISIONING_FAILED_ERROR_CODE,
})
}
21 changes: 20 additions & 1 deletion packages/utils/src/sso-domain.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { normalizeSSODomain } from './sso-domain'
import { isEmailInSSODomain, normalizeSSODomain } from './sso-domain'

describe('normalizeSSODomain', () => {
it('strips wildcard, leading @, and email local part', () => {
Expand All @@ -21,3 +21,22 @@ describe('normalizeSSODomain', () => {
expect(normalizeSSODomain('company.123')).toBeNull()
})
})

describe('isEmailInSSODomain', () => {
it('matches an address whose mailbox domain is the provider domain', () => {
expect(isEmailInSSODomain('member@Company.com', 'company.com')).toBe(true)
})

it('reads the mailbox domain after the last @, never a domain-shaped local part', () => {
expect(isEmailInSSODomain('company.com/ceo@victim.test', 'company.com')).toBe(false)
expect(isEmailInSSODomain('company.com?ceo@victim.test', 'company.com')).toBe(false)
expect(isEmailInSSODomain('ceo@company.com?x@victim.test', 'company.com')).toBe(false)
expect(isEmailInSSODomain('ceo@company.com:443@victim.test', 'company.com')).toBe(false)
})

it('refuses a mailbox domain carrying anything but domain characters', () => {
expect(isEmailInSSODomain('ceo@company.com/x', 'company.com')).toBe(false)
expect(isEmailInSSODomain('ceo@company.com:443', 'company.com')).toBe(false)
expect(isEmailInSSODomain('company.com', 'company.com')).toBe(false)
})
})
15 changes: 15 additions & 0 deletions packages/utils/src/sso-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,18 @@ export function normalizeSSODomain(input: string): string | null {

return value
}

/**
* Whether an email address belongs to an SSO provider's domain, compared on the
* same canonical form {@link normalizeSSODomain} keys domain ownership on. The
* mailbox domain is the text after the last `@` and must hold only domain
* characters: {@link normalizeSSODomain} strips URL syntax first, so handing it
* the whole address would read `company.com/ceo@victim.test` as `company.com`.
*/
export function isEmailInSSODomain(email: string, domain: string): boolean {
const at = email.lastIndexOf('@')
const mailboxDomain = at > 0 ? email.slice(at + 1) : ''
if (!/^[a-z0-9.-]+$/i.test(mailboxDomain)) return false
const emailDomain = normalizeSSODomain(mailboxDomain)
return emailDomain !== null && emailDomain === normalizeSSODomain(domain)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}
Loading